package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.excel.bu;

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEmployeeNature;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEmployeeSkillsManagement;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesSkillsManagementBenchmark;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkCenterExt;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportErrorExtModel;
import cn.estsh.i3plus.ext.mes.pojo.model.ExcelImportResultExtModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEmployeeNatureRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEmployeeSkillsManagementRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesSkillsManagementBenchmarkRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.apache.poi.ss.usermodel.CellType;
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.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-13 10:04
 */
@Service
public class MesEmployeeSkillsManagementExcelService implements IExcelImportExtService {

    @Autowired
    private CommonExtService commonService;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesEmployeeSkillsManagementRepository employeeSkillsManagementRepository;

    @Autowired
    private MesEmployeeNatureRepository employeeNatureRepository;

    @Autowired
    private MesSkillsManagementBenchmarkRepository skillsManagementBenchmarkRepository;

    /**
     * 员工技能管理信息导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultModel = this.sheetExtractMesEmployeeSkillsManagement(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesEmployeeSkillsManagement(excelImportResultModel);
        return excelImportResultModel;
    }

    /**
     * 员工技能管理信息导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesEmployeeSkillsManagement(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //员工技能管理信息 集合
        List<MesEmployeeSkillsManagement> employeeSkillsManagements = new ArrayList<>();

        //成功数量
        Integer successRowNum = 0;
        //失败数量
        Integer failRowNum = 0;
        //错误的行号
        String errorRows = "";

        //错误行信息集合
        List<ExcelImportErrorExtModel> excelImportErrorModels = new ArrayList<>();

        //用于EXCEL表中的员工技能管理代码唯一校验，key：seq、workCenterCode、employeeCode，value：row
        Map<String,String> employeeSkillsManagementMap = new HashMap<>();

        //用于EXCEL表中的员工技能管理代码唯一校验，key：seq、workCenterCode，value：row
        Map<String,String> employeeSkillsManagementNoContainEmpMap = new HashMap<>();


        //员工技能管理数据
        List<MesEmployeeSkillsManagement> employeeSkillsManagementDbs = employeeSkillsManagementRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesEmployeeSkillsManagement>> employeeSkillsManagementDbMap = employeeSkillsManagementDbs.stream().collect(Collectors.groupingBy(o -> (new StringJoiner(MesExtConstWords.AND).add(o.getSeq().toString()).add(o.getWorkCenterCode()).add(o.getEmployeeCode())).toString()));

        Map<String, List<MesEmployeeSkillsManagement>> employeeSkillsManagementNotContainEmpMap = employeeSkillsManagementDbs.stream().collect(Collectors.groupingBy(o -> (new StringJoiner(MesExtConstWords.AND).add(o.getSeq().toString()).add(o.getWorkCenterCode())).toString()));

        Map<String, List<MesEmployeeSkillsManagement>> employeeSkillsManagementMapByEmp = employeeSkillsManagementDbs.stream().collect(Collectors.groupingBy(MesEmployeeSkillsManagement::getEmployeeCode));
        //根据员工代码分类员工技能信息
//        Map<String, List<MesEmployeeSkillsManagement>> employeeSkillsManagementByEmployeeCodeMap = employeeSkillsManagementDbs.stream().collect(Collectors.groupingBy(MesEmployeeSkillsManagement::getEmployeeCode));

        //员工性质数据
        List<MesEmployeeNature> employeeNatureList = employeeNatureRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesEmployeeNature>> employeeNatureMap = employeeNatureList.stream().collect(Collectors.groupingBy(MesEmployeeNature::getEmployeeNatureCode));

        //技能管理基准
        List<MesSkillsManagementBenchmark> skillsManagementBenchmarks = skillsManagementBenchmarkRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesSkillsManagementBenchmark>> skillsManagementBenchmarkMap = skillsManagementBenchmarks.stream().collect(Collectors.groupingBy(MesSkillsManagementBenchmark::getSkillLevel));

        //查询产线信息
        List<MesWorkCenterExt> workCenterExtList = workCenterExtRepository.findByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        //产线代码集合
        List<String> workCenterCodeList = workCenterExtList.stream().map(MesWorkCenterExt::getWorkCenterCode).collect(Collectors.toList());

        //从excel表的第2行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 1); i < totalNumberOfRows; i ++) {
            Row row = sheetAt.getRow(i);
            //空行跳过
            if (null == row) {
                continue;
            }
            //获取总列数
            Short lastCellNum = row.getLastCellNum();
            if (lastCellNum > 0) {

                int rowNum = i + 1;    //当前行号
                int errorNum = 0;      //错误数量
                String cellNum = "";   //错误列号
                String errorInfo = ""; //错误信息

                //序号
                String seq = null;
                try {
                    row.getCell(0).setCellType(CellType.STRING);
                    seq = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //员工代码
                String employeeCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    employeeCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //员工名称
                String employeeName = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    employeeName = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //员工性质代码
                String employeeNatureCode = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    employeeNatureCode = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //技能水平
                String skillLevel = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    skillLevel = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //产线代码
                String workCenterCode = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    workCenterCode = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                if(StringUtils.isEmpty(seq)){
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }else{
                    try {
                        Integer.valueOf(seq);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据无效;";
                    }
                }

                //校验产线
                if (StringUtils.isEmpty(employeeCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }

                if(StringUtils.isEmpty(employeeName)){
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }

                if(StringUtils.isEmpty(employeeNatureCode)){
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }else{
                    if( CollectionUtils.isEmpty(employeeNatureMap) || !employeeNatureMap.containsKey(employeeNatureCode)){
                        errorNum ++;
                        cellNum += "D;";
                        errorInfo += "第D列数据无效;";
                    }
                }

                if(StringUtils.isEmpty(skillLevel)){
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                }else{
                    if(CollectionUtils.isEmpty(skillsManagementBenchmarkMap) ||  !skillsManagementBenchmarkMap.containsKey(skillLevel)){
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }
                }

                if(StringUtils.isEmpty(workCenterCode)){
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                }else{
                    if(CollectionUtils.isEmpty(workCenterCodeList) ||!workCenterCodeList.contains(workCenterCode)){
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效;";
                    }
                }

                boolean isExist = false;

                boolean isExistNoContainEmp = false;

                //校验 序号+产线代码+员工代码 不重复
                if (!employeeSkillsManagementMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(employeeCode).toString())) {
                    employeeSkillsManagementMap.put(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(employeeCode).toString(), String.valueOf(rowNum));
                    //校验设备代码是否已经存在数据库
                    if (!CollectionUtils.isEmpty(employeeSkillsManagementDbMap) && employeeSkillsManagementDbMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(employeeCode).toString())) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "A+B+F;";
                    errorInfo += "第A+B+F列数据跟第" + employeeSkillsManagementMap.get(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(employeeCode).toString()) + "行的第A+B+F列数据重复;";
                }

                if(!isExist){
                    if(!employeeSkillsManagementNoContainEmpMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).toString())){
                        employeeSkillsManagementNoContainEmpMap.put(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).toString(), String.valueOf(rowNum));
                        //校验seq + 产线代码是否已经存在数据库
                        if(CollectionUtils.isEmpty(employeeSkillsManagementNotContainEmpMap) && employeeSkillsManagementNotContainEmpMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).toString())){
                            if(!CollectionUtils.isEmpty(employeeSkillsManagementMapByEmp) && employeeSkillsManagementMapByEmp.containsKey(employeeCode)){
                                MesEmployeeSkillsManagement employeeSkillsManagement = employeeSkillsManagementMapByEmp.get(employeeCode).get(0);
                                if(!employeeSkillsManagement.getEmployeeCode().equals(employeeCode)){
                                    errorNum ++;
                                    cellNum += "A+F;";
                                    errorInfo += workCenterCode +"产线下的"+ seq +"序号已存在,请重新操作";
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(employeeSkillsManagementMapByEmp) && employeeSkillsManagementMapByEmp.containsKey(employeeCode)) {
                            isExistNoContainEmp = true;
                        }
                    }else{
                        errorNum ++;
                        cellNum += "A+F;";
                        errorInfo += workCenterCode +"产线下的"+ seq +"序号已存在,请重新操作";
                    }
                }

                //没有错误的时候，封装MesSkillKanbanProcessInformation
                if (errorNum == 0) {
                    MesEmployeeSkillsManagement employeeSkillsManagement;
                    if(isExist){
                        employeeSkillsManagement = employeeSkillsManagementDbMap.get(new StringJoiner(MesExtConstWords.AND).add(seq).add(workCenterCode).add(employeeCode).toString()).get(0);
                        ConvertBean.serviceModelUpdate(employeeSkillsManagement,userName);
                    }else {
                        if(isExistNoContainEmp){
                            employeeSkillsManagement = employeeSkillsManagementMapByEmp.get(employeeCode).get(0);
                            ConvertBean.serviceModelUpdate(employeeSkillsManagement,userName);
                        }else{
                            employeeSkillsManagement = new MesEmployeeSkillsManagement();
                            ConvertBean.serviceModelInitialize(employeeSkillsManagement, userName);
                            employeeSkillsManagement.setSeq(Integer.parseInt(seq));
                            employeeSkillsManagement.setEmployeeCode(employeeCode);
                            employeeSkillsManagement.setEmployeeName(employeeName);
                        }
                    }
                    employeeSkillsManagement.setSkillLevel(skillLevel);
                    employeeSkillsManagement.setEmployeeNatureCode(employeeNatureCode);
                    employeeSkillsManagement.setWorkCenterCode(workCenterCode);
                    employeeSkillsManagement.setOrganizeCode(organizeCode);
                    employeeSkillsManagements.add(employeeSkillsManagement);

                    successRowNum ++;
                } else {
                    //封装错误行信息ExcelImportErrorModel
                    excelImportErrorModels = commonService.getExcelImportErrorModels(excelImportErrorModels, rowNum, errorNum, cellNum, errorInfo);

                    errorRows += rowNum + ";";
                    failRowNum ++;
                }
            }
        }

        //校验EXCEL数据
        commonService.checkExcelData(failRowNum, successRowNum, errorRows);

        //封装返回结果
        ExcelImportResultExtModel excelImportResultModel = commonService.getExcelImportResultModel(failRowNum, successRowNum, excelImportErrorModels, errorRows);
        excelImportResultModel.setExcelList((failRowNum > 0) ? null : employeeSkillsManagements);
        return excelImportResultModel;
    }

    /**
     * 员工技能管理信息导入-数据入库
     * @param excelImportResultModel
     */
    private void insertExcelMesEmployeeSkillsManagement(ExcelImportResultExtModel excelImportResultModel) {
        //导入数据
        if (null != excelImportResultModel) {
            List<MesEmployeeSkillsManagement> excelList = excelImportResultModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesEmployeeSkillsManagement employeeSkillsManagement : excelList) {
                    if(StringUtils.isEmpty(employeeSkillsManagement.getId())){
                        employeeSkillsManagementRepository.insert(employeeSkillsManagement);
                    }else{
                        employeeSkillsManagementRepository.update(employeeSkillsManagement);
                    }
                }
            }
        }
    }
}
