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.MesEmployeeAndProcessBind;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesEmployeeSkillsManagement;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesSkillKanbanProcessInformation;
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.MesEmployeeAndProcessBindRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesEmployeeSkillsManagementRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesSkillKanbanProcessInformationRepository;
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 MesEmployeeAndProcessBindExcelService implements IExcelImportExtService {

    @Autowired
    private CommonExtService commonService;

    @Autowired
    private MesEmployeeAndProcessBindRepository employeeAndProcessBindRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesEmployeeSkillsManagementRepository employeeSkillsManagementRepository;

    @Autowired
    private MesSkillKanbanProcessInformationRepository skillKanbanProcessInformationRepository;

    /**
     * 人员与工序关系信息导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultModel = this.sheetExtractMesEmployeeAndProcessBind(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesEmployeeAndProcessBind(excelImportResultModel);
        return excelImportResultModel;
    }

    /**
     * 人员与工序关系信息导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesEmployeeAndProcessBind(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //人员与工序关系信息 集合
        List<MesEmployeeAndProcessBind> employeeAndProcessBindList = new ArrayList<>();

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

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

        //用于EXCEL表中的人员与工序关系代码唯一校验，key：employeeCode、skillKanbanProcessCode、workCenterCode，value：row
        Map<String,String> employeeAndProcessBindMap = new HashMap<>();

        //人员与工序关系数据
        List<MesEmployeeAndProcessBind> employeeAndProcessBindDbList = employeeAndProcessBindRepository.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<MesEmployeeAndProcessBind>> employeeAndProcessBindDbMap = employeeAndProcessBindDbList.stream().collect(Collectors.groupingBy(o -> (new StringJoiner(MesExtConstWords.AND).add(o.getEmployeeCode()).add(o.getSkillKanbanProcessCode()).add(o.getWorkCenterCode()).toString())));

        //员工技能管理数据
        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>> employeeSkillsManagementByEmployeeCodeMap = employeeSkillsManagementDbs.stream().collect(Collectors.groupingBy(MesEmployeeSkillsManagement::getEmployeeCode));

        //查询产线信息
        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());

        //技能看板工序信息数据
        List<MesSkillKanbanProcessInformation> skillKanbanProcessInformationList = skillKanbanProcessInformationRepository.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<MesSkillKanbanProcessInformation>> skillKanbanProcessInformationMap = skillKanbanProcessInformationList.stream().collect(Collectors.groupingBy(MesSkillKanbanProcessInformation::getSkillKanbanProcessCode));

        //从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 employeeCode = null;
                try {
                    row.getCell(0).setCellType(CellType.STRING);
                    employeeCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //技能看板工序代码
                String skillKanbanProcessCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    skillKanbanProcessCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

                String employeeName = null;
                //校验员工代码有效性
                if (StringUtils.isEmpty(employeeCode)) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                }else{
                    if(!employeeSkillsManagementByEmployeeCodeMap.containsKey(employeeCode)){
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据无效;";
                    }
                }

                //校验技能看板工序代码
                if(StringUtils.isEmpty(skillKanbanProcessCode)){
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }else{
                    if(!skillKanbanProcessInformationMap.containsKey(skillKanbanProcessCode)){
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                //校验产线
                if(StringUtils.isEmpty(workCenterCode)){
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                }else{
                    if(!workCenterCodeList.contains(workCenterCode)){
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }

                boolean isExist = false;
                //校验 员工代码+技能看板工序代码+产线 不重复
                if (!employeeAndProcessBindMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(employeeCode).add(skillKanbanProcessCode).add(workCenterCode).toString())) {
                    employeeAndProcessBindMap.put(new StringJoiner(MesExtConstWords.AND).add(employeeCode).add(skillKanbanProcessCode).add(workCenterCode).toString(), String.valueOf(rowNum));
                    //校验是否已经存在数据库
                    if (!CollectionUtils.isEmpty(employeeAndProcessBindDbMap) && employeeAndProcessBindDbMap.containsKey(new StringJoiner(MesExtConstWords.AND).add(employeeCode).add(skillKanbanProcessCode).add(workCenterCode).toString())) {
                        isExist = true;
                    }
                } else {
                    isExist=  true;
                }

                if (isExist == true){
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A+B+C列数据跟第" + employeeAndProcessBindMap.get(new StringJoiner(MesExtConstWords.AND).add(employeeCode).add(skillKanbanProcessCode).add(workCenterCode).toString()) + "行的第A+B+C列数据重复;";
                }

                //没有错误的时候，封装MesSkillKanbanProcessInformation
                if (errorNum == 0) {

                    MesEmployeeAndProcessBind employeeAndProcessBind;

                    employeeAndProcessBind = new MesEmployeeAndProcessBind();
                    ConvertBean.serviceModelInitialize(employeeAndProcessBind, userName);
                    employeeAndProcessBind.setEmployeeCode(employeeCode);
                    employeeAndProcessBind.setSkillKanbanProcessCode(skillKanbanProcessCode);
                    employeeAndProcessBind.setWorkCenterCode(workCenterCode);
                    employeeAndProcessBind.setOrganizeCode(organizeCode);
                    employeeAndProcessBindList.add(employeeAndProcessBind);

                    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 : employeeAndProcessBindList);
        return excelImportResultModel;
    }

    /**
     * 人员与工序关系信息导入-数据入库
     * @param excelImportResultModel
     */
    private void insertExcelMesEmployeeAndProcessBind(ExcelImportResultExtModel excelImportResultModel) {
        //导入数据
        if (null != excelImportResultModel) {
            List<MesEmployeeAndProcessBind> excelList = excelImportResultModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesEmployeeAndProcessBind employeeAndProcessBind : excelList) {
                    if(StringUtils.isEmpty(employeeAndProcessBind.getId())){
                        employeeAndProcessBindRepository.insert(employeeAndProcessBind);
                    }
                }
            }
        }
    }
}
