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.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartCategoryPlanRate;
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.MesPartCategoryPlanRateRepository;
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.pojo.base.enumutil.CommonEnumUtil;
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.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 SxPartCategoryPlanRateExcelService implements IExcelImportExtService {

    @Autowired
    private MesPartCategoryPlanRateRepository partCategoryPlanRateRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 产品类别计划比例导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesPartCategoryPlanRate(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesPartCategoryPlanRate(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 产品类别计划比例导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesPartCategoryPlanRate(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

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

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

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

        Map<String, String> existMap = new HashMap<>();

        List<MesPartCategoryPlanRate> partCategoryPlanRateDbList = partCategoryPlanRateRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED}, new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesPartCategoryPlanRate>> partCategoryPlanRateDbMap = CollectionUtils.isEmpty(partCategoryPlanRateDbList) ? null :
                partCategoryPlanRateDbList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesPartCategoryPlanRate::getCategoryCode));

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

                //产品类别名称
                String categoryName = null;
                try {
                    categoryName = new DataFormatter().formatCellValue(row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //计划比例
                String planRate = null;
                try {
                    planRate = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //验证产品类别名称
                if (StringUtils.isEmpty(categoryName)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }

                //验证计划比例
                if (StringUtils.isEmpty(planRate)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    try {
                        if (MathOperation.compareTo(new Double(planRate), new Double(0)) < 0) {
                            errorNum++;
                            cellNum += "C;";
                            errorInfo += "第C列数据无效,必须是正数,最多四位小数;";
                        }
                        String[] planRateArr = planRate.split(MesExtConstWords.DECIMAL_POINT);
                        if (null != planRateArr && planRateArr.length == 2 && planRateArr[1].length() > 4) {
                            errorNum++;
                            cellNum += "C;";
                            errorInfo += "第C列数据无效,必须是正数,最多四位小数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效,必须是正数,最多四位小数;";
                    }
                }

                Boolean isExist = false;
                if (StringUtils.isEmpty(errorInfo)) {
                    if (!existMap.containsKey(categoryCode)) {
                        existMap.put(categoryCode, String.valueOf(rowNum));
                        //校验是否已经存在数据库
                        if (!CollectionUtils.isEmpty(partCategoryPlanRateDbMap) && partCategoryPlanRateDbMap.containsKey(categoryCode)) isExist = true;
                    } else {
                        errorNum ++;
                        cellNum += "A;";
                        errorInfo += "第A列数据跟第" + existMap.get(categoryCode) + "行的数据重复;";
                    }
                }

                //没有错误的时候，封装MesPartCategoryPlanRate
                if (errorNum == 0) {
                    MesPartCategoryPlanRate partCategoryPlanRate;
                    if (isExist) {
                        partCategoryPlanRate = partCategoryPlanRateDbMap.get(categoryCode).get(0);
                        partCategoryPlanRate.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
                        ConvertBean.serviceModelUpdate(partCategoryPlanRate, userName);
                    } else {
                        partCategoryPlanRate = new MesPartCategoryPlanRate();
                        ConvertBean.serviceModelInitialize(partCategoryPlanRate, userName);
                    }

                    partCategoryPlanRate.setCategoryCode(categoryCode);
                    partCategoryPlanRate.setCategoryName(categoryName);
                    partCategoryPlanRate.setPlanRate(planRate);
                    partCategoryPlanRate.setOrganizeCode(organizeCode);
                    partCategoryPlanRate.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    partCategoryPlanRateList.add(partCategoryPlanRate);

                    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 insertExcelMesPartCategoryPlanRate(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesPartCategoryPlanRate> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesPartCategoryPlanRate partCategoryPlanRate : excelList) {
                    if (StringUtils.isEmpty(partCategoryPlanRate.getId())) {
                        partCategoryPlanRateRepository.insert(partCategoryPlanRate);
                    } else {
                        partCategoryPlanRateRepository.save(partCategoryPlanRate);
                    }
                }
            }
        }
    }
}
