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.TSpecdevYlrq;
import com.ruoyi.project.sems.service.ITSpecdevYlrqService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.commons.lang3.StringUtils;
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.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.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 特种设备压力容器台账Controller
 *
 * @author ruoyi
 * @date 2021-06-30
 */
@RestController
@RequestMapping("/sems/specYlrq")
public class TSpecdevYlrqController extends BaseController {
    @Autowired
    private ITSpecdevYlrqService tSpecdevYlrqService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询特种设备压力容器台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevYlrq tSpecdevYlrq) {
        startPage();
        List<TSpecdevYlrq> list = tSpecdevYlrqService.selectTSpecdevYlrqList(tSpecdevYlrq);
        for (TSpecdevYlrq dev : list) {
            if (dev.getNextWarnDate() != null) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date d1 = dev.getNextWarnDate();
                    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();
                }
            }
        }
        //
//        SpecOverLifeThead specOverLifeThead = new SpecOverLifeThead(tSpecdevYlrqService);
//        Thread t = new Thread(specOverLifeThead);
//        t.start();

//        SpecDevYlrqThread specDevYlgdThread = new SpecDevYlrqThread(tSpecdevYlrqService);
//        Thread t2 = new Thread(specDevYlgdThread);
//        t2.start();
        return getDataTable(list);
    }

    /**
     * 导出特种设备压力容器台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:export')")
    @Log(title = "特种设备压力容器台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevYlrq tSpecdevYlrq) {
        List<TSpecdevYlrq> list = tSpecdevYlrqService.selectTSpecdevYlrqList(tSpecdevYlrq);
        for (TSpecdevYlrq dev : list) {
            if (dev.getNextWarnDate() != null) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date d1 = dev.getNextWarnDate();
                    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<TSpecdevYlrq> util = new ExcelUtil<TSpecdevYlrq>(TSpecdevYlrq.class);
        return util.exportExcel(list, "specYlrq");
    }

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

    /**
     * 新增特种设备压力容器台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:add')")
    @Log(title = "特种设备压力容器台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevYlrq tSpecdevYlrq) {
        return toAjax(tSpecdevYlrqService.insertTSpecdevYlrq(tSpecdevYlrq));
    }

    /**
     * 修改特种设备压力容器台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:edit')")
    @Log(title = "特种设备压力容器台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevYlrq tSpecdevYlrq) {
        TSpecdevYlrq old = tSpecdevYlrqService.selectTSpecdevYlrqById(tSpecdevYlrq.getId());
        /*if (!old.getReportNo().equals(tSpecdevYlrq.getReportNo())) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(1l);
            tc.setCheckUnit(tSpecdevYlrq.getCheckUnit());
            tc.setDevId(tSpecdevYlrq.getId());
            tc.setNextWarnDate(tSpecdevYlrq.getNextWarnDate());
            tc.setReportNo(tSpecdevYlrq.getReportNo());
            tc.setWarnDate(tSpecdevYlrq.getWarnDate());
            tc.setYearNextWarnDate(tSpecdevYlrq.getYearNextWarnDate());
            tc.setYearWarnDate(tSpecdevYlrq.getYearWarnDate());
            tc.setYearReportNo(tSpecdevYlrq.getReportNo());
            tc.setSafeClass(tSpecdevYlrq.getSafeClass());
            tSpecCheckService.insertTSpecCheck(tc);
        }*/
        return toAjax(tSpecdevYlrqService.updateTSpecdevYlrq(tSpecdevYlrq));
    }

    /**
     * 修改特种设备压力容器台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:edit')")
    @Log(title = "特种设备压力容器台账", businessType = BusinessType.UPDATE)
    @PutMapping("/pre")
    public AjaxResult editPre(@RequestBody TSpecdevYlrq tSpecdevYlrq) {
        return toAjax(tSpecdevYlrqService.updateTSpecdevYlrq(tSpecdevYlrq));
    }

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

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

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specYlrq:add')")
    @Log(title = "特种设备批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException, ParseException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TSpecdevYlrq> list = new ArrayList<TSpecdevYlrq>();
        //字典查询
        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 = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSpecdevYlrq entity = new TSpecdevYlrq();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    cell.getCellType();
                    String cellValue = ExcelUtils.getCellValue(cell);
                    if (StringUtils.trim(cellValue) == "") {
                        continue;
                    }
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setPlantCode(cellValue);//
                    } else if (j == 1) {
                        entity.setDevno(cellValue);
                    } else if (j == 2) {
                        entity.setPidNo(cellValue);//
                    } else if (j == 3) {
                        for (SysDictData data : status) {
                            if (data.getDictLabel().equals(cellValue)) {
                                entity.setStatus(Long.valueOf(data.getDictValue()));//
                                break;
                            }
                        }
                    } else if (j == 4) {
                        entity.setDevname(cellValue);//
                    } else if (j == 5) {
                        entity.setDevEnname(cellValue);//
                    } else if (j == 6) {
                        entity.setReliefValve(cellValue);//
                    } else if (j == 7) {
                        entity.setUseno(cellValue);//
                    } else if (j == 8) {
                        entity.setRegno(cellValue);//
                    } else if (j == 9) {
                        entity.setFactoryInfo(cellValue);//
                    } else if (j == 10) {
                        entity.setNextWarnDate(DateUtils.parseDate(cellValue));//
                    } else if (j == 11) {
                        entity.setFactoryNo(cellValue);//
                    } else if (j == 12) {
                        entity.setDesignUnit(cellValue);//
                    } else if (j == 13) {
                        entity.setCreateUnit(cellValue);//
                    } else if (j == 14) {
                        entity.setVesselType(cellValue);//
                    } else if (j == 15) {
                        entity.setUseCode(cellValue);//
                    } else if (j == 16) {
                        entity.setPressureGrade(cellValue);//
                    } else if (j == 17) {
                        entity.setSafeClass(cellValue);//
                    } else if (j == 18) {
                        entity.setSubmitdate(DateUtils.parseDate(cellValue));//
                    } else if (j == 19) {
                        entity.setDesYear(cellValue);
                    } else if (j == 20) {
                        entity.setDesignDead(DateUtils.parseDate(cellValue));
                    } else if (j == 21) {
                        entity.setWarnDate(DateUtils.parseDate(cellValue));
                    } else if (j == 22) {
                        entity.setRemarks(cellValue);
                    }
                }
                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 (TSpecdevYlrq t : list
        ) {
            failNum++;
            try {
                tSpecdevYlrqService.insertTSpecdevYlrq(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);
    }

}
