package com.cpms.project.process.controller;

import com.alibaba.fastjson2.JSON;
import com.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.core.page.TableDataInfo;
import com.cpms.common.enums.BusinessType;
import com.cpms.common.utils.file.ExcelUtils;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.project.process.domain.TSifOverview;
import com.cpms.project.process.service.ITSifOverviewService;
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.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * SIF Overview ListController
 *
 * @author admin
 * @date 2024-04-12
 */
@RestController
@RequestMapping("/process/overview")
public class TSifOverviewController extends BaseController {
    @Autowired
    private ITSifOverviewService tSifOverviewService;

    /**
     * 查询SIF Overview List列表
     */
    @PreAuthorize("@ss.hasPermi('process:overview:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSifOverview tSifOverview) {
        startPage();
        List<TSifOverview> list = tSifOverviewService.selectTSifOverviewList(tSifOverview);
        return getDataTable(list);
    }

    /**
     * 导出SIF Overview List列表
     */
    @PreAuthorize("@ss.hasPermi('process:overview:export')")
    @Log(title = "SIF Overview List" , businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TSifOverview tSifOverview) {
        List<TSifOverview> list = tSifOverviewService.selectTSifOverviewList(tSifOverview);
        ExcelUtil<TSifOverview> util = new ExcelUtil<TSifOverview>(TSifOverview.class);
        util.exportExcel(response, list, "SIF Overview List数据");
    }

    /**
     * 获取SIF Overview List详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:overview:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tSifOverviewService.selectTSifOverviewById(id));
    }

    /**
     * 新增SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:overview:add')")
    @Log(title = "SIF Overview List" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSifOverview tSifOverview) {
        return toAjax(tSifOverviewService.insertTSifOverview(tSifOverview));
    }

    /**
     * 修改SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:overview:edit')")
    @Log(title = "SIF Overview List" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSifOverview tSifOverview) {
        return toAjax(tSifOverviewService.updateTSifOverview(tSifOverview));
    }

    /**
     * 删除SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:overview:remove')")
    @Log(title = "SIF Overview List" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tSifOverviewService.deleteTSifOverviewByIds(ids));
    }


    @Log(title = "SIF Overview List批量导入" , 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<TSifOverview> 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();
                TSifOverview entity = new TSifOverview();
                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 0:
                            entity.setSifNo(cellValue);
                            break;
                        case 1:
                            entity.setDeviation(cellValue);
                            break;
                        case 2:
                            entity.setSheNo(cellValue);
                            break;
                        case 3:
                            entity.setCac(cellValue);
                            break;
                        case 4:
                            entity.setRequriedSil(cellValue);
                            break;
                        case 5:
                            entity.setSensors(cellValue);
                            break;
                        case 6:
                            entity.setsVoting(cellValue);
                            break;
                        case 7:
                            entity.setFinalElements(cellValue);
                            break;
                        case 8:
                            entity.setfVoting(cellValue);
                            break;
                        case 9:
                            entity.setAction(cellValue);
                            break;
                        case 10:
                            entity.setAchievedSil(cellValue);
                            break;
                        case 11:
                            entity.setPfdCr(cellValue);
                            break;
                        case 12:
                            entity.setRemarks(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 (TSifOverview 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);
    }
}
