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.TByxWorkcertificate;
import com.ruoyi.project.training.mapper.TByxWorkcertificateMapper;
import com.ruoyi.project.training.service.ITByxWorkcertificateService;
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.util.StringUtils;
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-01
 */
@RestController
@RequestMapping("/training/byxWorkcertificate")
public class TByxWorkcertificateController extends BaseController
{
    @Autowired
    private ITByxWorkcertificateService tByxWorkcertificateService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TByxWorkcertificateMapper tByxWorkcertificateMapper;
    /**
     * 查询作业证书一览列表
     */
    @PreAuthorize("@ss.hasPermi('training:byxWorkcertificate:list')")
    @GetMapping("/list")
    public TableDataInfo list(TByxWorkcertificate tByxWorkcertificate)
    {
        startPage();
        logger.info("tByxWorkcertificate:" + tByxWorkcertificate);
        List<TByxWorkcertificate> list = tByxWorkcertificateService.selectTByxWorkcertificateList(tByxWorkcertificate);
        return getDataTable(list);
    }

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

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


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

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

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

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

    /**
     * 批量导入作业证书一览
     */
    @PreAuthorize("@ss.hasPermi('training:byxWorkcertificate:add')")
    @Log(title = "作业证书一览", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult byxImportData(@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<TByxWorkcertificate> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        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.getLastCellNum();
                if(row==null){
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TByxWorkcertificate entity = new TByxWorkcertificate();
                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.setContainerIdnum(cellValue);//移动式压力容器充装证件号
                    } else if (j == 6) {
                        if (cellValue.length() > 3)
                            entity.setContainerDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//移动式压力容器充装证件有效期
                    } else if (j == 7) {
                        entity.setFireFacilities(cellValue);//消防设施操作
                    } else if (j == 8) {
                        entity.setFireFacilitiesIdnum(cellValue);//消防设施操作证件号
                    } else if (j == 9) {
                        if (cellValue.length() > 3) {
                            entity.setFireFacilitiesDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//消防设施操作证件有效期
                        }
                    } else if (j == 10) {
                        entity.setGuardian(cellValue);//监护人专项培训
                    } else if (j == 11) {
                        entity.setGuardianIdnum(cellValue);//监护人专项培训证件号
                    } else if (j == 12) {
                        if (cellValue.length() > 3) {
                            entity.setBoilvalidity(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//有效期
                        }
                    } else if (j == 13) {
                        if (cellValue.length() > 3) {
                            entity.setForemantrain(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长首次培训日期
                        }
                    } else if (j == 14) {
                        if (cellValue.length() > 3) {
                            entity.setForemanreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长本次复审
                        }
                    } else if (j == 15) {
                        if (cellValue.length() > 3) {
                            entity.setForemannextreview(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//班组长下次复审
                        }
                    } else if (j == 16) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 17) {
                        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 (TByxWorkcertificate t : list
        ) {
            failNum++;
            try {
                TByxWorkcertificate ttt=    tByxWorkcertificateService.selectTByxWorkcertificateByEmployeeid(t.getEmployeeid());
                if(StringUtils.isEmpty(ttt)){
                    tByxWorkcertificateService.insertTByxWorkcertificate(t);
                }else {
                    tByxWorkcertificateService.updateTByxWorkcertificateByEmployeeid(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;
    }

}
