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

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.api.base.bu.IBusiConfigService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.bu3.SxAssistOutAndEnterService;
import cn.estsh.i3plus.ext.mes.icloud.sdk.ICoreSysPushMessageCloud;
import cn.estsh.i3plus.ext.mes.icloud.sdk.ICoreSysUserExtCloud;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesAssistOutAndEnter;
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.MesAssistOutAndEnterRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkCenterExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.apache.poi.ss.usermodel.DataFormatter;
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.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description :援入援出明细记录导入
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class SxAssistOutAndEnterExcelService implements IExcelImportExtService {

    @Autowired
    private MesAssistOutAndEnterRepository assistOutAndEnterRepository;

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private IBusiConfigService busiConfigService;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private ICoreSysUserExtCloud iCoreSysUserExtCloud;

    @Autowired
    private SxAssistOutAndEnterService assistOutAndEnterService;

    @Autowired
    private ICoreSysPushMessageCloud pushMessageCloud;

    /**
     * 援入援出明细记录导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesAssistOutAndEnter(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesAssistOutAndEnter(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 援入援出明细记录导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesAssistOutAndEnter(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesAssistOutAndEnter集合
        List<MesAssistOutAndEnter> partCategoryPlanRateList = new ArrayList<>();

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

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

        List<MesWorkCenterExt> workCenterList = workCenterExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
        Map<String, List<MesWorkCenterExt>> workCenterCodeMap = CollectionUtils.isEmpty(workCenterList) ? null :
                workCenterList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkCenterExt::getWorkCenterCode));

        Map<String, String> ownerDepartmentMap = busiConfigService.getConfigMap(organizeCode, MesExtConstWords.OWNER_DEPARTMENT_CFG);

        //获取用户 userLoginName : userNameRdd
        Map<String,String> loginUserNameMap;
        BaseResultBean baseResultBean = iCoreSysUserExtCloud.queryUserInOrg(organizeCode);
        if (!baseResultBean.success) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("获取用户信息失败,请联系管理员!")
                    .build();
        }
        List<Map<String, Object>> userInfoList = (List<Map<String, Object>>) baseResultBean.getResultList();
        if (CollectionUtils.isEmpty(userInfoList)){
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION_FILE.getCode())
                    .setErrorDetail("用户信息为空,请联系管理员!")
                    .build();
        }
        loginUserNameMap = new HashMap<>();
        userInfoList.forEach(user -> loginUserNameMap.put(user.get(MesExtConstWords.USER_LOGIN_NAME).toString(),user.get(MesExtConstWords.USER_NAME_RDD).toString()));

        String takeOnUserName = null;
        String personResponsibleUserName = null;
        String responsibleMinisterUserName = null;

        //从excel表的第5行数据开始导入，getFirstRowNum是从0行开始读取
        for (int i = (sheetAt.getFirstRowNum() + 4); 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 workCenterCode;
                try {
                    workCenterCode = new DataFormatter().formatCellValue(row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

                //援入援出明细项
                String assistOutAndEnterDetail = null;
                try {
                    assistOutAndEnterDetail = new DataFormatter().formatCellValue(row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //责任部门
                String ownerDepartment = null;
                try {
                    ownerDepartment = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //工作内容
                String workContent = null;
                try {
                    workContent = new DataFormatter().formatCellValue(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //开始时间
                String startTime = null;
                try {
                    startTime = new DataFormatter().formatCellValue(row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //结束时间
                String endTime = null;
                try {
                    endTime = new DataFormatter().formatCellValue(row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //影响人数
                String influenceNumber = null;
                try {
                    influenceNumber = new DataFormatter().formatCellValue(row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //备注
                String cooperation = null;
                try {
                    cooperation = new DataFormatter().formatCellValue(row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //担当
                String takeOn = null;
                try {
                    takeOn = new DataFormatter().formatCellValue(row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //责任人
                String personResponsible = null;
                try {
                    personResponsible = new DataFormatter().formatCellValue(row.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //责任部长
                String responsibleMinister = null;
                try {
                    responsibleMinister = new DataFormatter().formatCellValue(row.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //验证生产线代码
                if (CollectionUtils.isEmpty(workCenterCodeMap) || !workCenterCodeMap.containsKey(workCenterCode)) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }

                //验证援入援出明细项
                if (StringUtils.isEmpty(assistOutAndEnterDetail)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (StringUtils.isEmpty(MesExtEnumUtil.BU_ASSIST_OUT_AND_ENTER_DETAIL.descriptionOfValue(assistOutAndEnterDetail))) {
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                //验证责任部门
                if (StringUtils.isEmpty(ownerDepartment)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(ownerDepartmentMap) || !ownerDepartmentMap.containsKey(ownerDepartment)) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }

                //验证工作内容
                if (StringUtils.isEmpty(workContent)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                }

                //验证开始时间
                if (StringUtils.isEmpty(startTime)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    if (!TimeTool.checkDateFormat(startTime, MesExtConstWords.DATETIME_FORMAT)) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效,请检查时间格式[yyyy-MM-dd HH:mm:00];";
                    } else {
                        if (!startTime.substring(16, 19).equals(MesExtConstWords.APPEND_SECONDS)) {
                            errorNum ++;
                            cellNum += "E;";
                            errorInfo += "第E列数据无效,请检查时间格式[yyyy-MM-dd HH:mm:00];";
                        }
                    }
                }

                //验证结束时间
                if (StringUtils.isEmpty(endTime)) {
                    errorNum ++;
                    cellNum += "F;";
                    errorInfo += "第F列数据必填;";
                } else {
                    if (!TimeTool.checkDateFormat(endTime, MesExtConstWords.DATETIME_FORMAT)) {
                        errorNum ++;
                        cellNum += "F;";
                        errorInfo += "第F列数据无效,请检查时间格式[yyyy-MM-dd HH:mm:00];";
                    } else {
                        if (!endTime.substring(16, 19).equals(MesExtConstWords.APPEND_SECONDS)) {
                            errorNum ++;
                            cellNum += "F;";
                            errorInfo += "第F列数据无效,请检查时间格式[yyyy-MM-dd HH:mm:00];";
                        }
                    }
                }

                Double intervalTime = new Double(0);
                if (!cellNum.contains("E") && !cellNum.contains("F")) {
                    if (startTime.compareTo(endTime) >= 0) {
                        errorNum ++;
                        cellNum += "E+F;";
                        errorInfo += "第E+F列数据无效,开始时间必须小于结束时间;";
                    } else {
                        try {
                            intervalTime = new Double(TimeTool.getSecoundsBetweenTime(2, startTime, endTime));
                        } catch (ParseException e) {
                            errorNum ++;
                            cellNum += "E+F;";
                            errorInfo += String.format("第E+F列数据无效,计算影响时间发生异常%s;", e.getMessage());
                        }
                    }
                }

                //验证影响人数
                if (StringUtils.isEmpty(influenceNumber)) {
                    errorNum ++;
                    cellNum += "G;";
                    errorInfo += "第G列数据必填;";
                } else {
                    try {
                        Integer.valueOf(influenceNumber);
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "G;";
                        errorInfo += "第G列数据无效;";
                    }
                }

                //验证担当
                if (StringUtils.isEmpty(takeOn)) {
                    errorNum ++;
                    cellNum += "H;";
                    errorInfo += "第H列数据必填;";
                } else {
                    try {
                        for (String loginName : takeOn.split(",")) {
                            if (!loginUserNameMap.containsKey(loginName)){
                                errorNum ++;
                                cellNum += "H;";
                                errorInfo += String.format("第H列用户[%s]不存在;",loginName);
                            }else takeOnUserName += (loginUserNameMap.get(loginName))+ ",";
                        }
                    }catch (Exception e){
                        errorNum ++;
                        cellNum += "H;";
                        errorInfo += "第H列数据不符合格式要求;";
                    }
                }

                //验证责任人
                if (StringUtils.isEmpty(personResponsible)) {
                    errorNum ++;
                    cellNum += "I;";
                    errorInfo += "第I列数据必填;";
                } else {
                    try {
                        for (String loginName : personResponsible.split(",")) {
                            if (!loginUserNameMap.containsKey(loginName)){
                                errorNum ++;
                                cellNum += "H;";
                                errorInfo += String.format("第I列用户[%s]不存在;",loginName);
                            }else personResponsibleUserName += (loginUserNameMap.get(loginName))+ ",";
                        }
                    }catch (Exception e){
                        errorNum ++;
                        cellNum += "I;";
                        errorInfo += "第I列数据不符合格式要求;";
                    }
                }

                //验证责任部长
                if (StringUtils.isEmpty(responsibleMinister)) {
                    errorNum ++;
                    cellNum += "J;";
                    errorInfo += "第J列数据必填;";
                } else {
                    try {
                        for (String loginName : responsibleMinister.split(",")) {
                            if (!loginUserNameMap.containsKey(loginName)){
                                errorNum ++;
                                cellNum += "J;";
                                errorInfo += String.format("第J列用户[%s]不存在;",loginName);
                            }else responsibleMinisterUserName += (loginUserNameMap.get(loginName))+ ",";
                        }
                    }catch (Exception e){
                        errorNum ++;
                        cellNum += "J;";
                        errorInfo += "第J列数据不符合格式要求;";
                    }
                }

                //没有错误的时候，封装MesAssistOutAndEnter
                if (errorNum == 0) {
                    MesAssistOutAndEnter assistOutAndEnter = new MesAssistOutAndEnter();
                    assistOutAndEnter.setWorkCenterCode(workCenterCode);
                    assistOutAndEnter.setWorkCenterName(workCenterCodeMap.get(workCenterCode).get(0).getWorkCenterName());
                    assistOutAndEnter.setAssistOutAndEnterDetail(MesExtEnumUtil.BU_ASSIST_OUT_AND_ENTER_DETAIL.descriptionOfValue(assistOutAndEnterDetail));
                    assistOutAndEnter.setOwnerDepartment(ownerDepartment);
                    assistOutAndEnter.setWorkContent(workContent);
                    assistOutAndEnter.setStartTime(startTime);
                    assistOutAndEnter.setEndTime(endTime);
                    assistOutAndEnter.setInfluenceDate(startTime.substring(0, 10));
                    assistOutAndEnter.setInfluenceNumber(Integer.valueOf(influenceNumber));
                    assistOutAndEnter.setIntervalTime(intervalTime);
                    assistOutAndEnter.setInfluenceTime(MathOperation.mul(intervalTime, new Double(assistOutAndEnter.getInfluenceNumber())));
                    assistOutAndEnter.setPersonnelCost(workCenterCodeMap.get(workCenterCode).get(0).getPersonnelCost());
                    assistOutAndEnter.setAmount(StringUtils.isEmpty(assistOutAndEnter.getPersonnelCost()) ? new Double(0) :
                            MathOperation.mul(assistOutAndEnter.getInfluenceTime(), new Double(assistOutAndEnter.getPersonnelCost())));
                    assistOutAndEnter.setOrganizeCode(organizeCode);
                    assistOutAndEnter.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    assistOutAndEnter.setCooperation(StringUtils.isEmpty(cooperation) ? "" : cooperation);
                    assistOutAndEnter.setTakeOn(takeOn);
                    assistOutAndEnter.setPersonResponsible(personResponsible);
                    assistOutAndEnter.setResponsibleMinister(responsibleMinister);
                    assistOutAndEnter.setTakeOnUserName(takeOnUserName.substring(0,takeOnUserName.length()-1));
                    assistOutAndEnter.setPersonResponsibleUserName(personResponsibleUserName.substring(0,personResponsibleUserName.length()-1));
                    assistOutAndEnter.setResponsibleMinisterUserName(responsibleMinisterUserName.substring(0,responsibleMinisterUserName.length()-1));
                    assistOutAndEnter.setCategoryCode(workCenterCodeMap.get(workCenterCode).get(0).getCategoryCode());
                    assistOutAndEnter.setCareerCode(workCenterCodeMap.get(workCenterCode).get(0).getCareerCode());
                    ConvertBean.serviceModelInitialize(assistOutAndEnter, userName);

                    takeOnUserName = null;
                    personResponsibleUserName = null;
                    responsibleMinisterUserName = null;

                    partCategoryPlanRateList.add(assistOutAndEnter);

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

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

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

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

    /**
     * 援入援出明细记录导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesAssistOutAndEnter(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesAssistOutAndEnter> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                Map<String, String> ownerDepartmentMap = busiConfigService.getConfigMap(excelList.get(0).getOrganizeCode(), MesExtConstWords.OWNER_DEPARTMENT_CFG);
                for (MesAssistOutAndEnter assistOutAndEnter : excelList) {
                    assistOutAndEnterRepository.insert(assistOutAndEnter);
                }
                //新增完后统一推送
                for (MesAssistOutAndEnter assistOutAndEnter : excelList) {
                    pushMessageCloud.pushMessage(assistOutAndEnterService.getAssistOutAndEnterDingPushInfo(assistOutAndEnter,null,ownerDepartmentMap == null ? new HashMap<>() : ownerDepartmentMap));
                }
            }
        }
    }
}
