package com.ruoyi.project.training.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.project.common.domain.DataEntity;
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.mapper.TWorkcertificateMapper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
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.training.domain.TWorkcertificate;
import com.ruoyi.project.training.service.ITWorkcertificateService;
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;

/**
 * 作业证书一览Controller
 *
 * @author ruoyi
 * @date 2020-12-01
 */
@RestController
@RequestMapping("/training/workcertificate")
public class TWorkcertificateController extends BaseController
{
    @Autowired
    private ITWorkcertificateService tWorkcertificateService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TWorkcertificateMapper tWorkcertificateMapper;
    /**
     * 查询作业证书一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWorkcertificate tWorkcertificate)
    {
        startPage();
        logger.info("tWorkcertificate:" + tWorkcertificate);
        List<TWorkcertificate> list = tWorkcertificateService.selectTWorkcertificateList(tWorkcertificate);
        return getDataTable(list);
    }

    //申请年份统计
    @GetMapping("/cerData")
    public List<DataEntity> cerData(Map param)
    {
        param.put("params" , new HashMap<>());
        param.put("cert", 1);
        DataEntity data1 = tWorkcertificateMapper.selectCerData(param);
        data1.setDataName("锅炉证");
        param.put("cert", 2);
        DataEntity data2 = tWorkcertificateMapper.selectCerData(param);
        data2.setDataName("加氢工艺");
        param.put("cert", 3);
        DataEntity data3 = tWorkcertificateMapper.selectCerData(param);
        data3.setDataName("裂化工艺");
        List<DataEntity> list = new ArrayList<>();
        list.add(data1);
        list.add(data2);
        list.add(data3);
        return list;
    }

    /**
     * 导出作业证书一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:export')")
    @Log(title = "作业证书一览", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWorkcertificate tWorkcertificate)
    {
        List<TWorkcertificate> list = tWorkcertificateService.selectTWorkcertificateList(tWorkcertificate);
        ExcelUtil<TWorkcertificate> util = new ExcelUtil<TWorkcertificate>(TWorkcertificate.class);
        return util.exportExcel(list, "workcertificate");
    }

    /**
     * 获取作业证书一览详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tWorkcertificateService.selectTWorkcertificateById(id));
    }

    /**
     * 新增作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:add')")
    @Log(title = "作业证书一览", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWorkcertificate tWorkcertificate)
    {
        tWorkcertificate.setCreaterCode(getUserId().toString());
        return toAjax(tWorkcertificateService.insertTWorkcertificate(tWorkcertificate));
    }

    /**
     * 修改作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:edit')")
    @Log(title = "作业证书一览", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWorkcertificate tWorkcertificate)
    {
        tWorkcertificate.setUpdaterCode(getUserId().toString());
        tWorkcertificate.setUpdatedate(new Date());
        return toAjax(tWorkcertificateService.updateTWorkcertificate(tWorkcertificate));
    }

    /**
     * 删除作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate:remove')")
    @Log(title = "作业证书一览", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWorkcertificateService.deleteTWorkcertificateByIds(ids));
    }

    /**
     * 批量导入作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:workcertificate: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<TWorkcertificate> list = new ArrayList<TWorkcertificate>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> classes = iSysDictTypeService.selectDictDataByType("CLASSES");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        for (int i = 1; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
             //   int cellNum = row.getPhysicalNumberOfCells();
                if(row==null){
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TWorkcertificate entity = new TWorkcertificate();
                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) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        entity.setName(cellValue);//姓名
                    } else if (j == 2) {
                        cellValue=supplementZero(Integer.parseInt(cellValue));
                        entity.setEmployeeid(cellValue);//员工号
                    } else if (j == 3) {
                        for (SysDictData p : classes) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setClasses(p.getDictValue());//班型
                            }
                        }
                    } else if (j == 4) {
                        entity.setContainer(cellValue);//压力容器
                    } else if (j == 5) {
                        entity.setPipe(cellValue);//压力管道
                    } else if (j == 6) {
                        entity.setIdnum(cellValue);//身份证件号
                    } else if (j == 7) {
                        if (cellValue.length() > 3) {
                            entity.setReviewdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//复证日期
                        }
                    } else if (j == 8) {
                        if (cellValue.length() > 3) {
                            entity.setPipevalidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//有效期
                        }
                    } else if (j == 9) {
                        entity.setBoiler(cellValue);//锅炉证
                    } else if (j == 10) {
                        if (cellValue.length() > 3) {
                            entity.setBoilvalidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//有效期
                        }
                    } else if (j == 11) {
                        entity.setHydrogenation(cellValue);//加氢工艺
                    } else if (j == 12) {
                        if (cellValue.length() > 3) {
                            entity.setHydvalidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//有效期
                        }
                    } else if (j == 13) {
                        if (cellValue.length() > 3) {
                            entity.setHydnextreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次复审
                        }
                    } else if (j == 14) {
                        entity.setCracking(cellValue);//裂化工艺
                    } else if (j == 15) {
                        if (cellValue.length() > 3) {
                            entity.setCrackingvalidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//有效期
                        }
                    } else if (j == 16) {
                        if (cellValue.length() > 3) {
                            entity.setCrackingreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//复审
                        }
                    } else if (j == 17) {
                        if (cellValue.length() > 3) {
                            entity.setForemantrain(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长最近培训日期
                        }
                    } else if (j == 18) {
                        if (cellValue.length() > 3) {
                            entity.setForemanreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长本次复审
                        }
                    } else if (j == 19) {
                        if (cellValue.length() > 3) {
                            entity.setForemannextreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长下次复审
                        }
                    } else if (j == 20) {
                        if (cellValue.length() > 3) {
                            entity.setWaterdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//锅炉水质培训日期
                        }
                    } else if (j == 21) {
                        if (cellValue.length() > 3) {
                            entity.setEnergydate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//锅炉能效培训日期
                        }
                    } else if (j == 22) {
                        if (cellValue.length() > 3) {
                            entity.setRefrigerationdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//制冷作业培训日期
                        }
                    } else if (j == 23) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 24) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                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 (TWorkcertificate t : list
        ) {
            failNum++;
            try {
                TWorkcertificate ttt=    tWorkcertificateService.selectTWorkcertificateByEmployeeid(t.getEmployeeid());
                if(StringUtils.isEmpty(ttt)){
                    tWorkcertificateService.insertTWorkcertificate(t);
                }else {
                    tWorkcertificateService.updateTWorkcertificateByEmployeeid(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));
   //     logger.info("update:"+String.valueOf());
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

    //补全员工编号的前缀 0
    public static String supplementZero(int randomNum){

        String newString = String.format("%0" + 5+ "d", randomNum);

        return newString;
    }

}
