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.MesEsopCenterRemainCfg;
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.MesEsopCenterRemainCfgRepository;
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.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCenter;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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 SxEsopCenterRemainCfgExcelService implements IExcelImportExtService {

    @Autowired
    private MesEsopCenterRemainCfgRepository esopCenterRemainCfgRepository;

    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    @Autowired
    private CommonExtService commonExtService;

    /**
     * 作业指导书生产线切替数量配置导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesEsopCenterRemainCfg(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesEsopCenterRemainCfg(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     * 作业指导书生产线切替数量配置导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesEsopCenterRemainCfg(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesEsopCenterRemainCfg集合
        List<MesEsopCenterRemainCfg> esopCenterRemainCfgList = new ArrayList<>();

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

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

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

        List<MesWorkCenter> workCenterList = workCenterRepository.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<MesWorkCenter>> workCenterCodeMap = CollectionUtils.isEmpty(workCenterList) ? null :
                workCenterList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkCenter::getWorkCenterCode));

        List<MesEsopCenterRemainCfg> esopCenterRemainCfgDbList = esopCenterRemainCfgRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED}, new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesEsopCenterRemainCfg>> esopCenterRemainCfgDbMap = CollectionUtils.isEmpty(esopCenterRemainCfgDbList) ? null :
                esopCenterRemainCfgDbList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesEsopCenterRemainCfg::getWorkCenterCode));

        //从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 workCenterName = null;

                //剩余切替数量
                String remainQty = null;
                try {
                    remainQty = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                //校验生产线代码
                if (CollectionUtils.isEmpty(workCenterCodeMap) ||
                        (!CollectionUtils.isEmpty(workCenterCodeMap) && !workCenterCodeMap.containsKey(workCenterCode))) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                } else {
                    workCenterName = workCenterCodeMap.get(workCenterCode).get(0).getWorkCenterName();
                }

                //验证上限值
                if (StringUtils.isEmpty(remainQty)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    try {
                        if (Integer.valueOf(remainQty).compareTo(0) < 0) {
                            errorNum++;
                            cellNum += "C;";
                            errorInfo += "第C列数据无效,必须是0或正整数;";
                        }
                    } catch (NumberFormatException e) {
                        errorNum++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效,必须是0或正整数;";
                    }
                }

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

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

                    esopCenterRemainCfg.setWorkCenterCode(workCenterCode);
                    esopCenterRemainCfg.setWorkCenterName(workCenterName);
                    esopCenterRemainCfg.setRemainQty(new Double(remainQty));
                    esopCenterRemainCfg.setOrganizeCode(organizeCode);
                    esopCenterRemainCfg.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());

                    esopCenterRemainCfgList.add(esopCenterRemainCfg);

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

    /**
     * 作业指导书生产线切替数量配置导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesEsopCenterRemainCfg(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesEsopCenterRemainCfg> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesEsopCenterRemainCfg esopCenterRemainCfg : excelList) {
                    if (StringUtils.isEmpty(esopCenterRemainCfg.getId())) {
                        esopCenterRemainCfgRepository.insert(esopCenterRemainCfg);
                    } else {
                        esopCenterRemainCfgRepository.save(esopCenterRemainCfg);
                    }
                }
            }
        }
    }
}
