package com.ruoyi.project.sems.controller;

 import com.alibaba.fastjson2.JSON;
 import com.ruoyi.common.annotation.Log;
 import com.ruoyi.common.config.RuoYiConfig;
 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.StringUtils;
 import com.ruoyi.common.utils.file.ExcelUtils;
 import com.ruoyi.common.utils.file.FileUploadUtils;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.project.sems.domain.TSpecdevYlgd;
 import com.ruoyi.project.sems.service.ITSpecdevYlgdService;
 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-22
 */
@RestController
@RequestMapping("/sems/specYlgd")
public class TSpecdevYlgdController extends BaseController {
    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;
    @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);
        for (TSpecdevYlgd 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();
                }
            }
        }
        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);
        for (TSpecdevYlgd dev : list) {
            if(StringUtils.isNotEmpty(dev.getIsoPicUrl())){
                dev.setIsoPicUrl("Y");
            }else {
                dev.setIsoPicUrl("NA");
            }
            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<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();
    }

    @Log(title = "文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getFilePath("/specYlgd"), file);
            return AjaxResult.success(avatar);
        }
        return AjaxResult.error("上传异常，请联系管理员");
    }

    /**
     * 批量导入
     */
    @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> 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();
                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) {
                        entity.setPlantCode(cellValue);//
                    } else if (j == 1) {
                        entity.setDevname(cellValue);
                    } else if (j == 2) {
                        entity.setPidNo(cellValue);//
                    } else if (j == 3) {
                        entity.setDevno(cellValue);//
                    } else if (j == 4) {
                        entity.setNextWarnDate(DateUtils.parseDate(cellValue));//
                    } else if (j == 5) {
                        entity.setWarnDate(DateUtils.parseDate(cellValue));//
                    } else if (j == 6) {
                        entity.setStarting(cellValue);//
                    } else if (j == 7) {
                        entity.setEnding(cellValue);//
                    } else if (j == 8) {
                        entity.setReliefValve(cellValue);//
                    } else if (j == 9) {
                        entity.setFitNumber(Long.valueOf(cellValue));//
                    } else if (j == 10) {
                        entity.setWeldNumber(cellValue);//
                    } else if (j == 11) {
                        entity.setGrade(cellValue);//
                    } else if (j == 12) {//
                        entity.setDesigner(cellValue);//
                    } else if (j == 13) {//
                        entity.setInstaller(cellValue);
                    } else if (j == 14) {
                        entity.setInstallDate(DateUtils.parseDate(cellValue));//
                    } else if (j == 15) {
                        entity.setSubmitdate(DateUtils.parseDate(cellValue));//
                    } else if (j == 16) {
                        entity.setDia(cellValue);//
                    } else if (j == 17) {
                        entity.setScheduleNo(cellValue);//
                    } else if (j == 18) {
                        entity.setLength(cellValue);//
                    } else if (j == 19) {
                        entity.setMaterial(cellValue);//
                    } else if (j == 20) {
                        entity.setHeatPreservation(cellValue);//
                    } else if (j == 21) {
                        entity.setThickness(cellValue);//
                    } else if (j == 22) {
                        entity.setDesPressure(cellValue);//
                    } else if (j == 23) {
                        entity.setOptPressure(cellValue);//
                    } else if (j == 25) {
                        entity.setDesTemp(cellValue);//
                    } else if (j == 24) {
                        entity.setOptTemp(cellValue);//
                    } else if (j == 26) {
                        entity.setMedium(cellValue);//
                    } else if (j == 27) {
                        entity.setCheckConclusion(cellValue);//
                    } else if (j == 28) {
                        entity.setCheckUnit(cellValue);
                    } else if (j == 29) {
                        entity.setReportNo(cellValue);//
                    } else if (j == 30) {
                        for (SysDictData data : status) {
                            if (data.getDictLabel().equals(cellValue)) {
                                entity.setStatus(Long.valueOf(data.getDictValue()));//
                                break;
                            }
                        }
                    } else if (j == 31) {
                        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 (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);
    }
}
