package com.ruoyi.project.training.controller;

import com.alibaba.fastjson.JSON;
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.mapper.TByxWorklicenseMapper;
import com.ruoyi.project.training.service.ITByxWorklicenseService;
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/byxWorklicense")
public class TByxWorklicenseController extends BaseController
{
    @Autowired
    private ITByxWorklicenseService tByxWorklicenseService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Resource
    private TByxWorklicenseMapper tByxWorklicenseMapper;
    /**
     * 查询上岗证一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:byxWorklicense:list')")
    @GetMapping("/list")
    public TableDataInfo list(TByxWorklicense tByxWorklicense)
    {
        startPage();
        Long e = new Date().getTime() + Long.parseLong("15724800000");
        Date expiringDate = new Date();
        expiringDate.setTime(e);
        tByxWorklicense.setExpiringDate(expiringDate);
        List<TByxWorklicense> list = tByxWorklicenseService.selectTByxWorklicenseList(tByxWorklicense);
        return getDataTable(list);
    }

    /**
     * 查询培训成绩列表
     */
    @PreAuthorize("@ss.hasPermi('training:trainingrecords:list')")
    @GetMapping("/listByxWorklicense")
    public List<TTrainingWorklicense> listByxWorklicense(TByxWorklicense tByxWorklicense)
    {
        List<TByxWorklicense> list = tByxWorklicenseService.selectTByxWorklicenseList(tByxWorklicense);
        List<TTrainingWorklicense> tTrainingWorklicenses = new ArrayList<TTrainingWorklicense>();
        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).getBoilerIdnum());
            tTrainingWorklicenses.add(tTrainingWorklicense);
        }
        if ("1".equals(list.get(0).getContainer())) {
            TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
            tTrainingWorklicense.setId(list.get(0).getId());
            tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
            tTrainingWorklicense.setWorklicenseType("压力容器");
            tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getContainerIdnum());
            tTrainingWorklicenses.add(tTrainingWorklicense);
        }
        if ("1".equals(list.get(0).getPipe())) {
            TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
            tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
            tTrainingWorklicense.setId(list.get(0).getId());
            tTrainingWorklicense.setWorklicenseType("压力管道");
            tTrainingWorklicense.setWorklicenseIdnum(list.get(0).getPipeIdnum());
            tTrainingWorklicenses.add(tTrainingWorklicense);
        }
        if ("1".equals(list.get(0).getAlkylation())) {
            TTrainingWorklicense tTrainingWorklicense = new TTrainingWorklicense();
            tTrainingWorklicense.setWorklicenseId(list.get(0).getId());
            tTrainingWorklicense.setId(list.get(0).getId());
            tTrainingWorklicense.setWorklicenseType("烷基化");
            tTrainingWorklicense.setWorklicenseIdnum(list.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 = tByxWorklicenseMapper.selectLicenseData(param);
        data1.setDataName("裂解（裂化）");
        param.put("type", 2);
        DataEntity data2 = tByxWorklicenseMapper.selectLicenseData(param);
        data2.setDataName("压力容器");
        param.put("type", 3);
        DataEntity data3 = tByxWorklicenseMapper.selectLicenseData(param);
        data3.setDataName("压力管道");
        param.put("type", 4);
        DataEntity data4 = tByxWorklicenseMapper.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:byxWorklicense:export')")
    @Log(title = "上岗证一览", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TByxWorklicense tByxWorklicense)
    {
        List<TByxWorklicense> list = tByxWorklicenseService.selectTByxWorklicenseList(tByxWorklicense);
        ExcelUtil<TByxWorklicense> util = new ExcelUtil<TByxWorklicense>(TByxWorklicense.class);
        return util.exportExcel(list, "ByxWorklicense");
    }

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

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

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

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

    /**
     * 批量导入上岗证一览
     */
    @PreAuthorize("@ss.hasPermi('training:byxWorklicense: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<TByxWorklicense> list = new ArrayList<TByxWorklicense>();
        //字典查询
        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();
                TByxWorklicense entity = new TByxWorklicense();
                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.setContainerIdnum(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.setContainer(p.getDictValue());//压力容器
                            }
                        }
                    } else if (j == 9) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPipe(p.getDictValue());//压力管道
                            }
                        }
                    } else if (j == 10) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setAlkylation(p.getDictValue());//烷基化
                            }
                        }
                    } 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 (TByxWorklicense t : list
        ) {
            failNum++;
            try {
                tByxWorklicenseService.insertTByxWorklicense(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);
    }
}
