package com.cpms.project.process.controller;

import java.io.IOException;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import com.alibaba.fastjson2.JSON;
import com.cpms.common.utils.file.ExcelUtils;
import com.cpms.common.utils.DateUtils;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.enums.BusinessType;
import com.cpms.project.process.domain.TSisRecord;
import com.cpms.project.process.service.ITSisRecordService;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.common.core.page.TableDataInfo;

/**
 * sis RecordController
 * 
 * @author admin
 * @date 2024-05-22
 */
@RestController
@RequestMapping("/process/sisRecord")
public class TSisRecordController extends BaseController
{
    @Autowired
    private ITSisRecordService tSisRecordService;

    /**
     * 查询sis Record列表
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSisRecord tSisRecord)
    {
        startPage();
        List<TSisRecord> list = tSisRecordService.selectTSisRecordList(tSisRecord);
        return getDataTable(list);
    }

    /**
     * 导出sis Record列表
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:export')")
    @Log(title = "sis Record", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TSisRecord tSisRecord)
    {
        List<TSisRecord> list = tSisRecordService.selectTSisRecordList(tSisRecord);
        ExcelUtil<TSisRecord> util = new ExcelUtil<TSisRecord>(TSisRecord.class);
        util.exportExcel(response, list, "sis Record数据");
    }

    /**
     * 获取sis Record详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tSisRecordService.selectTSisRecordById(id));
    }

    /**
     * 新增sis Record
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:add')")
    @Log(title = "sis Record", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSisRecord tSisRecord)
    {
        tSisRecord.setCreaterCode(getUserId().toString());
        tSisRecord.setCreatedate(new Date());
        return toAjax(tSisRecordService.insertTSisRecord(tSisRecord));
    }

    /**
     * 修改sis Record
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:edit')")
    @Log(title = "sis Record", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSisRecord tSisRecord)
    {
        tSisRecord.setUpdaterCode(getUserId().toString());
        tSisRecord.setUpdatedate(new Date());
        return toAjax(tSisRecordService.updateTSisRecord(tSisRecord));
    }

    /**
     * 删除sis Record
     */
    @PreAuthorize("@ss.hasPermi('process:sisRecord:remove')")
    @Log(title = "sis Record", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSisRecordService.deleteTSisRecordByIds(ids));
    }


    @Log(title = "sis Record批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TSisRecord> list = new ArrayList<>();
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSisRecord entity = new TSisRecord();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    switch (j) {
                        case 1:
                            entity.setSensorTag ( cellValue);
                            break;
                        case 2:
                            entity.setType ( cellValue);
                            break;
                        case 3:
                            entity.setService ( cellValue);
                            break;
                        case 4:
                            entity.setVotingQ ( cellValue);
                            break;
                        case 5:
                            entity.setCondition ( cellValue);
                            break;
                        case 6:
                            entity.setMainPti ( cellValue);
                            break;
                        case 7:
                            entity.setFinalElementTag ( cellValue);
                            break;
                        case 8:
                            entity.setVotingH ( cellValue);
                            break;
                        case 9:
                            entity.setAction ( cellValue);
                            break;
                        case 10:
                            entity.setFilter ( cellValue);
                            break;
                    }
                }
                entity.setCreaterCode(String.valueOf(userId));
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TSisRecord t : list
        ) {
            failNum++;
            try {
                //根据使用证、注册编号、位号，进行数据更新
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + successNumber);
        logger.info("failNumber:" + failNumber);
        logger.info("failRow:" + failRow);
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
