package com.ruoyi.project.process.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.common.domain.DataEntity;
import com.ruoyi.project.common.domain.TCommonfile;
import com.ruoyi.project.common.service.ITCommonfileService;
import com.ruoyi.project.process.mapper.TMocMapper;
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 com.ruoyi.project.training.domain.TTraining;
import com.ruoyi.project.training.service.ITTrainingService;
import org.apache.commons.lang.StringUtils;
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.process.domain.TMoc;
import com.ruoyi.project.process.service.ITMocService;
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;

import javax.annotation.Resource;

/**
 * MOC管理Controller
 *
 * @author ruoyi
 * @date 2020-12-07
 */
@RestController
@RequestMapping("/process/moc")
public class TMocController extends BaseController
{
    @Autowired
    private ITMocService tMocService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Resource
    private TMocMapper tMocMapper;

    @Autowired
    private ITTrainingService tTrainingService;

    @Autowired
    private ITCommonfileService commonfileService;

    /**
     * 查询MOC管理列表
     */
    @PreAuthorize("@ss.hasPermi('process:moc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TMoc tMoc)
    {
        startPage();
        List<TMoc> list = tMocService.selectTMocList(tMoc);
        for (TMoc m : list) {
            TCommonfile commonfile = new TCommonfile();
            commonfile.setpId(m.getId());
            if (m.getEhsCheck() != null) {
                commonfile.setpType("moc-ehsCheck");
                List<TCommonfile> commonfilesEhsCheck = commonfileService.selectAllFileList(commonfile);
                if (commonfilesEhsCheck.size() == 0) {
                    m.setIsEhsCheck("1");
                }
            }
            if (m.getTraining() != null) {
                commonfile.setpType("moc-training");
                List<TCommonfile> commonfilesTraining = commonfileService.selectAllFileList(commonfile);
                if (commonfilesTraining.size() == 0) {
                    m.setIsTraining("1");
                }
            }
            if (m.getPssr() != null) {
                commonfile.setpType("moc-pssr");
                List<TCommonfile> commonfilesPssr = commonfileService.selectAllFileList(commonfile);
                if (commonfilesPssr.size() == 0) {
                    m.setIsPssr("1");
                }
            }
        }
        return getDataTable(list);
    }

    //申请年份统计
    @GetMapping("/yearData")
    public List<DataEntity> engData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tMocMapper.selectYearData(param);
        return list;
    }

