package com.ruoyi.project.training.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
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.domain.TByxWorklicense;
import com.ruoyi.project.training.domain.TTrainingWorklicense;
import com.ruoyi.project.training.domain.TWorklicense;
import com.ruoyi.project.training.mapper.TWorklicenseMapper;
import com.ruoyi.project.training.service.ITByxWorklicenseService;
import com.ruoyi.project.training.service.ITWorklicenseService;
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.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 javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 上岗证一览Controller
 *
 * @author ruoyi
 * @date 2020-12-02
 */
@RestController
@RequestMapping("/training/worklicense")
public class TWorklicenseController extends BaseController
{
    @Autowired
    private ITWorklicenseService tWorklicenseService;
    @Autowired
    private ITByxWorklicenseService tByxWorklicenseService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Resource
    private TWorklicenseMapper tWorklicenseMapper;
    /**
     * 查询上岗证一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWorklicense tWorklicense)
    {
        startPage();
        Long e = new Date().getTime() + Long.parseLong("15724800000");
        Date expiringDate = new Date();
        expiringDate.setTime(e);
        tWorklicense.setExpiringDate(expiringDate);
        List<TWorklicense> list = tWorklicenseService.selectTWorklicenseList(tWorklicense);
        return getDataTable(list);
    }

    /**
     * 查询培训成绩列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:list')")
    @GetMapping("/listWorklicense")
    public List<TTrainingWorklicense> listWorklicense(TWorklicense tWorklicense)
    {
        List<TWorklicense> list = tWorklicenseService.selectTWorklicenseList(tWorklicense);
        List<TTrainingWorklicense> tTrainingWorklicenses = new ArrayList<TTrainingWorklicense>();
        if (list.size() > 0) {
            if ("1".equals(list.get(0).getBoiler())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
                tTrainingWorklicense.setId(list.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("裂解");
                tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getCrackingIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(list.get(0).getCracking())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setId(list.get(0).getId());
                tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("压缩");
                tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getCrackingIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(list.get(0).getHotarea())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
                tTrainingWorklicense.setId(list.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("分离");
                tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getCrackingIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(list.get(0).getColdarea())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
                tTrainingWorklicense.setId(list.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("PGU/AEU");
                tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getCrackingIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
        }
        TByxWorklicense byxWorklicense = new TByxWorklicense();
        byxWorklicense.setEmployeeid(tWorklicense.getEmployeeid());
        List<TByxWorklicense> byxList = tByxWorklicenseService.selectTByxWorklicenseList(byxWorklicense);
        if (byxList.size() > 0) {
            if ("1".equals(byxList.get(0).getContainer())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(byxList.get(0).getId());
                tTrainingWorklicense.setId(byxList.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("压力容器");
                tTrainingWorklicense.setWorklicenseIdnum(byxList.get(0).getContainerIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(byxList.get(0).getPipe())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(byxList.get(0).getId());
                tTrainingWorklicense.setId(byxList.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("压力管道");
                tTrainingWorklicense.setWorklicenseIdnum(byxList.get(0).getPipeIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(byxList.get(0).getBoiler())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(byxList.get(0).getId());
                tTrainingWorklicense.setId(byxList.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("裂解");
                tTrainingWorklicense.setWorklicenseIdnum(byxList.get(0).getBoilerIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
            if ("1".equals(byxList.get(0).getAlkylation())) {
                TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
                tTrainingWorklicense.setWorklicenseId(byxList.get(0).getId());
                tTrainingWorklicense.setId(byxList.get(0).getId());
                tTrainingWorklicense.setWorklicenseType("烷基化");
                tTrainingWorklicense.setWorklicenseIdnum(byxList.get(0).getAlkylationIdnum());
                tTrainingWorklicenses.add(tTrainingWorklicense);
            }
        }
        return tTrainingWorklicenses;
    }

    //统计
    @GetMapping("/licenseData")
    public List<DataEntity> licenseData(Map param)
    {
        param.put("params" , new HashMap<>());
        param.put("type", 1);
        DataEntity data1 = tWorklicenseMapper.selectLicenseData(param);
        data1.setDataName("裂解");
        param.put("type", 2);
        DataEntity data2 = tWorklicenseMapper.selectLicenseData(param);
        data2.setDataName("压缩");
        param.put("type", 3);
        DataEntity data3 = tWorklicenseMapper.selectLicenseData(param);
        data3.setDataName("分离");
        param.put("type", 4);
        DataEntity data4 = tWorklicenseMapper.selectLicenseData(param);
        data4.setDataName("PGU");
        param.put("type", 5);
        DataEntity data5 = tWorklicenseMapper.selectLicenseData(param);
        data5.setDataName("AEU");
        List<DataEntity> list = new ArrayList<>();
        list.add(data1);
        list.add(data2);
        list.add(data3);
        list.add(data4);
        list.add(data5);
        return list;
    }
    @GetMapping("/licensebyxData")
    public List<DataEntity> licensebyxData(Map param)
    {
        param.put("params" , new HashMap<>());
        param.put("type", 1);
        DataEntity data1 = tWorklicenseMapper.selectLicenseData(param);
        data1.setDataName("裂解（裂化）");
        param.put("type", 2);
        DataEntity data2 = tWorklicenseMapper.selectLicenseData(param);
        data2.setDataName("压力容器");
        param.put("type", 3);
        DataEntity data3 = tWorklicenseMapper.selectLicenseData(param);
        data3.setDataName("压力管道");
        param.put("type", 4);
        DataEntity data4 = tWorklicenseMapper.selectLicenseData(param);
        data4.setDataName("烷基化");
        List<DataEntity> list = new ArrayList<>();
        list.add(data1);
        list.add(data2);
        list.add(data3);
        list.add(data4);
        return list;
    }

    /**
     * 导出上岗证一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:export')")
    @Log(title = "上岗证一览", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWorklicense tWorklicense)
    {
        List<TWorklicense> list = tWorklicenseService.selectTWorklicenseList(tWorklicense);
        ExcelUtil<TWorklicense> util = new ExcelUtil<TWorklicense>(TWorklicense.class);
        return util.exportExcel(list, "worklicense");
    }

    @PreAuthorize("@ss.hasPermi('training:worklicense:export')")
    @Log(title = "上岗证一览", businessType = BusinessType.EXPORT)
    @GetMapping("/exportByx")
    public AjaxResult exportByx(TWorklicense tWorklicense) {
        List<TWorklicense> tWorklicenses = tWorklicenseService.selectTWorklicenseList(tWorklicense);
        List<TByxWorklicense> list = JSONArray.parseArray(JSON.toJSONString(tWorklicenses), TByxWorklicense.class);
        ExcelUtil<TByxWorklicense> util = new ExcelUtil<TByxWorklicense>(TByxWorklicense.class);
        return util.exportExcel(list, "worklicense");
    }

    /**
     * 获取上岗证一览详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tWorklicenseService.selectTWorklicenseById(id));
    }

    /**
     * 新增上岗证一览
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:add')")
    @Log(title = "上岗证一览", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWorklicense tWorklicense)
    {
        tWorklicense.setCreaterCode(getUserId().toString());
        return toAjax(tWorklicenseService.insertTWorklicense(tWorklicense));
    }

    /**
     * 修改上岗证一览
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:edit')")
    @Log(title = "上岗证一览", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWorklicense tWorklicense)
    {
        tWorklicense.setUpdaterCode(getUserId().toString());
        tWorklicense.setUpdatedate(new Date());
        return toAjax(tWorklicenseService.updateTWorklicense(tWorklicense));
    }

    /**
     * 删除上岗证一览
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense:remove')")
    @Log(title = "上岗证一览", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWorklicenseService.deleteTWorklicenseByIds(ids));
    }

    /**
     * 批量导入上岗证一览
     */
    @PreAuthorize("@ss.hasPermi('training:worklicense: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<TWorklicense> list = new ArrayList<TWorklicense>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> classes = iSysDictTypeService.selectDictDataByType("CLASSES");
        List<SysDictData> yesno = iSysDictTypeService.selectDictDataByType("YES_NO_EN");
        //部门查询
        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();
                TWorklicense entity = new TWorklicense();
                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.setName(cellValue);//姓名
                    } else if (j == 2) {
                        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.setPost(cellValue);//职务
                    } else if (j == 5) {
                        entity.setIdtype(cellValue);//证件类型
                    } else if (j == 6) {
                        entity.setCompressionIdnum(cellValue);//证件号
                    } else if (j == 7) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setBoiler(p.getDictValue());//裂解
                            }
                        }
                    } else if (j == 8) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCracking(p.getDictValue());//压缩
                            }
                        }
                    } else if (j == 9) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setHotarea(p.getDictValue());//分离
                            }
                        }
                    } else if (j == 10) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setColdarea(p.getDictValue());//PGU
                            }
                        }
                    } else if (j == 11) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setAromatic(p.getDictValue());//AEU
                            }
                        }
                    } else if (j == 12) {
                        if (cellValue.length() > 3) {
                            entity.setRecertificatedate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//取复证日期
                        }
                    } else if (j == 13) {
                        if (cellValue.length() > 3) {
                            entity.setValidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//证书有效期
                        }
                    } else if (j == 14) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 15) {
                        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 (TWorklicense t : list
        ) {
            failNum++;
            try {
                tWorklicenseService.insertTWorklicense(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);
    }
}
