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

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.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWeigh;
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.MesPartExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWeighRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : 称重导入，支持编辑
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class SxWeighExcelService implements IExcelImportExtService {

    @Autowired
    private MesWeighRepository weighRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 称重导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesWeigh(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesWeigh(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 称重导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesWeigh(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesWeigh集合
        List<MesWeigh> weighList = new ArrayList<>();

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

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

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

        //查询称重表
        List<MesWeigh> weighs = weighRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesWeigh>> weighMap = CollectionUtils.isEmpty(weighs) ? null :
                weighs.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWeigh::getPartNo));

        // 查询物料表
        Map<String, Object> partCodeEntityMap;
        try {
            partCodeEntityMap = MesCommonUtil.getCodeEntityMap(partExtRepository, MesExtConstWords.PART_NO, organizeCode, "物料表");
        } catch (Exception e) {
            partCodeEntityMap = 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 = ""; //错误信息

                //物料编码
                try {
                    //第一列必须有值，否则跳过
                    row.getCell(0).setCellType(CellType.STRING);
                } catch (Exception e) {
                    continue;
                }
                String partNo = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //称重数量
                String weighNum = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    weighNum = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //参考标准重量
                String standardWeight = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    standardWeight = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //偏差上限
                String upLimit = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    upLimit = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //偏差下限
                String downLimit = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    downLimit = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

                //校验物料编码
                if (CollectionUtils.isEmpty(partCodeEntityMap) || StringUtils.isEmpty(partNo) ||
                        (!CollectionUtils.isEmpty(partCodeEntityMap) && !partCodeEntityMap.containsKey(partNo))) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }


                boolean isExist = false;
                //校验物料编码不重复
                if (!partNoMap.containsKey(partNo)) {
                    partNoMap.put(partNo, String.valueOf(rowNum));
                    //校验 物料编码 是否已经存在数据库
                    if (StringUtils.isEmpty(errorInfo) && !CollectionUtils.isEmpty(weighMap) && weighMap.containsKey(partNo)) {
                        isExist = true;
                    }
                } else {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据跟第" + partNoMap.get(partNo) + "行的第A列数据重复;";
                }

                //校验称重数量
                if (StringUtils.isEmpty(weighNum)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    try {
                        if (MathOperation.compareTo(Double.valueOf(weighNum), new Double(0)) < 0) {
                            errorNum++;
                            cellNum += "B;";
                            errorInfo += "第B列数据不能小于0;";
                        }
                        String[] weighNumArr = weighNum.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != weighNumArr && weighNumArr.length == 2 && weighNumArr[1].length() > 2) {
                            errorNum++;
                            cellNum += "B;";
                            errorInfo += "第B列数据无效,最多2位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "B;";
                        errorInfo += "第B列数据无效;";
                    }
                }

                //校验参考标准重量
                if (!StringUtils.isEmpty(standardWeight)) {
                    try {
                        if (MathOperation.compareTo(Double.valueOf(standardWeight), new Double(0)) < 0) {
                            errorNum++;
                            cellNum += "C;";
                            errorInfo += "第C列数据不能小于0;";
                        }
                        String[] standardWeightArr = standardWeight.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != standardWeightArr && standardWeightArr.length == 2 && standardWeightArr[1].length() > 2) {
                            errorNum++;
                            cellNum += "C;";
                            errorInfo += "第C列数据无效,最多2位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }
                //校验偏差上限
                if (!StringUtils.isEmpty(upLimit)) {
                    try {
                        Double.valueOf(upLimit);
                        String[] upLimitArr = upLimit.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != upLimitArr && upLimitArr.length == 2 && upLimitArr[1].length() > 2) {
                            errorNum ++;
                            cellNum += "D;";
                            errorInfo += "第D列数据无效,最多2位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "D;";
                        errorInfo += "第D列数据无效;";
                    }
                }
                //校验偏差下限
                if (!StringUtils.isEmpty(downLimit)) {
                    try {
                        Double.valueOf(downLimit);
                        String[] downLimitArr = downLimit.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != downLimitArr && downLimitArr.length == 2 && downLimitArr[1].length() > 2) {
                            errorNum ++;
                            cellNum += "E;";
                            errorInfo += "第E列数据无效,最多2位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据无效;";
                    }
                }

                //没有错误的时候，封装MesWeigh
                if (errorNum == 0) {
                    MesWeigh weigh;
                    if (isExist) {
                        weigh = weighMap.get(partNo).get(0);
                        ConvertBean.serviceModelUpdate(weigh, userName);
                    } else {
                        weigh = new MesWeigh();
                        ConvertBean.serviceModelInitialize(weigh, userName);
                    }
                    String partName = ((MesPartExt) partCodeEntityMap.get(partNo)).getPartName();
                    weigh.setPartNo(partNo);
                    weigh.setPartName(partName);
                    weigh.setWeighNum(Double.valueOf(weighNum));
                    weigh.setStandardWeight(StringUtil.isEmpty(standardWeight) ? 0.0 : Double.valueOf(standardWeight));
                    weigh.setUpLimit(StringUtil.isEmpty(upLimit) ? 0.0 : Double.valueOf(upLimit));
                    weigh.setDownLimit(StringUtil.isEmpty(downLimit) ? 0.0 : Double.valueOf(downLimit));
                    weigh.setOrganizeCode(organizeCode);

                    weighList.add(weigh);

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

    /**
     * 称重扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesWeigh(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesWeigh> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesWeigh weigh : excelList) {
                    if(StringUtils.isEmpty(weigh.getId())){
                        weighRepository.insert(weigh);
                    }else{
                        weighRepository.save(weigh);
                    }
                }
            }
        }
    }
}
