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

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.api.base.IPartExtDataService;
import cn.estsh.i3plus.ext.mes.api.busi.bu3.ISxPartExtService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOqcRuleNoteDetail;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOqcRuleNoteDetailTravel;
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.model.bu.PartCategoryModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesOqcRuleNoteDetailRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesOqcRuleNoteDetailTravelRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.bean.MesPartCategory;
import cn.estsh.i3plus.pojo.mes.repository.MesPartRepository;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.BeanUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:出货检验项目导入
 * @Reference:
 * @Author: wangjie
 * @CreateDate: 2019\11\4 10:39
 * @Modify:
 **/
@Service
public class JxOqcProjectExcelService implements IExcelImportExtService {
    @Autowired
    private MesOqcRuleNoteDetailRepository oqcProjectRepository;

    @Autowired
    private MesOqcRuleNoteDetailTravelRepository oqcRuleNoteDetailTravelRepository;

    @Autowired
    private MesPartRepository partExtRepository;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private ISxPartExtService partExtService;

    private static final String ONE =  "1";
    private static final String TWO =  "2";
    private static final String THREE =  "3";
    private static final String FOUR =  "4";
    private static final String FIVE =  "5";

    /**
     * 出货检验项目导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractOqcProject(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelOqcProject(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 出货检验项目导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractOqcProject(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesOqcRuleNoteDetail集合
        List<MesOqcRuleNoteDetail> oqcProjectList = new ArrayList<>();

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

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

        //用于EXCEL表中的 检验类型+物料+产品类别+序号+项目 唯一校验，key：oqcType&partNo&categoryCode3&seq&oqcProject，value：row
        Map<String,String> existMap = new HashMap<>();

        // 查询物料表
        Map<String, Object> partCodeEntityMap;
        try {
            partCodeEntityMap = MesCommonUtil.getCodeEntityMap(partExtRepository, MesExtConstWords.PART_NO, organizeCode, "物料表");
        } catch (Exception e) {
            partCodeEntityMap = null;
        }


        List<MesPartCategory> partCategoryList = partExtService.queryPartCategoryListByType(organizeCode, "Category3");

        //BaseResultBean baseResultBean = mesBaseDataCloud.queryMesPartCategoryByProperties(organizeCode, null, null, "Category3");
        //
        //List<PartCategoryModel> partCategoryList = new ArrayList<>();
        //if (null != baseResultBean && baseResultBean.success) {
        //    List<Object> objectList = baseResultBean.getResultList();
        //    if (!CollectionUtils.isEmpty(objectList)) {
        //        for (Object object : objectList) {
        //            if (null == object) {
        //                continue;
        //            }
        //            PartCategoryModel partCategoryModel = JSONObject.toJavaObject(JSONObject.parseObject(JSON.toJSONString(object)), PartCategoryModel.class);
        //            partCategoryList.add(partCategoryModel);
        //        }
        //    }
        //}

        List<String> categoryCode3List = CollectionUtils.isEmpty(partCategoryList) ? null :
                partCategoryList.stream().filter(o -> null != o).map(MesPartCategory::getCategoryCode).collect(Collectors.toList());

        List<MesOqcRuleNoteDetail> oqcProjectDbList = oqcProjectRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.IS_VAILD.VAILD.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        Map<String, List<MesOqcRuleNoteDetail>> oqcProjectMapByPart = CollectionUtils.isEmpty(oqcProjectDbList) ? null :
                oqcProjectDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOqcNoType()) && MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == o.getOqcNoType()))
                .collect(Collectors.groupingBy(o -> o.getOqcNoType() + "&" + o.getPartNo() + "&" + o.getSeq() + "&" + o.getCheckItem()));
        Map<String, List<MesOqcRuleNoteDetail>> oqcProjectMapByCate = CollectionUtils.isEmpty(oqcProjectDbList) ? null :
                oqcProjectDbList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOqcNoType()) && MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() != o.getOqcNoType()))
                .collect(Collectors.groupingBy(o -> o.getOqcNoType() + "&" + o.getCategoryCode3() + "&" + o.getSeq() + "&" + o.getCheckItem()));

        //从excel表的第2行数据开始导入，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 = ""; //错误信息


                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }

                String oqcType = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();

                //物料编码
                String partNo = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    partNo = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //产品类别
                String categoryCode3 = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    categoryCode3 = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

                String oqcProject = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    oqcProject = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //判断基准
                String standard = null;
                try {
                    row.getCell(5).setCellType(CellType.STRING);
                    standard = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //值类型
                String valueTypeStr = null;
                try {
                    row.getCell(6).setCellType(CellType.STRING);
                    valueTypeStr = row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //进制类型
                String baseTypeStr = null;
                try {
                    row.getCell(7).setCellType(CellType.STRING);
                    baseTypeStr = row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //标准值
                String standardValue = null;

                try {
                    row.getCell(8).setCellType(CellType.STRING);
                    standardValue = row.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //下限值
                String downLimit = null;
                try {
                    row.getCell(9).setCellType(CellType.STRING);
                    downLimit = row.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //上限值
                String upLimit = null;
                try {
                    row.getCell(10).setCellType(CellType.STRING);
                    upLimit = row.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //启用器具
                String appliance = null;
                try {
                    row.getCell(11).setCellType(CellType.STRING);
                    appliance = row.getCell(11, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //备注
                String modifyRemark = null;
                try {
                    row.getCell(12).setCellType(CellType.STRING);
                    modifyRemark = row.getCell(12, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                if (StringUtils.isEmpty(oqcType)) {
                    errorNum++;
                    cellNum += "A;";
                    errorInfo += "第A列数据必填;";
                } else {
                    try {
                        if (StringUtils.isEmpty(MesExtEnumUtil.OQC_CHECK_TYPE.valueOfDescription(Integer.parseInt(oqcType)))) {
                            errorNum++;
                            cellNum += "A;";
                            errorInfo += "第A列数据无效;";
                        } else {
                            if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == Integer.parseInt(oqcType)) {

                                if (StringUtils.isEmpty(partNo)) {
                                    errorNum++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据必填;";
                                } else {
                                    if (CollectionUtils.isEmpty(partCodeEntityMap) || !partCodeEntityMap.containsKey(partNo)) {
                                        errorNum ++;
                                        cellNum += "B;";
                                        errorInfo += "第B列数据无效;";
                                    }else{
                                        categoryCode3 = ((MesPart) partCodeEntityMap.get(partNo)).getCategoryCode3();
                                    }
                                }
                            } else {
                                if (!StringUtils.isEmpty(partNo)) {
                                    errorNum++;
                                    cellNum += "B;";
                                    errorInfo += "第B列数据不可填;";
                                }
                                if (StringUtils.isEmpty(categoryCode3)) {
                                    errorNum++;
                                    cellNum += "C;";
                                    errorInfo += "第C列数据必填;";
                                } else {
                                    if (CollectionUtils.isEmpty(categoryCode3List) || !categoryCode3List.contains(categoryCode3)) {
                                        errorNum++;
                                        cellNum += "C;";
                                        errorInfo += "第C列数据无效;";
                                    }
                                }
                            }
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "A;";
                        errorInfo += "第A列数据无效;";
                    }
                }

                //校验检验顺序
                Double seqD = null;
                try {
                    seqD = Double.parseDouble(seq);
                    String[] seqArr = seqD.toString().split(MesExtConstWords.DECIMAL_POINT);
                    if (null != seqArr && seqArr.length == 2 && seqArr[1].length() > 1) {
                        errorNum++;
                        cellNum += "D;";
                        errorInfo += "第D列数据最多1位小数;";
                    }
                } catch (NumberFormatException e) {
                    errorNum++;
                    cellNum += "D;";
                    errorInfo += "第D列数据无效;";
                }

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

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

                Integer baseType = MesExtEnumUtil.OQC_BASE_TYPE.DECIMALISM.getValue();
                if (!StringUtils.isEmpty(baseTypeStr)) {
                    baseType = MesExtEnumUtil.OQC_BASE_TYPE.descriptionOfValue(baseTypeStr);
                    if (baseType == null) {
                        errorNum++;
                        cellNum += "H;";
                        errorInfo += "进制类型无效;";
                    }
                }

                Integer valueType = MesExtEnumUtil.CHECK_JUDGE_TYPE.descriptionOfValue(valueTypeStr);
                if (StringUtils.isEmpty(valueTypeStr)) {
                    errorNum++;
                    cellNum += "G;";
                    errorInfo += "第G列数据必填;";
                }else{
                    if (valueType == null) {
                        errorNum++;
                        cellNum += "G;";
                        errorInfo += "第G列数据无效;";
                    }else if(valueType == (MesExtEnumUtil.CHECK_JUDGE_TYPE.COMPARE_TYPE.getValue())){
                        try{
                            //标准值
                            Double standardValueCheck = null;

                            //上限值
                            Double upLimitCheck = null;

                            //下限值
                            Double downLimitCheck = null;

                            if(!StringUtils.isEmpty(standardValue)){

                                try {
                                    standardValueCheck =  baseConvertToDecimalism(standardValue, baseType);
                                } catch (Exception e) {
                                    errorNum++;
                                    cellNum += "I;";
                                    errorInfo += "第I列数据无效,十进制最多3位小数,十六进制值无效;";
                                }

                                String[] standardArray = standardValue.split(MesExtConstWords.DECIMAL_POINT);
                                if (null != standardArray && standardArray.length == 2 && standardArray[1].length() > 3) {
                                    errorNum++;
                                    cellNum += "I;";
                                    errorInfo += "第I列数据无效,最多3位小数;";
                                }
                            }

                            int num = 0;
                            if(!StringUtils.isEmpty(upLimit)){

                                try {
                                    upLimitCheck =  baseConvertToDecimalism(upLimit, baseType);
                                } catch (Exception e) {
                                    errorNum++;
                                    cellNum += "K;";
                                    errorInfo += "第K列数据无效,十进制最多3位小数,十六进制值无效;";
                                }

                                String[] standardArray = upLimit.split(MesExtConstWords.DECIMAL_POINT);
                                if (null != standardArray && standardArray.length == 2 && standardArray[1].length() > 3) {
                                    errorNum++;
                                    cellNum += "K;";
                                    errorInfo += "第K列数据无效,最多3位小数;";
                                }
                            }else{
                                num++;
                            }

                            if(!StringUtils.isEmpty(downLimit)){

                                try {
                                    downLimitCheck =  baseConvertToDecimalism(downLimit, baseType);
                                } catch (Exception e) {
                                    errorNum++;
                                    cellNum += "J;";
                                    errorInfo += "第J列数据无效,十进制最多3位小数,十六进制值无效;";
                                }

                                String[] standardArray = downLimit.split(MesExtConstWords.DECIMAL_POINT);
                                if (null != standardArray && standardArray.length == 2 && standardArray[1].length() > 3) {
                                    errorNum++;
                                    cellNum += "J;";
                                    errorInfo += "第J列数据无效,最多3位小数;";
                                }
                            }else{
                                num++;
                            }

                            if(num == 2){
                                errorNum++;
                                cellNum += "J+K;";
                                errorInfo += "第J+K列数据无效,需至少其中一个有值;";
                            }

                            String computeType;
                            if( downLimitCheck != null && upLimitCheck != null && standardValueCheck != null){
                                computeType = ONE;
                            }else if(downLimitCheck != null && standardValueCheck != null){
                                computeType = TWO;
                            }else if(upLimitCheck != null && standardValueCheck != null){
                                computeType = THREE;
                            }else if(downLimitCheck != null && upLimitCheck != null){
                                computeType = FOUR;
                            }else{
                                computeType = FIVE;
                            }

                            switch (computeType){
                                case ONE:
                                    if(downLimitCheck > standardValueCheck || standardValueCheck > upLimitCheck || downLimitCheck > upLimitCheck){
                                        errorNum++;
                                        cellNum += "I;";
                                        errorInfo += "比值范围输入不合理;";
                                    }
                                    break;
                                case TWO:
                                    if(standardValueCheck < downLimitCheck){
                                        errorNum++;
                                        cellNum += "I;";
                                        errorInfo += "标准值大于上限值;";
                                    }
                                    break;
                                case THREE:
                                    if(standardValueCheck > upLimitCheck){
                                        errorNum++;
                                        cellNum += "I;";
                                        errorInfo += "标准值大于上限值;";
                                    }
                                    break;
                                case FOUR:
                                    if(downLimitCheck > upLimitCheck){
                                        errorNum++;
                                        cellNum += "K;";
                                        errorInfo += "上限值小于下限值;";
                                    }
                            }
                        }catch (Exception e){
                            errorNum++;
                            cellNum += "I+J+K;";
                            errorInfo += "不符合结果类型对应的请求参数类型;";
                        }
                    }else if(valueType == MesExtEnumUtil.CHECK_JUDGE_TYPE.EQUIVALENCE_TYPE.getValue() && StringUtils.isEmpty(standardValue)){
                        errorNum++;
                        cellNum += "I;";
                        errorInfo += "标准值不能为空;";
                    }
                }

                //oqcType&partNo&categoryCode3&seq&oqcProject
                if (StringUtils.isEmpty(errorInfo)) {
                    String key = oqcType + "&" + partNo + "&" + categoryCode3 + "&" + seqD + "&" + oqcProject;
                    if (!existMap.containsKey(key)) {
                        existMap.put(key, String.valueOf(rowNum));
                        //校验是否已经存在数据库
                        if (StringUtils.isEmpty(errorInfo)) {
                            if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == Integer.parseInt(oqcType)) {
                                if (!CollectionUtils.isEmpty(oqcProjectMapByPart) && oqcProjectMapByPart.containsKey(oqcType + "&" + partNo + "&" + seqD + "&" + oqcProject)) {
                                    errorNum ++;
                                    cellNum += "ABDE;";
                                    errorInfo += "第A+B+D+E列数据已经存在数据库;";
                                }
                            } else {
                                if (!CollectionUtils.isEmpty(oqcProjectMapByCate) && oqcProjectMapByCate.containsKey(oqcType + "&" + categoryCode3 + "&" + seqD + "&" + oqcProject)) {
                                    errorNum ++;
                                    cellNum += "ACDE;";
                                    errorInfo += "第A+C+D+E列数据已经存在数据库;";
                                }
                            }
                        }
                    } else {
                        errorNum ++;
                        cellNum += "ABCDE;";
                        errorInfo += "第A+B+C+D+E列数据跟第" + existMap.get(key) +
                                "行的第A+B+C+D+E列数据重复;";
                    }
                }

                //没有错误的时候，封装MesBuOqcProject
                if (errorNum == 0) {
                    MesOqcRuleNoteDetail item = new MesOqcRuleNoteDetail();
                    item.setOqcNoType(Integer.parseInt(oqcType));
                    if (MesExtEnumUtil.OQC_CHECK_TYPE.DAILY_INSPECTION.getValue() == item.getOqcNoType()) {
                        item.setPartNo(partNo);
                        item.setCategoryCode3(categoryCode3);
                    } else {
                        item.setCategoryCode3(categoryCode3);
                    }
                    item.setCheckItem(oqcProject);
                    item.setBaseType(baseType);
                    item.setStandard(standard);
                    item.setUpLimit(upLimit);
                    item.setDownLimit(downLimit);
                    item.setCheckTool(appliance);
                    item.setSeq(seqD);
                    item.setCheckType(valueType);
                    item.setStandardValue(standardValue);
                    item.setModifyRemark(modifyRemark);
                    item.setOrganizeCode(organizeCode);
                    ConvertBean.serviceModelInitialize(item, userName);

                    oqcProjectList.add(item);

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

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

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

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

    /**
     * 出货检验项目导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelOqcProject(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesOqcRuleNoteDetail> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesOqcRuleNoteDetail oqcProject : excelList) {
                   oqcProjectRepository.insert(oqcProject);
                    MesOqcRuleNoteDetailTravel oqcRuleNoteDetailTravel = new MesOqcRuleNoteDetailTravel();
                    BeanUtils.copyProperties( oqcProject, oqcRuleNoteDetailTravel, MesExtConstWords.ID);
                    oqcRuleNoteDetailTravelRepository.insert(oqcRuleNoteDetailTravel);
                }
            }
        }
    }

    private Double baseConvertToDecimalism(String value, int baseOfValue) {
        return Double.valueOf(Integer.parseInt(value, MesExtEnumUtil.OQC_BASE_TYPE.baseOfValue(baseOfValue)));
    }
}
