package com.ruoyi.project.sems.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.document.ZipUtil;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.common.domain.TCommonfile;
import com.ruoyi.project.common.service.ITCommonfileService;
import com.ruoyi.project.sems.domain.ParamData;
import com.ruoyi.project.sems.domain.TSpecCheck;
import com.ruoyi.project.sems.domain.TSpecdevCc;
import com.ruoyi.project.sems.his.controller.TApproveSpecModifyController;
import com.ruoyi.project.sems.his.controller.TSpechiCcController;
import com.ruoyi.project.sems.his.domain.TApproveSpecModify;
import com.ruoyi.project.sems.his.service.ITApproveSpecModifyService;
import com.ruoyi.project.sems.service.ITSpecCheckService;
import com.ruoyi.project.sems.service.ITSpecdevCcService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysPlant;
import com.ruoyi.project.system.domain.TAlarmtype;
import com.ruoyi.project.system.mapper.SysPlantMapper;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ITAlarmtypeService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 特种设备叉车台账Controller
 *
 * @author ruoyi
 * @date 2021-07-26
 */
@RestController
@RequestMapping("/sems/specCc")
public class TSpecdevCcController extends BaseController {
    @Autowired
    private ITSpecdevCcService tSpecdevCcService;
    @Autowired
    private ITSpecCheckService tSpecCheckService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private ITApproveSpecModifyService tApproveSpecModifyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TApproveSpecModifyController approveSpecModifyController;
    @Autowired
    private TSpechiCcController tSpechiCcController;
    //注入特种设备预警接口
    @Autowired
    private ITAlarmtypeService tAlarmtypeService;
    @Resource
    private SysPlantMapper sysPlantMapper;
    @Autowired
    private ITCommonfileService tCommonfileService;
    /**
     * 查询特种设备叉车台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevCc tSpecdevCc) {
        startPage();
        List<TSpecdevCc> list = tSpecdevCcService.selectTSpecdevCcList(tSpecdevCc);
        return getDataTable(list);
    }

    /**
     * 导出特种设备叉车台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:export')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevCc tSpecdevCc) {
        List<TSpecdevCc> list = tSpecdevCcService.selectTSpecdevCcList(tSpecdevCc);
        ExcelUtil<TSpecdevCc> util = new ExcelUtil<TSpecdevCc>(TSpecdevCc.class);
        return util.exportExcel(list, "specCc");
    }

    /**
     * 获取特种设备叉车台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tSpecdevCcService.selectTSpecdevCcById(id));
    }

    /**
     * 新增特种设备叉车台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:add')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevCc tSpecdevCc) {
        tSpecdevCc.setApproveStatus(22l);
        tSpecdevCcService.insertTSpecdevCc(tSpecdevCc);

        TApproveSpecModify tApproveSpecModify = new TApproveSpecModify();
        Long userid = getUserId();
        tApproveSpecModify.setUserId(userid);
        tApproveSpecModify.setApproveType(3l);
        tApproveSpecModify.setDevType(6l);
        tApproveSpecModify.setDevId(String.valueOf(tSpecdevCc.getId()));
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tApproveSpecModify.setApNo(data);
        //
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveSpecModifyService.insertTApproveSpecModify(tApproveSpecModify);
        long bussniseeKey = tApproveSpecModify.getId();
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("wxjlusers", tSpecdevCc.getWxjl());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("semsAddDelProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveSpecModify.setProcessId(pi.getProcessInstanceId());
        new Thread(() -> {
            approveSpecModifyController.sendMail(tApproveSpecModify, tSpecdevCc.getWxjl());
        }, "发送邮件").start();

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName = loginUser != null ? loginUser.getUsername() : "";
        new Thread(() -> {
            tSpechiCcController.addOperLog(String.valueOf(tSpecdevCc.getId()), userName, new Date(), "新增申请");
        }, "特种设备操作日志").start();
        return AjaxResult.success();
    }

    /**
     * 修改特种设备叉车台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:edit')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevCc tSpecdevCc) {
        TSpecdevCc old = tSpecdevCcService.selectTSpecdevCcById(tSpecdevCc.getId());
        if (StringUtils.isNotEmpty(tSpecdevCc.getReportNo()) && !tSpecdevCc.getReportNo().equals(old.getReportNo())) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(6l);
            tc.setCheckUnit(tSpecdevCc.getCheckUnit());
            tc.setDevId(tSpecdevCc.getId());
            tc.setNextWarnDate(tSpecdevCc.getNextWarnDate());
            tc.setReportNo(tSpecdevCc.getReportNo());
            tc.setWarnDate(tSpecdevCc.getWarnDate());
            tc.setCheckConclusion(tSpecdevCc.getPerTestConclusion());
            tSpecCheckService.insertTSpecCheck(tc);
        }
        tSpecdevCcService.updateTSpecdevCc(tSpecdevCc);

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName = loginUser != null ? loginUser.getUsername() : "";
        new Thread(() -> {
            tSpechiCcController.addOperLog(String.valueOf(tSpecdevCc.getId()), userName, new Date(), "修改");
        }, "特种设备操作日志").start();
        new Thread(() -> {
            this.checkWarnflag();
        }, "特种设备warnflag更新").start();
        return AjaxResult.success();
    }

    /**
     * 删除特种设备叉车台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:remove')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tSpecdevCcService.deleteTSpecdevCcByIds(ids));
    }

    /**
     * 去重
     */
    @PreAuthorize("@ss.hasRole('admin')")
    @Log(title = "特种设备叉车台账去重", businessType = BusinessType.OTHER)
    @GetMapping("/duplicate")
    public AjaxResult duplicate() {
        tSpecdevCcService.duplicateTSpecdevCc();
        return AjaxResult.success();
    }

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:add')")
    @Log(title = "特种设备批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam("wxjl") String wxjl) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TSpecdevCc> list = new ArrayList<TSpecdevCc>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysPlant> plants =  sysPlantMapper.selectSysPlantList(new SysPlant());
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSpecdevCc entity = new TSpecdevCc();
                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);
                    if (j == 0) {
                        //序号
                    } else if (j == 1) {
                        entity.setPlantCode(cellValue);//装置名称
                        //判断是否存在的plant
                        boolean found = false;
                        for (SysPlant p : plants) {
                            if (p.getName().equals(cellValue)) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            //未发现plant
                            throw new Exception("未发现plant");
                        }
                    } else if (j == 2) {
                        entity.setUnit(cellValue);//使用部门
                    } else if (j == 3) {
                        entity.setUseDept(cellValue);//使用部门
                    } else if (j == 4) {
                        entity.setPlantMaint(cellValue);//装置维护组
                    } else if (j == 5) {
                        entity.setEngineer(cellValue);//装置维护人员
                    } else if (j == 6) {
                        entity.setCarNo(cellValue);//车牌号
                    } else if (j == 7) {
                        entity.setDocno(cellValue);//档案号
                    } else if (j == 8) {
                        entity.setEngineNo(cellValue);//发动机号
                    } else if (j == 9) {
                        entity.setRegno(cellValue);//注册代码
                    } else if (j == 10) {
                        entity.setColor(cellValue);//颜色
                    } else if (j == 11) {
                        entity.setCapacity(cellValue);//工作能力
                    } else if (j == 12) {
                        entity.setDevname(cellValue);//设备名称
                    } else if (j == 13) {
                        entity.setEngineType(cellValue);//动力形式
                    } else if (j == 14) {
                        entity.setModel(cellValue);//型号
                    } else if (j == 15) {
                        entity.setFrameNo(cellValue);//车架号
                    } else if (j == 16) {
                        entity.setProductNo(cellValue);//产品编号
                    } else if (j == 17) {
                        entity.setCreateUnit(cellValue);//生产厂家
                    } else if (j == 18) {
                        entity.setExUnit(cellValue);//防爆改造厂家
                    } else if (j == 19) {
                        entity.setExGrade(cellValue);//最高防爆级别
                    } else if (j == 20) {
                        if (cellValue.length() > 3) {//初检日期
                            entity.setFirstWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 21) {
                        entity.setCheckStrategy(cellValue);//检验策略
                    } else if (j == 22) {
                        if (cellValue.length() > 3) {//检验日期
                            entity.setWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 23) {
                        if (cellValue.length() > 3) {//下次年检日期
                            entity.setNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 24) {
                        entity.setReportNo(cellValue);//报告编号
                    } else if (j == 25) {
                        entity.setPerTestConclusion(cellValue);
                    } else if (j == 26) {
                        entity.setAssetOwner(cellValue);//资产形式
                    } else if (j == 27) {
                        entity.setRemarks(cellValue);//备注
                    }else if (j == 28) {
                        entity.setRemarks2(cellValue);//备注2
                    }
                }
                entity.setCreaterCode(userId);
                logger.info("entity:" + entity);
                if(entity.getPlantCode() == null) {
                    //未发现plant
                    throw new Exception("plant为空");
                }
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        CopyOnWriteArrayList<String> ids = new CopyOnWriteArrayList();
        for (TSpecdevCc t : list
        ) {
            failNum++;
            try {
                t.setApproveStatus(22l);
                tSpecdevCcService.insertTSpecdevCc(t);
                ids.add(t.getId().toString());
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        String devIds = StringUtils.join(ids.toArray(), ",");
        TApproveSpecModify tApproveSpecModify = new TApproveSpecModify();
        Long userid = getUserId();
        tApproveSpecModify.setUserId(userid);
        tApproveSpecModify.setApproveType(3l);
        tApproveSpecModify.setDevType(6l);
        tApproveSpecModify.setDevId(devIds);
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tApproveSpecModify.setApNo(data);
        //
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveSpecModifyService.insertTApproveSpecModify(tApproveSpecModify);
        long bussniseeKey = tApproveSpecModify.getId();
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("wxjlusers", wxjl);
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("semsAddDelProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveSpecModify.setProcessId(pi.getProcessInstanceId());
        new Thread(() -> {
            approveSpecModifyController.sendMail(tApproveSpecModify, wxjl);
        }, "发送邮件").start();

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName = loginUser != null ? loginUser.getUsername() : "";
        new Thread(() -> {
            tSpechiCcController.addOperLog(ids.toArray(), userName, new Date(), "新增申请");
        }, "特种设备操作日志").start();

        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }


    /**
     * 批量导入
     * 检验更新中的批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:add')")
    @Log(title = "特种设备批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/updateData")
    public AjaxResult updateData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TSpecdevCc> list = new ArrayList<TSpecdevCc>();
        List<TSpecdevCc> oldList = new ArrayList<TSpecdevCc>();
        TSpecdevCc oldEntity = new TSpecdevCc();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSpecdevCc entity = new TSpecdevCc();
                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);

                    if (j == 0) {
                        //序号
                        Double d = Double.parseDouble(cellValue);
                        long s = new Double(d).longValue();
                        entity.setId(s);
                    } else if (j == 1) {    //装置名称
                        entity.setPlantCode(cellValue);
                    } else if (j == 2) {
                        entity.setCarNo(cellValue);
                    } else if (j == 3) {
                        entity.setDocno(cellValue);
                    } else if (j == 4) {
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {
                            entity.setWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 5) {
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {
                            entity.setNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 6) {
                        entity.setReportNo(cellValue);
                    } else if (j == 7) {
                        entity.setPerTestConclusion(cellValue);
                    }else if (j == 8) {
                        entity.setRemarks(cellValue);
                    }else if (j == 9) {
                        entity.setRemarks2(cellValue);
                    }
                }
                logger.info("entity:" + entity);
                list.add(entity);
                oldEntity = entity;
                oldList.add(oldEntity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        List<String> ids = new ArrayList<>();
        for (TSpecdevCc t : list) {
            failNum++;
            try {
                tSpecdevCcService
                        .update(t,
                                new QueryWrapper<TSpecdevCc>()
                                        .eq("DOCNO", t.getDocno())
                                        .eq("CAR_NO", t.getCarNo())
                                        .eq("PLANT_CODE", t.getPlantCode())
                        );
                ids.add(t.getId().toString());
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
                e.printStackTrace();
            }
        }
        for (TSpecdevCc t : oldList) {
            try {
                TSpecCheck tc = new TSpecCheck();
                tc.setDevType(6l);
                tc.setCheckUnit(t.getCheckUnit());
                tc.setDevId(t.getId());
                tc.setNextWarnDate(t.getNextWarnDate());
                tc.setReportNo(t.getReportNo());
                tc.setWarnDate(t.getWarnDate());
                tc.setCheckConclusion(t.getPerTestConclusion());
                tSpecCheckService.insertTSpecCheck(tc);
            } catch (Exception e) {
                logger.info("e:" + e);
                e.printStackTrace();
            }
        }

        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        String userName = loginUser != null ? loginUser.getUsername() : "";
        new Thread(() -> {
            tSpechiCcController.addOperLog(ids.toArray(), userName, new Date(), "批量更新");
        }, "特种设备操作日志").start();
        new Thread(() -> {
            this.checkWarnflag();
        }, "特种设备warnflag更新").start();
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }


    @GetMapping("/exportDevList")
    public AjaxResult exportbmy(ParamData params) throws IOException {
        logger.info(JSON.toJSONString(params));
        String id = params.getIds();
        String[] ids = id.split(",");
        List<TSpecdevCc> list = new ArrayList<>();
        for (String i : ids
        ) {
            TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
            list.add(ccEntity);
        }
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        CellStyle wrapStyle = wb.createCellStyle();
        wrapStyle.setWrapText(true);    //设置自动换行
        //创建sheet页
        Sheet sheet = wb.createSheet("sheet1");
        //设置列的宽度，第一个参数为列的序号，从0开始，第二参数为列宽，单位1/256个字节
        sheet.setColumnWidth(0, 12 * 256);
        sheet.setColumnWidth(1, 26 * 256);
        sheet.setColumnWidth(2, 26 * 256);
        sheet.setColumnWidth(3, 26 * 256);
        sheet.setColumnWidth(4, 26 * 256);
        sheet.setColumnWidth(5, 26 * 256);
        sheet.setColumnWidth(6, 26 * 256);
        sheet.setColumnWidth(7, 26 * 256);
        sheet.setColumnWidth(8, 40 * 256);
        sheet.setColumnWidth(9, 40 * 256);
        //设置开始行和开始列

        Row row0 = sheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        Font headerFont = wb.createFont();
//        headerFont.setFontName("Arial");
//        headerFont.setFontHeightInPoints((short) 12);
//        headerFont.setBold(false);
//        headerFont.setColor(IndexedColors.BLACK.getIndex());
//        style.setFont(headerFont);
        Cell cell0 = row0.createCell(0);
        row0.createCell(0).setCellValue("序号");
        row0.createCell(1).setCellValue("装置");
        row0.createCell(2).setCellValue("车牌号");
        row0.createCell(3).setCellValue("档案号");
        row0.createCell(4).setCellValue("检验日期");
        row0.getCell(4).setCellStyle(style);
        row0.createCell(5).setCellValue("下次检验日期");
        row0.getCell(5).setCellStyle(style);
        row0.createCell(6).setCellValue("报告编号");
        row0.getCell(6).setCellStyle(style);
        row0.createCell(7).setCellValue("定期检验结论");
        row0.getCell(7).setCellStyle(style);
        row0.createCell(8).setCellValue("备注");
        row0.getCell(8).setCellStyle(style);
        row0.createCell(9).setCellValue("备注2（如报告未到备注在此处）");
        row0.getCell(9).setCellStyle(style);
        //填充数据
        int rowIndex = 1;
        int columnIndex = 1;
        for (TSpecdevCc t : list
        ) {
            Row row = sheet.createRow(rowIndex);
            row.createCell(0).setCellValue(t.getId());
            row.createCell(1).setCellValue(t.getPlantCode());
            row.createCell(2).setCellValue(t.getCarNo());
            row.createCell(3).setCellValue(t.getDocno());
            if (t.getWarnDate() != null) {
                row.createCell(4).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getWarnDate()));
            }
            if (t.getNextWarnDate() != null) {
                row.createCell(5).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getNextWarnDate()));
            }
            row.createCell(6).setCellValue(t.getReportNo());
            row.createCell(7).setCellValue(t.getPerTestConclusion());
            row.createCell(8).setCellValue(t.getRemarks());
            row.createCell(9).setCellValue(t.getRemarks2());
            rowIndex++;
        }

        OutputStream out = null;
        String filename = ExcelUtil.encodingFilename("叉车批量更新");
        out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
        wb.write(out);
        wb.close();
        out.close();
        return AjaxResult.success(filename);
    }

    public void checkWarnflag() {
        //获取动态处理预警级别
        TAlarmtype tAlarmtype = this.tAlarmtypeService.selectTAlarmtypeById(1080L);
        if (tAlarmtype.getIsOpen() == 0) {
            logger.info("特种设备预警标识定时任务未启用");
            return;
        }
        Long firstlevel = tAlarmtype.getFirstlevel();//1级
        Long secondlevel = tAlarmtype.getSecondlevel();//2级
        Long thirdlevel = tAlarmtype.getThirdlevel();//3级
        List<TSpecdevCc> list = this.tSpecdevCcService.list(new QueryWrapper<TSpecdevCc>()
                .eq("del_flag", 0).eq("status", "1"));
        List<TSpecdevCc> firstList = new ArrayList<>();
        List<TSpecdevCc> secondList = new ArrayList<>();
        List<TSpecdevCc> thirdList = new ArrayList<>();
        for (TSpecdevCc tSpecdevCc : list) {
            if (tSpecdevCc.getNextWarnDate() != null) {
                long now = System.currentTimeMillis();
                long diff = tSpecdevCc.getNextWarnDate().getTime() - now;
                long nd = 1000 * 24 * 60 * 60;
                long day = diff / nd;
                // 半年内 预警标识为2级
                if (day > 0 && day <= secondlevel) {
                    this.updateForCc(2L, tSpecdevCc);
                    //只在当天发送邮件
                    if (day == secondlevel) {
                        firstList.add(tSpecdevCc);
                    }
                    continue;
                }
                // 半年-一年 预警标识为1级
                if (day > secondlevel && day <= thirdlevel) {
                    this.updateForCc(1L, tSpecdevCc);
                    //只在当天发送邮件
                    if (day == thirdlevel) {
                        secondList.add(tSpecdevCc);
                    }
                    continue;
                }
                // 超时 预警标识为3级
                if (day <= firstlevel) {
                    this.updateForCc(3L, tSpecdevCc);
                    //只在当天发送邮件
                    if (day == firstlevel) {
                        thirdList.add(tSpecdevCc);
                    }
                    continue;
                }
                if (day > thirdlevel) {
                    this.updateForCc(0L, tSpecdevCc);
                    continue;
                }
            }
        }
    }

    private void updateForCc(Long flag, TSpecdevCc tSpecdevCc) {
        tSpecdevCc.setWarnFlag(flag);
        this.tSpecdevCcService.updateTSpecdevCc(tSpecdevCc);
    }

    /**
     * 批量导入文件
     */
    @Log(title = "特种设备文件导入", businessType = BusinessType.OTHER)
    @PostMapping("/importFiles")
    public AjaxResult importFiles(@RequestParam("file") List<MultipartFile> files,@RequestParam("plantCode") String plantCode,@RequestParam("fileType") String fileType) throws Exception {
        tSpecdevCcService.importFiles(files,plantCode,fileType,getUserId().toString());

        return AjaxResult.success();
    }

    /**
     * @return
     * @throws IOException
     */
    @RequestMapping("/downloadFileZip")
    public AjaxResult downloadFileZip(@RequestParam String id, String type, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] stringIds = id.split(",");

        TCommonfile tCommonfile = new TCommonfile();
        tCommonfile.setpType("sems-cc-" + type);
        tCommonfile.setpIds(stringIds);
        List<TCommonfile> fileList = tCommonfileService.selectAllFileListFuzzy(tCommonfile);

        OutputStream out = null;
        out = response.getOutputStream();
        //存放所有文件路径
        List<String> urlList = new ArrayList<>();
        for (TCommonfile t:fileList
        ) {
            // 将路径字符串转换为Path对象
            Path path = Paths.get(t.getFileUrl());
            // 获取文件名
            String fileName = path.getFileName().toString();
            urlList.add(t.getFileUrl().replace("/profile",""));
        }
        logger.info(JSON.toJSONString(urlList));
        return ZipUtil.createZip(RuoYiConfig.getProfile(), "",  "特种设备.zip", urlList, response);
    }

}
