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.TSpecdevDt;
import com.ruoyi.project.sems.service.ITSpecdevDtService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictTypeService;
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.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 特种设备电梯台账Controller
 *
 * @author ruoyi
 * @date 2021-07-26
 */
@RestController
@RequestMapping("/sems/specDt")
public class TSpecdevDtController extends BaseController {
    @Autowired
    private ITSpecdevDtService tSpecdevDtService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询特种设备电梯台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specDt:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevDt tSpecdevDt) {
        startPage();
        List<TSpecdevDt> list = tSpecdevDtService.selectTSpecdevDtList(tSpecdevDt);
        for (TSpecdevDt 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:specDt:export')")
    @Log(title = "特种设备电梯台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevDt tSpecdevDt) {
        List<TSpecdevDt> list = tSpecdevDtService.selectTSpecdevDtList(tSpecdevDt);
        for (TSpecdevDt 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<TSpecdevDt> util = new ExcelUtil<TSpecdevDt>(TSpecdevDt.class);
        return util.exportExcel(list, "specDt");
    }

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

    /**
     * 新增特种设备电梯台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specDt:add')")
    @Log(title = "特种设备电梯台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevDt tSpecdevDt) {
        return toAjax(tSpecdevDtService.insertTSpecdevDt(tSpecdevDt));
    }

    /**
     * 修改特种设备电梯台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specDt:edit')")
    @Log(title = "特种设备电梯台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevDt tSpecdevDt) {
        /*TSpecdevDt old = tSpecdevDtService.selectTSpecdevDtById(tSpecdevDt.getId());
        if (!old.getReportNo().equals(tSpecdevDt.getReportNo())) {
            TSpecCheck tc = new TSpecCheck();
            tc.setDevType(5l);
            tc.setCheckUnit(tSpecdevDt.getCheckUnit());
            tc.setDevId(tSpecdevDt.getId());
            tc.setNextWarnDate(tSpecdevDt.getNextWarnDate());
            tc.setReportNo(tSpecdevDt.getReportNo());
            tc.setWarnDate(tSpecdevDt.getWarnDate());
            tSpecCheckService.insertTSpecCheck(tc);
        }*/
        return toAjax(tSpecdevDtService.updateTSpecdevDt(tSpecdevDt));
    }

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

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

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specDt: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<TSpecdevDt> list = new ArrayList<TSpecdevDt>();
        //字典查询
        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();
                TSpecdevDt entity = new TSpecdevDt();
                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.setModel(cellValue);
                    } else if (j == 2) {
                        entity.setUseDept(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.setNextWarnDate(DateUtils.parseDate(cellValue));// 使用部门
                    } else if (j == 5) {
                        entity.setPlateNo(cellValue);// 装置维修组
                    } else if (j == 6) {
                        entity.setRegno(cellValue);//名称
                    } else if (j == 7) {
                        entity.setFactoryInfo(cellValue);//设备注册编号
                    } else if (j == 8) {
                        entity.setEngineNo(cellValue);//型号
                    } else if (j == 9) {
                        entity.setExGrade(cellValue);//额定载重
                    } else if (j == 10) {
                        entity.setCreateUnit(cellValue);//层站数
                    } else if (j == 11) {
                        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 (TSpecdevDt t : list
        ) {
            failNum++;
            try {
                tSpecdevDtService.insertTSpecdevDt(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);
    }

}
