package com.ruoyi.project.sems.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.sems.domain.TSpecdevGl;
import com.ruoyi.project.sems.service.ITSpecdevGlService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.joda.time.DateTime;
import org.joda.time.Days;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 特种设备锅炉台账Controller
 *
 * @author ruoyi
 * @date 2021-07-21
 */
@RestController
@RequestMapping("/sems/specGl")
public class TSpecdevGlController extends BaseController {
    @Autowired
    private ITSpecdevGlService tSpecdevGlService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询特种设备锅炉台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specGl:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevGl tSpecdevGl) {
        startPage();
        List<TSpecdevGl> list = tSpecdevGlService.selectTSpecdevGlList(tSpecdevGl);
        for (TSpecdevGl dev : list) {
            if (dev.getExternalInspection() != null) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date d1 = dev.getExternalInspection();
                    Date d2 = format.parse(DateUtils.getDate());
                    DateTime dt1 = new DateTime(d1);
                    DateTime dt2 = new DateTime(d2);
                    int days = Days.daysBetween(dt2, dt1).getDays();
                    if (days > 60) {
                        dev.setCheckStatus("正常");
                    } else {
                        dev.setCheckStatus("待报检");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出特种设备锅炉台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specGl:export')")
    @Log(title = "特种设备锅炉台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevGl tSpecdevGl) {
        List<TSpecdevGl> list = tSpecdevGlService.selectTSpecdevGlList(tSpecdevGl);
        for (TSpecdevGl dev : list) {
            if (dev.getExternalInspection() != null) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date d1 = dev.getExternalInspection();
                    Date d2 = format.parse(DateUtils.getDate());
                    DateTime dt1 = new DateTime(d1);
                    DateTime dt2 = new DateTime(d2);
                    int days = Days.daysBetween(dt2, dt1).getDays();
                    if (days > 60) {
                        dev.setCheckStatus("正常");
                    } else {
                        dev.setCheckStatus("待报检");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        ExcelUtil<TSpecdevGl> util = new ExcelUtil<TSpecdevGl>(TSpecdevGl.class);
        return util.exportExcel(list, "specGl");
    }

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

    /**
     * 新增特种设备锅炉台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specGl:add')")
    @Log(title = "特种设备锅炉台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevGl tSpecdevGl) {
        return toAjax(tSpecdevGlService.insertTSpecdevGl(tSpecdevGl));
    }

    /**
     * 修改特种设备锅炉台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specGl:edit')")
    @Log(title = "特种设备锅炉台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevGl tSpecdevGl) {
        //TSpecdevGl old = tSpecdevGlService.selectTSpecdevGlById(tSpecdevGl.getId());
       /* if (!old.getReportNo().equals(tSpecdevGl.getReportNo())) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(4l);
            tc.setCheckUnit(tSpecdevGl.getCheckUnit());
            tc.setDevId(tSpecdevGl.getId());
            tc.setNextWarnDate(tSpecdevGl.getNextWarnDate());
            tc.setReportNo(tSpecdevGl.getReportNo());
            tc.setWarnDate(tSpecdevGl.getWarnDate());
            tc.setOutWarnDate(tSpecdevGl.getOutWarnDate());
            tc.setOutReportNo(tSpecdevGl.getOutReportNo());
            tc.setOutCheckConclusion(tSpecdevGl.getOutCheckConclusion());
            tc.setOutNextWarnDate(tSpecdevGl.getOutNextWarnDate());
            tSpecCheckService.insertTSpecCheck(tc);
        }*/
        return toAjax(tSpecdevGlService.updateTSpecdevGl(tSpecdevGl));
    }

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

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

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specGl: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<TSpecdevGl> list = new ArrayList<TSpecdevGl>();
        //字典查询
        List<SysDictData> status = iSysDictTypeService.selectDictDataByType("spec_dev_status");

        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        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();
                TSpecdevGl entity = new TSpecdevGl();
                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) {
                        //序号
                        entity.setPlantCode(cellValue);
                    } else if (j == 1) {
                        entity.setContainerNo(cellValue);//装置名称
                    } else if (j == 2) {
                        entity.setRegno(cellValue);//位号
                    } else if (j == 3) {
                        entity.setUseno(cellValue);//设备名称
                    } else if (j == 4) {
                        entity.setFiledSituation(cellValue);//使用证号
                    } else if (j == 5) {
                        entity.setFactoryInfo(cellValue);//检验单位
                    } else if (j == 6) {
                        entity.setInternalInspection(DateUtils.parseDate(cellValue));
                    } else if (j == 7) {
                        entity.setExternalInspection(DateUtils.parseDate(cellValue));//内部检验结论
                    } else if (j == 8) {
                        entity.setPressureTest(DateUtils.parseDate(cellValue));//内部检验报告编号
                    } else if (j == 9) {
                        entity.setEnergyEfficiencyTest(DateUtils.parseDate(cellValue));

                    } else if (j == 10) {
                        entity.setDevname(cellValue);
                    } else if (j == 11) {
                        entity.setFactoryNo(cellValue);//外部检验结论
                    } else if (j == 12) {
                        entity.setMedium(cellValue);//外部检验报告编号
                    } else if (j == 13) {
                        entity.setDesignUnit(cellValue);
                    }else if (j == 14) {
                        entity.setCreateUnit(cellValue);
                    }else if (j == 15) {
                        for (SysDictData data : status) {
                            if (data.getDictLabel().equals(cellValue)) {
                                entity.setStatus(Long.valueOf(data.getDictValue()));//备注
                                break;
                            }
                        }
                    }else if (j == 16) {
                        entity.setRemarks(cellValue);
                    }}
                entity.setCreaterCode(userId.toString());
                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 (TSpecdevGl t : list
        ) {
            failNum++;
            try {
                tSpecdevGlService.insertTSpecdevGl(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);
    }

}