    //情况统计
    @GetMapping("/trueStateData")
    public List<DataEntity> trueStateData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tMocMapper.selectTrueStateData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("MOC_STATE");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //变更统计
    @GetMapping("/changeData")
    public List<DataEntity> changeData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tMocMapper.selectChangeData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("MOC_CHANGE");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //变更统计
    @GetMapping("/categoryData")
    public List<DataEntity> categoryData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tMocMapper.selectCategoryData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("MOC_CATEGORY");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //风险统计
    @GetMapping("/riskData")
    public List<DataEntity> riskData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tMocMapper.selectRiskData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("MOC_RISKLEVEL");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }
    /**
     * 导出MOC管理列表
     */
    @PreAuthorize("@ss.hasPermi('process:moc:export')")
    @Log(title = "MOC管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TMoc tMoc)
    {
        List<TMoc> list = tMocService.selectTMocList(tMoc);
        ExcelUtil<TMoc> util = new ExcelUtil<TMoc>(TMoc.class);
        return util.exportExcel(list, "moc");
    }

    /**
     * 获取MOC管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:moc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tMocService.selectTMocById(id));
    }

    /**
     * 新增MOC管理
     */
    @PreAuthorize("@ss.hasPermi('process:moc:add')")
    @Log(title = "MOC管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMoc tMoc)
    {
        tMoc.setCreaterCode(getUserId().toString());
        TTraining tTraining = new TTraining();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        tTraining.setPlantCode(tMoc.getPlantCode());
        tTraining.setCourseid(tMoc.getMocNo());
        tTraining.setYear(sdf.format(new Date()));;
        tTraining.setCourse("MOC培训");
        tTraining.setTrainingType("12");
        tTraining.setContent(tMoc.getTitle());
        tTraining.setIsfinish(Long.parseLong("0"));
        tTraining.setDeptId(tMoc.getDeptId());
        tTrainingService.insertTTraining(tTraining);
        return toAjax(tMocService.insertTMoc(tMoc));
    }

    /**
     * 修改MOC管理
     */
    @PreAuthorize("@ss.hasPermi('process:moc:edit')")
    @Log(title = "MOC管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMoc tMoc)
    {
        tMoc.setUpdaterCode(getUserId().toString());
        tMoc.setUpdatedate(new Date());
        if (tMoc.getChangeNature().equals("12")) {
            tMoc.setTemporaryState("14");
        }
        return toAjax(tMocService.updateTMoc(tMoc));
    }

    /**
     * 删除MOC管理
     */
    @PreAuthorize("@ss.hasPermi('process:moc:remove')")
    @Log(title = "MOC管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tMocService.deleteTMocByIds(ids));
    }

    /**
     * 批量导入MOC管理
     */
    @PreAuthorize("@ss.hasPermi('process:moc:add')")
    @Log(title = "MOC管理", 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<TMoc> list = new ArrayList<TMoc>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> state = iSysDictTypeService.selectDictDataByType("MOC_STATE");
        List<SysDictData> change = iSysDictTypeService.selectDictDataByType("MOC_CHANGE");
        List<SysDictData> risklevel = iSysDictTypeService.selectDictDataByType("MOC_RISKLEVEL");
        List<SysDictData> area = iSysDictTypeService.selectDictDataByType("MOC_AREA");
        List<SysDictData> temporarystate = iSysDictTypeService.selectDictDataByType("MOC_TEMPORARYSTATE");
        List<SysDictData> yesno = iSysDictTypeService.selectDictDataByType("YES_NO");
        //部门查询
        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.getPhysicalNumberOfCells();
                TMoc entity = new TMoc();
                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) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        entity.setMocNo(cellValue);//MOC编号
                    } else if (j == 2) {
                        for (SysDictData a : area) {
                            if (a.getDictLabel().equals(cellValue.trim())) {
                                entity.setArea(a.getDictValue());//区域
                            }
                        }
                    } else if (j == 3) {
                        entity.setTitle(cellValue);//标题
                    } else if (j == 4) {
                        entity.setOwner(cellValue);//负责人
                    } else if (j == 5) {
                        if (cellValue.length() > 3) {
                            entity.setApproveTime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//申请时间
                        }
                    } else if (j == 6) {
                        if (cellValue.length() > 3) {
                            entity.setEndtime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//完成时间
                        }
                    } else if (j == 7) {
                        for (SysDictData s : state) {
                            if (s.getDictLabel().equals(cellValue.trim())) {
                                entity.setTrueState(s.getDictValue());//实施情况
                            }
                        }
                    } else if (j == 8) {
                        for (SysDictData c : change) {
                            if (c.getDictLabel().equals(cellValue.trim())) {
                                entity.setChangeNature(c.getDictValue());//变更性质
                            }
                        }
                    } else if (j == 9) {
                        if (cellValue.length() > 3) {
                            entity.setOverTime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//到期时间
                        }
                    } else if (j == 10) {
                        for (SysDictData t : temporarystate) {
                            if (t.getDictLabel().equals(cellValue.trim())) {
                                entity.setTemporaryState(t.getDictValue());//临时moc状态
                            }
                        }
                    } else if (j == 11) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 12) {
                        for (SysDictData r : risklevel) {
                            if (r.getDictLabel().equals(cellValue.trim())) {
                                entity.setRiskLevel(r.getDictValue());//风险等级
                            }
                        }
                    } else if (j == 13) {
                        if (cellValue.length() > 3) {
                            entity.setEhsCheck(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//EHS审查
                        }
                    } else if (j == 14) {
                        if (cellValue.length() > 3) {
                            entity.setTraining(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//培训
                        }
                    } else if (j == 15) {
                        if (cellValue.length() > 3) {
                            entity.setPssr(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//PSSR
                        }
                    } else if (j == 16) {
                        for (SysDictData y : yesno) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setSopUpdate(y.getDictValue());//SOP更新
                            }
                        }
                    } else if (j == 17) {
                        for (SysDictData y : yesno) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setPidMaster(y.getDictValue());//PID更新
                            }
                        }
                    } else if (j == 18) {
                        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 (TMoc t : list
        ) {
            failNum++;
            try {
                tMocService.insertTMoc(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);
    }
}
