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.StringUtils;
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.domain.TSifVo;
import com.cpms.project.process.domain.TSisRecord;
import com.cpms.project.process.domain.TValveCsocsc;
import com.cpms.project.process.service.ITSifOverviewService;
import com.cpms.project.process.service.ITSisRecordService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * SIF Overview ListController
 *
 * @author admin
 * @date 2024-05-22
 */
@RestController
@RequestMapping("/process/sifList")
public class TSifOverviewController extends BaseController {
    @Autowired
    private ITSifOverviewService tSifOverviewService;
    @Autowired
    private ITSisRecordService tSisRecordService;

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

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

    /**
     * 导出SIF Overview List列表
     */
    @PreAuthorize("@ss.hasPermi('process:sifList:export')")
    @Log(title = "SIF Overview List", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTmpl")
    public void exportTmpl(HttpServletResponse response, TSifOverview tSifOverview) {
        List<TSifVo> list = tSifOverviewService.selectTSifOverviewList(tSifOverview);
        try {
            String tempUrl = "static/template/process/sisListExport.xlsx"; // 模板文件
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb1 = null;
            wb1 = new XSSFWorkbook(is);
            SXSSFWorkbook wb = new SXSSFWorkbook(wb1, 1000);

            Sheet sheet;
            if (wb instanceof SXSSFWorkbook) {
                SXSSFWorkbook sxssfWorkbook = (SXSSFWorkbook) wb;
                sheet = sxssfWorkbook.getXSSFWorkbook().getSheetAt(0);
            } else {
                sheet = wb.getSheetAt(0);
            }

            //填充数据
            int rowIndex = 1;
            int num = 1;

            Row originalRow = sheet.getRow(1);
            Cell originalcell = originalRow.getCell(0);
            // 获取单元格样式
            CellStyle originalStyle = originalcell.getCellStyle();

            for (TSifVo t: list
            ) {
                Row row = sheet.createRow(rowIndex);
                row.createCell(0).setCellValue(t.getSifNo());
                row.createCell(1).setCellValue(t.getPlant());
                row.createCell(2).setCellValue(t.getSifTag());
                row.createCell(3).setCellValue(t.getDeviation());
                row.createCell(4).setCellValue(t.getRiskAnalysis());
                row.createCell(5).setCellValue(t.getCauseConsequence());
                row.createCell(6).setCellValue(t.getRequiredSil());
                row.createCell(7).setCellValue(t.getAcheievedSil());
                row.createCell(8).setCellValue(t.getPfdavg());
                row.createCell(9).setCellValue(t.getSensorTag());
                row.createCell(10).setCellValue(t.getType());
                row.createCell(11).setCellValue(t.getService());
                row.createCell(12).setCellValue(t.getVotingQ());
                row.createCell(13).setCellValue(t.getCondition());
                row.createCell(14).setCellValue(t.getMainPti());
                row.createCell(15).setCellValue(t.getFinalElementTag());
                row.createCell(16).setCellValue(t.gethType());
                row.createCell(17).setCellValue(t.gethService());
                row.createCell(18).setCellValue(t.getVotingH());
                row.createCell(19).setCellValue(t.getAction());
                row.createCell(20).setCellValue(t.getMainPtiH());
                row.createCell(21).setCellValue(t.getRemarks());
                row.createCell(22).setCellValue(t.getVer());
                row.createCell(23).setCellValue(t.getFilter());

                //渲染样式
                for (int i = 0; i < 24; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }

            //合并操作
            rowIndex = 1;
            String sn = list.get(0).getSifNo();
            int firstRow = 1;
            for (TSifVo t: list
            ) {
                if (sn.equals(t.getSifNo())) {

                }else {
                    //合并
                    addRegion(sheet,firstRow,rowIndex);
                    sn = t.getSifNo();
                    firstRow = rowIndex + 1;
                }
                rowIndex++;
            }

            // 生成文件返回下载地址
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            wb.write(response.getOutputStream());
            wb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void addRegion(Sheet sheet, int firstRow, int rowIndex) {
        logger.info("起始行:" + firstRow);
        logger.info("结束行:" +rowIndex);
        if (firstRow == rowIndex) {
            return;
        }
        // 合并区域从第0行第0列到第0行第3列
        for (int i = 0; i < 9; i++) {
            CellRangeAddress mergedRegion = new CellRangeAddress(
                    firstRow, // 起始行
                    rowIndex, // 结束行
                    i, // 起始列
                    i  // 结束列
            );
            sheet.addMergedRegion(mergedRegion);
        }

    }

    /**
     * 获取SIF Overview List详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:sifList:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TSifOverview tSifOverview = tSifOverviewService.selectTSifOverviewById(id);
        TSisRecord tSisRecord = new TSisRecord();
        tSisRecord.setSisId(id);
        tSifOverview.setRecordList(tSisRecordService.selectTSisRecordList(tSisRecord));
        return success(tSifOverview);
    }

    /**
     * 新增SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:sifList:add')")
    @Log(title = "SIF Overview List", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSifOverview tSifOverview) {
        tSifOverview.setCreaterCode(getUserId().toString());
        tSifOverview.setCreatedate(new Date());
        tSifOverviewService.insertTSifOverview(tSifOverview);
        for (TSisRecord tSisRecord : tSifOverview.getRecordList()) {
            tSisRecord.setSisId(tSifOverview.getId());
            tSisRecord.setCreaterCode(getUserId().toString());
            tSisRecord.setCreatedate(new Date());
            tSisRecordService.insertTSisRecord(tSisRecord);
        }
        return success();
    }

    /**
     * 修改SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:sifList:edit')")
    @Log(title = "SIF Overview List", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSifOverview tSifOverview) {
        tSifOverview.setUpdaterCode(getUserId().toString());
        tSifOverview.setUpdatedate(new Date());
        for (TSisRecord tSisRecord : tSifOverview.getRecordList()) {
            if (tSisRecord.getId() != null) {
                tSisRecordService.updateTSisRecord(tSisRecord);
            } else {
                tSisRecord.setSisId(tSifOverview.getId());
                tSisRecord.setCreaterCode(getUserId().toString());
                tSisRecord.setCreatedate(new Date());
                tSisRecordService.insertTSisRecord(tSisRecord);
            }
        }
        return toAjax(tSifOverviewService.updateTSifOverview(tSifOverview));
    }

    /**
     * 删除SIF Overview List
     */
    @PreAuthorize("@ss.hasPermi('process:sifList: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;
        List<TSisRecord> records = null;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSifOverview entity = new TSifOverview();
                TSisRecord record = new TSisRecord();
                boolean flag = false;
                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);
                            if (StringUtils.isNotEmpty(cellValue)) {
                                records = new ArrayList<>();
                                flag = true;
                            }
                            if (StringUtils.isEmpty(cellValue)){
                                flag = false;
                            }
                            break;
                        case 1:
                            entity.setPlant(cellValue);
                            break;
                        case 2:
                            entity.setSifTag(cellValue);
                            break;
                        case 3:
                            entity.setDeviation(cellValue);
                            break;
                        case 4:
                            entity.setRiskAnalysis(cellValue);
                            break;
                        case 5:
                            entity.setCauseConsequence(cellValue);
                            break;
                        case 6:
                            entity.setRequiredSil(cellValue);
                            break;
                        case 7:
                            entity.setAcheievedSil(cellValue);
                            break;
                        case 8:
                            entity.setPfdavg(cellValue);
                            break;
                        case 9:
                            record.setSensorTag(cellValue);
                            break;
                        case 10:
                            record.setType(cellValue);
                            break;
                        case 11:
                            record.setService(cellValue);
                            break;
                        case 12:
                            record.setVotingQ(cellValue);
                            break;
                        case 13:
                            record.setCondition(cellValue);
                            break;
                        case 14:
                            record.setMainPti(cellValue);
                            break;
//                        case 15:
//                            record.setFinalElementTag(cellValue);
//                            break;
                        case 15:
                            record.setH(cellValue);
                            break;
                        case 16:
                            record.sethType(cellValue);
                            break;
                        case 17:
                            record.sethService(cellValue);
                            break;
                        case 18:
                            record.setVotingH(cellValue);
                            break;
                        case 19:
                            record.setAction(cellValue);
                            break;
                        case 20:
                            record.setMainPtiH(cellValue);
                            break;
                        case 21:
                            entity.setRemarks(cellValue);
                            break;
                        case 22:
                            entity.setVer(cellValue);
                            break;
                        case 23:
                            record.setFilter(cellValue);
                            break;
                    }
                }
                if (records != null) {
                    records.add(record);
                }
                if (!flag){
                    entity = list.get(list.size()-1);
                    entity.setRecordList(records);
                    list.remove(list.size()-1);
                    list.add(entity);
                }else {
                    entity.setRecordList(records);
                    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);
    }
}
