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

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.MesModuleFileImportLot;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartDivulgeCheckCfg;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
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.MesModuleFileImportLotRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartDivulgeCheckCfgRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
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.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.repository.MesPartProduceTypeRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yumingxing
 * @version 1.0
 * @date 2021/4/13 13:09
 **/
@Service
public class PartDivulgeCheckCfgExcelService implements IExcelImportExtService {


    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private MesPartDivulgeCheckCfgRepository partDivulgeCheckCfgRepository;

    @Autowired
    private MesModuleFileImportLotRepository moduleFileImportLotRepository;

    @Autowired
    private CommonExtService commonExtService;


    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        ExcelImportResultExtModel excelImportResultModel = this.sheetExtractMesPart(workbook.getSheetAt(0), organizeCode, userName);
        this.insertExcelPartDivulegeCheckCfg(excelImportResultModel);
        return excelImportResultModel;
    }

    private ExcelImportResultExtModel sheetExtractMesPart(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesPartExt集合
        List<MesPartDivulgeCheckCfg> partDivulgeCheckCfgExtList = new ArrayList<>();

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

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

        //用于EXCEL表中的物料代码唯一校验，key：partNo，value：row
        Map<String, String> existMap = new HashMap<>();

        List<MesPartDivulgeCheckCfg> partDivulgeCheckCfgs = partDivulgeCheckCfgRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()});

        Map<String, List<MesPartDivulgeCheckCfg>> mesPartDivulgeCheckCfgMap = CollectionUtils.isEmpty(partDivulgeCheckCfgs) ? null :
                partDivulgeCheckCfgs.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartDivulgeCheckCfg::getPartNo));


        List<MesPartExt> partList = partExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        Map<String, List<MesPartExt>> partNoMap = CollectionUtils.isEmpty(partList) ? null :
                partList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartExt::getPartNo));

        Map<String, List<MesPartExt>> partNameMap = CollectionUtils.isEmpty(partList) ? null :
                partList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartExt::getPartName));

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

                //物料名称
                String partName = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    partName = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception var80) {
                }

                boolean isExist = false;
                //校验物料代码不重复
                if (!existMap.containsKey(partNo)) {

                    if(!partNoMap.containsKey(partNo)){
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据" + existMap.get(partNo) + "不存在于当前物料配置中";
                    }else{
                        existMap.put(partNo, String.valueOf(rowNum));
                        //校验 物料代码 是否已经存在数据库
                        if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(mesPartDivulgeCheckCfgMap) && mesPartDivulgeCheckCfgMap.containsKey(partNo)) {
                            isExist = true;
                        }
                    }

                } else {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据跟第" + existMap.get(partNo) + "行的第A列数据重复;";
                }

                if (StringUtils.isEmpty(partName)) {
                    ++errorNum;
                    cellNum = cellNum + "B;";
                    errorInfo = errorInfo + "第B列数据必填;";
                }else{
                    if(!CollectionUtils.isEmpty(partNameMap) && partNameMap.containsKey(partName) && partNoMap.containsKey(partNo)){
                        if(!partName.equals(partNoMap.get(partNo).get(0).getPartName())){
                            ++errorNum;
                            cellNum = cellNum + "B;";
                            errorInfo = errorInfo + "第B列数据物料号与物料名称在物料配置中不匹配;";
                        }
                    }else {
                        ++errorNum;
                        cellNum = cellNum + "B;";
                        errorInfo = errorInfo + "第B列数据物料号与物料名称在物料配置中不存在;";
                    }
                }

                if (errorNum == 0) {
                    MesPartDivulgeCheckCfg partDivulgeCheckCfg;
                    if (isExist) {
                        partDivulgeCheckCfg = (MesPartDivulgeCheckCfg) ((List) partNoMap.get(partNo)).get(0);
                        ConvertBean.serviceModelUpdate(partDivulgeCheckCfg, userName);
                    } else {
                        partDivulgeCheckCfg = new MesPartDivulgeCheckCfg();
                        ConvertBean.serviceModelInitialize(partDivulgeCheckCfg, userName);
                    }

                    partDivulgeCheckCfg.setPartNo(partNo);
                    partDivulgeCheckCfg.setPartName(partName);
                    partDivulgeCheckCfg.setSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    partDivulgeCheckCfg.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    partDivulgeCheckCfgExtList.add(partDivulgeCheckCfg);
                    successRowNum = successRowNum + 1;
                } 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 : partDivulgeCheckCfgExtList);
        return excelImportResultModel;
    }

    private void insertExcelPartDivulegeCheckCfg(ExcelImportResultExtModel excelImportResultExtModel) {
        if (null != excelImportResultExtModel) {
            List<MesPartDivulgeCheckCfg> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesPartDivulgeCheckCfg partDivulgeCheckCfg : excelList) {
                    if(StringUtils.isEmpty(partDivulgeCheckCfg.getId())){
                        partDivulgeCheckCfgRepository.insert(partDivulgeCheckCfg);
                    }else{
                        partDivulgeCheckCfgRepository.save(partDivulgeCheckCfg);
                    }
                }
            }
        }
    }

    /**
     * 获取EXCEL的行数据
     * @param sheetAt
     * @param i
     * @return
     */
    private Row getExcelRow(Sheet sheetAt, int i) {
        if (i == 0) {
            return null;
        }
        Row row = sheetAt.getRow(sheetAt.getFirstRowNum() + (i - 1));
        if (null == row) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("EXCEL表中第%s行为空", i)
                    .build();
        }
        return row;
    }

    /**
     * 获取当前行每列的数据
     * @param row
     * @param cell
     * @param cellLetter
     * @param cell
     * @param fieldName
     * @param checkNullFlag
     * @return
     */
    private String getCellData(Row row, int cell, String cellLetter, String fieldName, int rowNum, boolean checkNullFlag, String methodStr, Object... obj) {
        String data = null;
        try {
            row.getCell(cell).setCellType(CellType.STRING);
            data = row.getCell(cell, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
        } catch (Exception e) {
        }

        checkDataNull(checkNullFlag, data, rowNum, cellLetter, fieldName);

        if (!StringUtils.isEmpty(methodStr)) {
            Method method;
            try {
                method = this.getClass().getDeclaredMethod(methodStr, String.class, int.class, String.class, String.class, Object[].class);
                method.setAccessible(true);
                Object result = method.invoke(this, data, rowNum, cellLetter, fieldName, obj);
                data = !StringUtils.isEmpty(result) ? result.toString() : data;
            } catch (Exception e) {
                InvocationTargetException targetEx = (InvocationTargetException) e;
                Throwable trowEx = targetEx.getTargetException();
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail(trowEx.getMessage())
                        .build();
            }
        }
        return data;
    }

    /**
     * 数据判空
     * @param checkNullFlag
     * @param data
     * @param rowNum
     * @param cellLetter
     * @param fieldName
     */
    private void checkDataNull(boolean checkNullFlag, String data, int rowNum, String cellLetter, String fieldName) {
        if (checkNullFlag && StringUtils.isEmpty(data)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("EXCEL表中第%s行%s列%s为空", rowNum, cellLetter, fieldName)
                    .build();
        }
    }

    /**
     * 批次号
     * @param data
     * @param rowNum
     * @param cellLetter
     * @param fieldName
     * @param obj -> organizeCode
     * @return
     */
    private String checkLotNoMethod(String data, int rowNum, String cellLetter, String fieldName, Object... obj){
        if (!StringUtils.isEmpty(data)) {
            if (data.length() > 20) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("EXCEL表中第%s行%s列%长度超过20个字符", rowNum, cellLetter, fieldName)
                        .build();
            }
            MesModuleFileImportLot lot = moduleFileImportLotRepository.getByProperty(
                    new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.LOT_NO, MesExtConstWords.MODULE},
                    new Object[]{obj[0].toString(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), data, MesExtEnumUtil.BATCH_FILE_IMPORT_MODULE.PART.getValue()});
            if (null != lot) {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("EXCEL表中第%s行%s列%s已存在数据库", rowNum, cellLetter, fieldName)
                        .build();
            }
        }
        return data;
    }

}
