package com.ruoyi.project.ehs.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ehs.domain.TIncidentRecords;
import com.ruoyi.project.ehs.service.ITIncidentRecordsService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 事件报告清单Controller
 *
 * @author ruoyi
 * @date 2021-07-27
 */
@RestController
@RequestMapping("/ehs/records")
public class TIncidentRecordsController extends BaseController
{
    @Autowired
    private ITIncidentRecordsService tIncidentRecordsService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询事件报告清单列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:list')")
    @GetMapping("/list")
    public TableDataInfo list(TIncidentRecords tIncidentRecords)
    {
        startPage();
        List<TIncidentRecords> list = tIncidentRecordsService.selectTIncidentRecordsList(tIncidentRecords);
        return getDataTable(list);
    }

    /**
     * 导出事件报告清单列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:export')")
    @Log(title = "事件报告清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TIncidentRecords tIncidentRecords)
    {
        List<TIncidentRecords> list = tIncidentRecordsService.selectTIncidentRecordsList(tIncidentRecords);
        ExcelUtil<TIncidentRecords> util = new ExcelUtil<TIncidentRecords>(TIncidentRecords.class);
        return util.exportExcel(list, "records");
    }

    /**
     * 获取事件报告清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tIncidentRecordsService.selectTIncidentRecordsById(id));
    }

    /**
     * 新增事件报告清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:add')")
    @Log(title = "事件报告清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TIncidentRecords tIncidentRecords)
    {
        return toAjax(tIncidentRecordsService.insertTIncidentRecords(tIncidentRecords));
    }

    /**
     * 修改事件报告清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:edit')")
    @Log(title = "事件报告清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TIncidentRecords tIncidentRecords)
    {
        return toAjax(tIncidentRecordsService.updateTIncidentRecords(tIncidentRecords));
    }

    /**
     * 删除事件报告清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:records:remove')")
    @Log(title = "事件报告清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tIncidentRecordsService.deleteTIncidentRecordsByIds(ids));
    }

    /**
     * 批量导入事件报告清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:records: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<TIncidentRecords> list = new ArrayList<TIncidentRecords>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> yesNoEn = iSysDictTypeService.selectDictDataByType("YES_NO_EN");
        List<SysDictData> incidentClassification = iSysDictTypeService.selectDictDataByType("INCIDENT_CLASSIFICATION");
        List<SysDictData> riskkindNm = iSysDictTypeService.selectDictDataByType("RISKKIND_NM");
        List<SysDictData> oad = iSysDictTypeService.selectDictDataByType("OAD");
        List<SysDictData> actualClassification = iSysDictTypeService.selectDictDataByType("ACTUAL_CLASSIFICATION");
        List<SysDictData> probability = iSysDictTypeService.selectDictDataByType("PROBABILITY");
        List<SysDictData> severity = iSysDictTypeService.selectDictDataByType("SEVERITY");
        List<SysDictData> riskClass = iSysDictTypeService.selectDictDataByType("RISK_CLASS");
        List<SysDictData> potentialLevel = iSysDictTypeService.selectDictDataByType("POTENTIAL_LEVEL");
        //部门查询
        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();
                TIncidentRecords entity = new TIncidentRecords();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        if (cellValue.length() > 3) {
                            entity.setIncidentDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//日期
                        }
                    } else if (j == 1) {
                        entity.setReportNo(cellValue);//事故报告编号
                    } else if (j == 2) {
                        entity.setInvestigationNo(cellValue);//调查报告编号
                    } else if (j == 3) {
                        entity.setCompany(cellValue);//单位
                    } else if (j == 4) {
                        for (SysDictData y : yesNoEn) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setContractor(y.getDictValue());//承包商
                            }
                        }
                    } else if (j == 5) {
                        for (SysDictData c : incidentClassification) {
                            if (c.getDictLabel().equals(cellValue.trim())) {
                                entity.setClassification(c.getDictValue());//事件分类
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData r : riskkindNm) {
                            if (r.getDictLabel().equals(cellValue.trim())) {
                                entity.setRiskKind(r.getDictValue());//未遂事件风险类别
                            }
                        }
                    } else if (j == 7) {
                        entity.setMaterials(cellValue);//物料/作业
                    } else if (j == 8) {
                        entity.setLeakedAmount(cellValue);//漏量
                    } else if (j == 9) {
                        entity.setProcessSafety(cellValue);//工艺安全相关事件
                    } else if (j == 10) {
                        for (SysDictData y : yesNoEn) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setProcessSystem(y.getDictValue());//是否工艺系统
                            }
                        }
                    } else if (j == 11) {
                        for (SysDictData o : oad) {
                            if (o.getDictLabel().equals(cellValue.trim())) {
                                entity.setOad(o.getDictValue());//OAD
                            }
                        }
                    } else if (j == 12) {
                        entity.setBridfing(cellValue);//事件简述/机械/电仪问题
                    } else if (j == 13) {
                        for (SysDictData a : actualClassification) {
                            if (a.getDictLabel().equals(cellValue.trim())) {
                                entity.setActualClassification(a.getDictValue());//实际后果事件分级
                            }
                        }
                    } else if (j == 14) {
                        for (SysDictData a : probability) {
                            if (a.getDictLabel().equals(cellValue.trim())) {
                                entity.setProbability(a.getDictValue());//可能性
                            }
                        }
                    } else if (j == 15) {
                        for (SysDictData s : severity) {
                            if (s.getDictLabel().equals(cellValue.trim())) {
                                entity.setSeverity(s.getDictValue());//严重性
                            }
                        }
                    } else if (j == 16) {
                        for (SysDictData r : riskClass) {
                            if (r.getDictLabel().equals(cellValue.trim())) {
                                entity.setRiskClass(r.getDictValue());//风险等级
                            }
                        }
                    } else if (j == 17) {
                        for (SysDictData p : potentialLevel) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPotentialLevel(p.getDictValue());//潜在后果事件等级
                            }
                        }
                    } else if (j == 18) {
                        entity.setMeasures(cellValue);//对策
                    } else if (j == 19) {
                        entity.setAims(cellValue);//输入AIMS
                    } else if (j == 20) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 21) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TIncidentRecords t : list
        ) {
            failNum++;
            try {
                tIncidentRecordsService.insertTIncidentRecords(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                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);
    }
}
