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.TSpecdevCc;
import com.ruoyi.project.sems.service.ITSpecdevCcService;
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/specCc")
public class TSpecdevCcController extends BaseController
{
    @Autowired
    private ITSpecdevCcService tSpecdevCcService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    /**
     * 查询特种设备叉车台账列表
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpecdevCc tSpecdevCc)
    {
        startPage();
        List<TSpecdevCc> list = tSpecdevCcService.selectTSpecdevCcList(tSpecdevCc);
        for (TSpecdevCc 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:specCc:export')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSpecdevCc tSpecdevCc)
    {
        List<TSpecdevCc> list = tSpecdevCcService.selectTSpecdevCcList(tSpecdevCc);
        for (TSpecdevCc 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<TSpecdevCc> util = new ExcelUtil<TSpecdevCc>(TSpecdevCc.class);
        return util.exportExcel(list, "specCc");
    }

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

    /**
     * 新增特种设备叉车台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:add')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSpecdevCc tSpecdevCc)
    {
        return toAjax(tSpecdevCcService.insertTSpecdevCc(tSpecdevCc));
    }

    /**
     * 修改特种设备叉车台账
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc:edit')")
    @Log(title = "特种设备叉车台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSpecdevCc tSpecdevCc)
    {
        return toAjax(tSpecdevCcService.updateTSpecdevCc(tSpecdevCc));
    }

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

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('sems:specCc: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<TSpecdevCc> list = new ArrayList<TSpecdevCc>();
        //字典查询
        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();
                TSpecdevCc entity = new TSpecdevCc();
                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.setDevType(cellValue);
                    } else if (j == 1) {
                        entity.setPlantCode(cellValue);//装置名称
                    } else if (j == 2) {
                        entity.setCarNo(cellValue);//车牌号
                    }else if (j == 3) {
                        entity.setUseDept(cellValue);//使用部门
                    } else if (j == 4) {
                        entity.setModel(cellValue);//型号
                    }else if (j == 5) {
                        entity.setRegno(cellValue);//设备代码
                    } else if (j == 6) {
                        entity.setFrameNo(cellValue);//发动机号
                    } else if (j == 7) {
                        entity.setNextWarnDate(DateUtils.parseDate(cellValue));//下次校验日期
                    } else if (j == 8) {
                        entity.setFactoryInfo(cellValue);//出场资料
                    } else if (j == 9) {
                        entity.setExGrade(cellValue);//防爆级别
                    } else if (j == 10) {
                        entity.setCreateUnit(cellValue);//制造单位
                    } else if (j == 11) {
                        for (SysDictData data : status) {
                            if (data.getDictLabel().equals(cellValue)) {
                                entity.setStatus(Long.valueOf(data.getDictValue()));//状态
                                break;
                            }
                        }
                    } else if (j == 12) {
                        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 (TSpecdevCc t : list
        ) {
            failNum++;
            try {
                tSpecdevCcService.insertTSpecdevCc(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);
    }
}
