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.bu3.ISxOfficialLossDetailRecordService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesOfficialLossDetailRecord;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
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.MesOfficialLossDetailRecordRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartExtRepository;
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.tool.MathOperation;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import lombok.extern.slf4j.Slf4j;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description :仕损明细记录导入
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Slf4j
@Service
public class SxOfficialLossDetailRecordExcelService implements IExcelImportExtService {

    @Autowired
    private MesWorkCenterExtRepository workCenterExtRepository;

    @Autowired
    private MesOfficialLossDetailRecordRepository officialLossDetailRecordRepository;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private ISxOfficialLossDetailRecordService officialLossDetailRecordService;

    @Autowired
    private MesPartExtRepository partExtRepository;

    /**
     * 仕损明细记录导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        log.info("MES二开导入 --- 仕损明细记录 --- 读取表格 START ---");
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesOfficialLossDetailRecord(workbook.getSheetAt(0), organizeCode, userName);
        log.info("MES二开导入 --- 仕损明细记录 --- 数据写入 START ---");
        //数据入库
        this.insertExcelMesOfficialLossDetailRecord(excelImportResultExtModel);
        log.info("MES二开导入 --- 仕损明细记录 --- 数据导入 END ---");
        return excelImportResultExtModel;
    }

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

        //MesOfficialLossDetailRecord集合
        List<MesOfficialLossDetailRecord> officialLossDetailRecordList = new ArrayList<>();

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

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

        log.info("MES二开导入 --- 仕损明细记录 --- 读取生产线 START ---");

        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));

        log.info("MES二开导入 --- 仕损明细记录 --- 读取仕损明细记录类型明细配置 START ---");

        Map<String, Map<String, String>> itemCfgMap = officialLossDetailRecordService.getOfficialLossItemCfgMap(organizeCode);

        log.info("MES二开导入 --- 仕损明细记录 --- 读取物料 START ---");

        List<MesPartExt> partExtList = partExtRepository.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()});

        log.info("MES二开导入 --- 仕损明细记录 --- 读取物料 END ---");

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

        log.info("MES二开导入 --- 仕损明细记录 --- 分组物料 END ---");

        //从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 lossDate;
                try {
                    lossDate = new DataFormatter().formatCellValue(row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                    continue;
                }

                //仕损类型
                String lossType = null;
                String lossTypeStr = null;
                try {
                    lossTypeStr = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //仕损明细
                String lossItem = null;
                try {
                    lossItem = new DataFormatter().formatCellValue(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //物料编码
                String partNo = null;
                try {
                    partNo = new DataFormatter().formatCellValue(row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //物料名称
                String partNameRdd = null;
                Double partPrice = null;

                //报废数量
                String qty = null;
                try {
                    qty = new DataFormatter().formatCellValue(row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                MesWorkCenterExt workCenterExt = (!CollectionUtils.isEmpty(workCenterCodeMap) && workCenterCodeMap.containsKey(workCenterCode)) ? workCenterCodeMap.get(workCenterCode).get(0) : null;
                if (null == workCenterExt) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                } else {
                    if (StringUtils.isEmpty(workCenterExt.getCareerCode()) || StringUtils.isEmpty(workCenterExt.getCategoryCode())) {
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据生产线信息未维护事业别或产品别;";
                    }
                }

                if (StringUtils.isEmpty(lossDate)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (!TimeTool.checkDateFormat(lossDate, MesExtConstWords.DATE_FORMAT_YM)) {
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                if (StringUtils.isEmpty(lossTypeStr)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    lossType = MesExtEnumUtil.SX_OFFICIAL_LOSS_TYPE.descriptionOfValue(lossTypeStr);
                    if (StringUtils.isEmpty(lossType)) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    } else {
                        if (StringUtils.isEmpty(lossItem)) {
                            errorNum ++;
                            cellNum += "D;";
                            errorInfo += "第D列数据必填;";
                        } else {
                            if (CollectionUtils.isEmpty(itemCfgMap) || (!itemCfgMap.containsKey(lossType) || !itemCfgMap.get(lossType).containsKey(lossItem))) {
                                errorNum ++;
                                cellNum += "D;";
                                errorInfo += "第D列数据无效;";
                            }
                        }
                    }
                }

                if (StringUtils.isEmpty(partNo)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(partNoMap) || !partNoMap.containsKey(partNo)) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    } else {
                        partPrice = partNoMap.get(partNo).get(0).getPartPrice();
                        if (StringUtils.isEmpty(partPrice) || MathOperation.compareTo(partPrice, new Double(0)) <= 0) {
                            errorNum ++;
                            cellNum += "E;";
                            errorInfo += "第E列数据无效,未同步部品单价;";
                        } else {
                            partNameRdd = partNoMap.get(partNo).get(0).getPartName();
                        }
                    }
                }

                if (StringUtils.isEmpty(qty)) {
                    errorNum ++;
                    cellNum += "G;";
                    errorInfo += "第G列数据必填;";
                } else {
                    try {
                        if (MathOperation.compareTo(new Double(qty), new Double(0)) < 0) {
                            errorNum++;
                            cellNum += "G;";
                            errorInfo += "第G列数据无效,必须是正数,最多三位小数;";
                        }
                        String[] qtyArr = qty.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != qtyArr && qtyArr.length == 2 && qtyArr[1].length() > 3) {
                            errorNum++;
                            cellNum += "G;";
                            errorInfo += "第G列数据无效,必须是正数,最多三位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "G;";
                        errorInfo += "第G列数据无效,必须是正数,最多三位小数;";
                    }
                }

                //没有错误的时候，封装MesOfficialLossDetailRecord
                if (errorNum == 0) {
                    MesOfficialLossDetailRecord officialLossDetailRecord = new MesOfficialLossDetailRecord();
                    ConvertBean.serviceModelInitialize(officialLossDetailRecord, userName);
                    officialLossDetailRecord.setWorkCenterCode(workCenterCode);
                    officialLossDetailRecord.setCareerCode(workCenterExt.getCareerCode());
                    officialLossDetailRecord.setCategoryCode(workCenterExt.getCategoryCode());
                    officialLossDetailRecord.setLossDate(lossDate);
                    officialLossDetailRecord.setLossType(lossType);
                    officialLossDetailRecord.setLossItem(lossItem);
                    officialLossDetailRecord.setPartNo(partNo);
                    officialLossDetailRecord.setPartNameRdd(partNameRdd);
                    officialLossDetailRecord.setQty(new Double(qty));
                    officialLossDetailRecord.setUnitPrice(partPrice);
                    officialLossDetailRecord.setAmount(MathOperation.mul(officialLossDetailRecord.getQty(), partPrice));
                    officialLossDetailRecord.setOrganizeCode(organizeCode);
                    officialLossDetailRecord.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    officialLossDetailRecordList.add(officialLossDetailRecord);

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

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

        log.info("MES二开导入 --- 仕损明细记录 --- 数据处理 END ---");

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

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

    /**
     * 仕损明细记录导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesOfficialLossDetailRecord(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesOfficialLossDetailRecord> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesOfficialLossDetailRecord officialLossDetailRecord : excelList) {
                    officialLossDetailRecordRepository.insert(officialLossDetailRecord);
                }
            }
        }
    }
}
