package com.ruoyi.project.sems.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.service.ITSpecCheckService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.sems.service.ITSpecdevYlgdService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 特种设备压力管道台账Controller
 *
 * @author ruoyi
 * @date 2021-07-22
 */
@RestController
@RequestMapping("/sems/specYlgd")
public class TSpecdevYlgdController extends BaseController {
    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;
    @Autowired
    private ITSpecCheckService tSpecCheckService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询特种设备压力管道台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevYlgd tSpecdevYlgd) {
        startPage();
        List<TSpecdevYlgd> list = tSpecdevYlgdService.selectTSpecdevYlgdList(tSpecdevYlgd);
        return getDataTable(list);
    }

    /**
     * 导出特种设备压力管道台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:export')")
    @Log(title = "特种设备压力管道台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevYlgd tSpecdevYlgd) {
        List<TSpecdevYlgd> list = tSpecdevYlgdService.selectTSpecdevYlgdList(tSpecdevYlgd);
        ExcelUtil<TSpecdevYlgd> util = new ExcelUtil<TSpecdevYlgd>(TSpecdevYlgd.class);
        return util.exportExcel(list, "specYlgd");
    }

    /**
     * 获取特种设备压力管道台账详细信息
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tSpecdevYlgdService.selectTSpecdevYlgdById(id));
    }

    /**
     * 新增特种设备压力管道台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:add')")
    @Log(title = "特种设备压力管道台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevYlgd tSpecdevYlgd) {
        return toAjax(tSpecdevYlgdService.insertTSpecdevYlgd(tSpecdevYlgd));
    }

    /**
     * 修改特种设备压力管道台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:edit')")
    @Log(title = "特种设备压力管道台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevYlgd tSpecdevYlgd) {
        TSpecdevYlgd old = tSpecdevYlgdService.selectTSpecdevYlgdById(tSpecdevYlgd.getId());
        if (!old.getReportNo().equals(tSpecdevYlgd.getReportNo())) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(2l);
            tc.setCheckUnit(tSpecdevYlgd.getCheckUnit());
            tc.setDevId(tSpecdevYlgd.getId());
            tc.setNextWarnDate(tSpecdevYlgd.getNextWarnDate());
            tc.setReportNo(tSpecdevYlgd.getReportNo());
            tc.setWarnDate(tSpecdevYlgd.getWarnDate());
            tc.setYearNextWarnDate(tSpecdevYlgd.getYearNextWarnDate());
            tc.setYearWarnDate(tSpecdevYlgd.getYearWarnDate());
            tc.setYearReportNo(tSpecdevYlgd.getReportNo());
            tc.setSafeClass(tSpecdevYlgd.getSafeClass());
            tSpecCheckService.insertTSpecCheck(tc);
        }

        return toAjax(tSpecdevYlgdService.updateTSpecdevYlgd(tSpecdevYlgd));
    }

    /**
     * 删除特种设备压力管道台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:remove')")
    @Log(title = "特种设备压力管道台账", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tSpecdevYlgdService.deleteTSpecdevYlgdByIds(ids));
    }

    /**
     * 去重
     */
    @PreAuthorize("@ss.hasPermi('sems:plant:remove')")
    @GetMapping("/duplicate")
    public AjaxResult duplicate()
    {
        tSpecdevYlgdService.duplicateTSpecdevYlgd();
        return AjaxResult.success();
    }

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlgd:add')")
    @Log(title = "特种设备批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@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<TSpecdevYlgd> list = new ArrayList<TSpecdevYlgd>();
        //字典查询
        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();
                TSpecdevYlgd entity = new TSpecdevYlgd();
                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);//装置名称
                    } else if (j == 2) {
                        entity.setUnit(cellValue);//单元
                    } else if (j == 3) {
                        entity.setPlantMaint(cellValue);//装置维修组
                    } else if (j == 4) {
                        entity.setEngineer(cellValue);//装置维修工程师
                    } else if (j == 5) {
                        entity.setDevname(cellValue);//管道名称
                    } else if (j == 6) {
                        entity.setDevno(cellValue);//管道编号
                    } else if (j == 7) {
                        entity.setRegno(cellValue);//压力管道工业代码
                    } else if (j == 8) {
                        entity.setUseno(cellValue);//使用登记表编号
                    } else if (j == 9) {
                        entity.setGrade(cellValue);//管道级别
                    } else if (j == 10) {
                        entity.setDesigner(cellValue);//设计单位
                    } else if (j == 11) {
                        entity.setInstaller(cellValue);//安装单位
                    } else if (j == 12) {//安装年月
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {
                            entity.setInstallDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 13) {//投用年月
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {
                            entity.setSubmitdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 14) {
                        entity.setMaterial(cellValue);//材质
                    } else if (j == 15) {
                        entity.setDia(cellValue);//管道外径（英寸）
                    } else if (j == 16) {
                        entity.setScheduleNo(cellValue);//厚度等级
                    } else if (j == 17) {
                        entity.setLength(cellValue);//长度
                    } else if (j == 18) {
                        entity.setWeldNumber(cellValue);//焊口数量
                    } else if (j == 19) {
                        entity.setStarting(cellValue);//起点
                    } else if (j == 20) {
                        entity.setEnding(cellValue);//终点
                    } else if (j == 21) {
                        entity.setLayingMethod(cellValue);//敷设方式
                    } else if (j == 22) {
                        entity.setMedium(cellValue);//介质
                    } else if (j == 23) {
                        entity.setDesPressure(cellValue);//设计压力
                    } else if (j == 25) {
                        entity.setDesTemp(cellValue);//设计温度
                    } else if (j == 24) {
                        entity.setOptPressure(cellValue);//工作压力
                    } else if (j == 26) {
                        entity.setOptTemp(cellValue);//工作温度
                    } else if (j == 27) {
                        entity.setAdiabatic(cellValue);//绝热层代码
                    } else if (j == 28) {
                        entity.setIsDanger(cellValue);
                    } else if (j == 29) {
                        entity.setCheckUnit(cellValue);//检验单位
                    } else if (j == 30) {//检验日期
                        if (cellValue.length() < 4) {
                            continue;
                        }
                        entity.setWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    } else if (j == 31) {
                        entity.setSafeClass(cellValue);//安全状况等级
                    } else if (j == 32) {
                        //年度检查报告编号
                        entity.setReportNo(cellValue);//报告编号
                    } else if (j == 33) {//下次检验日期
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() < 4) {
                            continue;
                        }
                        entity.setNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    } else if (j == 34) {
                        if (cellValue.length() > 3) {//年度检查日期
                            entity.setYearWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 35) {
                        entity.setCheckConclusion(cellValue);//年度结论
                    } else if (j == 36) {
                        if (cellValue.length() > 3) {//下次年度检验日期
                            entity.setYearNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 37) {
                        entity.setYearReportNo(cellValue);
                    } else if (j == 38) {
                        entity.setRemarks(cellValue);//备注
                    } /*else if (j == 39) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue)) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }*/
                }
                entity.setCreaterCode(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 (TSpecdevYlgd t : list
        ) {
            failNum++;
            try {
                tSpecdevYlgdService.insertTSpecdevYlgd(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        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:specYlgd: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<TSpecdevYlgd> list = new ArrayList<TSpecdevYlgd>();
        List<TSpecdevYlgd> oldList = new ArrayList<TSpecdevYlgd>();
        TSpecdevYlgd oldEntity = new TSpecdevYlgd();
        //字典查询
        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();
                TSpecdevYlgd entity = new TSpecdevYlgd();
                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.setDevname(cellValue);
                    } else if (j == 3) {    //管道编号
                        entity.setDevno(cellValue);
                    } else if (j == 4) {    //使用登记表编号
                        entity.setUseno(cellValue);
                    } else if (j == 5) {    //检验单位
                        entity.setCheckUnit(cellValue);
                    } else if (j == 6) {    //检验日期
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {
                            entity.setWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 7) {    //安全状况等级
                        entity.setSafeClass(cellValue);
                    } else if (j == 8) {    //报告编号
                        entity.setReportNo(cellValue);
                    } else if (j == 9) {    //下次检验日期
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {//检验日期
                            entity.setNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 10) {   //年度检查日期
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {//检验日期
                            entity.setYearWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 11) {   //年度检查结论
                        entity.setCheckConclusion(cellValue);
                    } else if (j == 12) {   //下次年度检查日期
                        logger.info("日期格式：" + cellValue);
                        if (cellValue.length() > 3) {//检验日期
                            entity.setYearNextWarnDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 13) {   //年度检查报告编号
                        entity.setYearReportNo(cellValue);
                    }
                }
                logger.info("entity:" + JSON.toJSONString(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;
        for (TSpecdevYlgd t : list) {
            failNum++;
            try {
                tSpecdevYlgdService
                        .update(t,
                                new QueryWrapper<TSpecdevYlgd>()
                                        .eq("USENO", t.getUseno())
                                        .eq("PLANT_CODE", t.getPlantCode())
                                        .eq("DEVNO" , t.getDevno())
                        );
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        for (TSpecdevYlgd t : oldList) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(2l);
            tc.setCheckUnit(t.getCheckUnit());
            tc.setDevId(t.getId());
            tc.setNextWarnDate(t.getNextWarnDate());
            tc.setReportNo(t.getReportNo());
            tc.setWarnDate(t.getWarnDate());
            tc.setYearNextWarnDate(t.getYearNextWarnDate());
            tc.setYearWarnDate(t.getYearWarnDate());
            tc.setYearReportNo(t.getReportNo());
            tc.setSafeClass(t.getSafeClass());
            tSpecCheckService.insertTSpecCheck(tc);
        }
        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<TSpecdevYlgd> list = new ArrayList<>();
        for (String i : ids
        ) {
            TSpecdevYlgd t = tSpecdevYlgdService.getById(i);
            list.add(t);
        }
        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);
        sheet.setColumnWidth(10, 26*256);
        sheet.setColumnWidth(11, 26*256);
        sheet.setColumnWidth(12, 40*256);
        sheet.setColumnWidth(13, 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.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("下次定期检验日期");row0.getCell(9).setCellStyle(style);

        row0.createCell(10).setCellValue("年度检查日期");row0.getCell(10).setCellStyle(style);
        row0.createCell(11).setCellValue("年度检查结论");row0.getCell(11).setCellStyle(style);
        row0.createCell(12).setCellValue("下次年度检查日期");row0.getCell(12).setCellStyle(style);
        row0.createCell(13).setCellValue("年度检查报告编号");row0.getCell(13).setCellStyle(style);

        //填充数据
        int rowIndex = 1;
        int columnIndex = 1;
        for (TSpecdevYlgd t: list
        ) {
            Row row = sheet.createRow(rowIndex);
            row.createCell(0).setCellValue(t.getId());
            row.createCell(1).setCellValue(t.getPlantCode());
            row.createCell(2).setCellValue(t.getDevname());
            row.createCell(3).setCellValue(t.getDevno());
            row.createCell(4).setCellValue(t.getUseno());
            row.createCell(5).setCellValue(t.getCheckUnit());
            if (t.getWarnDate()!= null){
                row.createCell(6).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getWarnDate()));
            }
            row.createCell(7).setCellValue(t.getSafeClass());
            row.createCell(8).setCellValue(t.getReportNo());
            if (t.getNextWarnDate()!= null){
                row.createCell(9).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getNextWarnDate()));
            }
            if (t.getYearWarnDate()!= null){
                row.createCell(10).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getYearWarnDate()));
            }
            row.createCell(11).setCellValue(t.getCheckConclusion());
            if (t.getYearNextWarnDate()!= null){
                row.createCell(12).setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(t.getYearNextWarnDate()));
            }
            row.createCell(13).setCellValue(t.getYearReportNo());
            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);
    }
}
