package com.ruoyi.project.training.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
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 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.training.domain.TSkillevaluation;
import com.ruoyi.project.training.service.ITSkillevaluationService;
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;

/**
 * 岗位人员技能评估Controller
 *
 * @author ruoyi
 * @date 2020-12-08
 */
@RestController
@RequestMapping("/training/skillevaluation")
public class TSkillevaluationController extends BaseController
{
    @Autowired
    private ITSkillevaluationService tSkillevaluationService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询岗位人员技能评估列表
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSkillevaluation tSkillevaluation)
    {
        startPage();
        List<TSkillevaluation> list = tSkillevaluationService.selectTSkillevaluationList(tSkillevaluation);
        return getDataTable(list);
    }

    /**
     * 导出岗位人员技能评估列表
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:export')")
    @Log(title = "岗位人员技能评估", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSkillevaluation tSkillevaluation)
    {
        List<TSkillevaluation> list = tSkillevaluationService.selectTSkillevaluationList(tSkillevaluation);
        ExcelUtil<TSkillevaluation> util = new ExcelUtil<TSkillevaluation>(TSkillevaluation.class);
        return util.exportExcel(list, "skillevaluation");
    }

    /**
     * 获取岗位人员技能评估详细信息
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tSkillevaluationService.selectTSkillevaluationById(id));
    }

    /**
     * 新增岗位人员技能评估
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:add')")
    @Log(title = "岗位人员技能评估", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSkillevaluation tSkillevaluation)
    {
        tSkillevaluation.setCreaterCode(getUserId().toString());
        Long tScore = totalScore(tSkillevaluation.getCrackingBoard()) + totalScore(tSkillevaluation.getCrackingField()) + totalScore(tSkillevaluation.getCompressionBoard())
                + totalScore(tSkillevaluation.getCompressionField()) + totalScore(tSkillevaluation.getSeparationBoard()) + totalScore(tSkillevaluation.getSeparationField())
                + totalScore(tSkillevaluation.getAeuBoard()) + totalScore(tSkillevaluation.getAeuField()) + totalScore(tSkillevaluation.getPguBoard()) + totalScore(tSkillevaluation.getPguField())
                + totalScore(tSkillevaluation.getSubBoard()) + totalScore(tSkillevaluation.getSubField());
        tSkillevaluation.setTotalScore(tScore.toString());
        TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(tSkillevaluation.getStaffid());
        tSkillevaluation.setName(staffmgr.getName());
        tSkillevaluation.setClasses(staffmgr.getTeam());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        if (tSkillevaluation.getYear() == Long.parseLong(sdf.format(new Date()))) {
            staffmgr.setSkillScore(tSkillevaluation.getTotalScore());
            tStaffmgrService.updateTStaffmgr(staffmgr);
        }
        return toAjax(tSkillevaluationService.insertTSkillevaluation(tSkillevaluation));
    }

    /**
     * 修改岗位人员技能评估
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:edit')")
    @Log(title = "岗位人员技能评估", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSkillevaluation tSkillevaluation)
    {
        //修改人修改时间更新
        tSkillevaluation.setUpdaterCode(getUserId().toString());
        tSkillevaluation.setUpdatedate(new Date());
        //总分自动生成
        Long tScore = totalScore(tSkillevaluation.getCrackingBoard()) + totalScore(tSkillevaluation.getCrackingField()) + totalScore(tSkillevaluation.getCompressionBoard())
                + totalScore(tSkillevaluation.getCompressionField()) + totalScore(tSkillevaluation.getSeparationBoard()) + totalScore(tSkillevaluation.getSeparationField())
                + totalScore(tSkillevaluation.getAeuBoard()) + totalScore(tSkillevaluation.getAeuField()) + totalScore(tSkillevaluation.getPguBoard()) + totalScore(tSkillevaluation.getPguField())
                + totalScore(tSkillevaluation.getSubBoard()) + totalScore(tSkillevaluation.getSubField());
        tSkillevaluation.setTotalScore(tScore.toString());
        //人员信息对应
        TStaffmgr staffmgr = tStaffmgrService.selectTStaffmgrByStaffId(tSkillevaluation.getStaffid());
        tSkillevaluation.setName(staffmgr.getName());
        tSkillevaluation.setClasses(staffmgr.getTeam());
        //人员信息人员技能评估字段当年数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        if (tSkillevaluation.getYear() == Long.parseLong(sdf.format(new Date()))) {
            staffmgr.setSkillScore(tSkillevaluation.getTotalScore());
            tStaffmgrService.updateTStaffmgr(staffmgr);
        }
        return toAjax(tSkillevaluationService.updateTSkillevaluation(tSkillevaluation));
    }

    //总分计算规则
    public Long totalScore(Long proficiency) {
        Long score = null;
        if (proficiency == null) { score = Long.parseLong("0"); }
        else if (proficiency == 16) { score = Long.parseLong("5"); }
        else if (proficiency == 14) { score = Long.parseLong("3"); }
        else if (proficiency == 12) { score = Long.parseLong("2"); }
        else if (proficiency == 10) { score = Long.parseLong("1"); }
        return score;
    }

    /**
     * 删除岗位人员技能评估
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation:remove')")
    @Log(title = "岗位人员技能评估", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSkillevaluationService.deleteTSkillevaluationByIds(ids));
    }

    /**
     * 批量导入岗位人员技能评估
     */
    @PreAuthorize("@ss.hasPermi('training:skillevaluation: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<TSkillevaluation> list = new ArrayList<TSkillevaluation>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> percentage = iSysDictTypeService.selectDictDataByType("PERCENTAGE");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        //人员信息查询
        List<TStaffmgr> staffmgrs = tStaffmgrService.selectTStaffmgrList(new TStaffmgr());
        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();
                TSkillevaluation entity = new TSkillevaluation();
                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) {
                        entity.setYear(Long.parseLong(cellValue));//年份
                    } else if (j == 1) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 2) {
                    } else if (j == 3) {
                        for (TStaffmgr s : staffmgrs) {
                            if (s.getName().equals(cellValue.trim())) {
                                if (s.getStaffid().equals(ExcelUtils.getCellValue(row.getCell(2)))) {
                                    entity.setStaffid(s.getStaffid());//员工号
                                    entity.setName(s.getName());//姓名
                                    entity.setClasses(s.getTeam());//班组
                                }
                            }
                        }
                    } else if (j == 4) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCrackingBoard(Long.parseLong(p.getDictValue()));//裂解内操
                            }
                        }
                    } else if (j == 5) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCrackingField(Long.parseLong(p.getDictValue()));//裂解外操
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCompressionBoard(Long.parseLong(p.getDictValue()));//压缩内操
                            }
                        }
                    } else if (j == 7) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCompressionField(Long.parseLong(p.getDictValue()));//压缩外操
                            }
                        }
                    } else if (j == 8) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setSeparationBoard(Long.parseLong(p.getDictValue()));//分离内操
                            }
                        }
                    } else if (j == 9) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setSeparationField(Long.parseLong(p.getDictValue()));//分离外操
                            }
                        }
                    } else if (j == 10) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setAeuBoard(Long.parseLong(p.getDictValue()));//AEU内操
                            }
                        }
                    } else if (j == 11) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setAeuField(Long.parseLong(p.getDictValue()));//AEU外操
                            }
                        }
                    } else if (j == 12) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPguBoard(Long.parseLong(p.getDictValue()));//PFU内操
                            }
                        }
                    } else if (j == 13) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPguField(Long.parseLong(p.getDictValue()));//PFU外操
                            }
                        }
                    } else if (j == 14) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setSubBoard(Long.parseLong(p.getDictValue()));//SUB内操
                            }
                        }
                    } else if (j == 15) {
                        for (SysDictData p : percentage) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setSubField(Long.parseLong(p.getDictValue()));//SUB外操
                            }
                        }
                    } 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);//备注
                    }
                }
                Long tScore = totalScore(entity.getCrackingBoard()) + totalScore(entity.getCrackingField()) + totalScore(entity.getCompressionBoard())
                        + totalScore(entity.getCompressionField()) + totalScore(entity.getSeparationBoard()) + totalScore(entity.getSeparationField())
                        + totalScore(entity.getAeuBoard()) + totalScore(entity.getAeuField()) + totalScore(entity.getPguBoard()) + totalScore(entity.getPguField())
                        + totalScore(entity.getSubBoard()) + totalScore(entity.getSubField());
                entity.setTotalScore(tScore.toString());
                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 (TSkillevaluation t : list
        ) {
            failNum++;
            try {
                tSkillevaluationService.insertTSkillevaluation(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);
    }
}
