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.apiservice.serviceimpl.base.ShiftProdCenterService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftProd;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesShiftProdCenter;
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.model.ShiftProdCenterModel;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftProdCenterRepository;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesShiftProdRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.mes.apiservice.util.MesCommonUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCenterRepository;
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.text.ParseException;
import java.text.SimpleDateFormat;
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 ShiftProdCenterExcelService implements IExcelImportExtService {

    @Autowired
    private MesShiftProdCenterRepository shiftProdCenterRepository;

    @Autowired
    private MesShiftProdRepository shiftProdRepository;

    @Autowired
    private MesShiftExtRepository shiftExtRepository;

    @Autowired
    private MesWorkCenterRepository workCenterRepository;

    @Autowired
    private CommonExtService commonExtService;

    @Autowired
    private ShiftProdCenterService shiftProdCenterService;

    /**
     *产线班次固定作业内容导入
     * @param workbook
     * @param organizeCode
     * @param userName
     * @return
     */
    @Override
    public ExcelImportResultExtModel insertDataByExcel(Workbook workbook, String organizeCode, String userName) {
        //读取表格
        ExcelImportResultExtModel excelImportResultExtModel = this.sheetExtractMesShiftProdCenter(workbook.getSheetAt(0), organizeCode, userName);
        //数据入库
        this.insertExcelMesShiftProdCenter(excelImportResultExtModel);
        return excelImportResultExtModel;
    }

    /**
     *产线班次固定作业内容导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @param userName
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesShiftProdCenter(Sheet sheetAt, String organizeCode, String userName) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesShiftProdCenter集合
        List<MesShiftProdCenter> shiftProdCenterList = new ArrayList<>();

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

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

        SimpleDateFormat sdf = new SimpleDateFormat(MesExtConstWords.TIME_TRUNCATE_SECOND_FORMAT);

        //查询生产线表
        Map<String, Object> workCenterCodeEntityMap;
        try {
            workCenterCodeEntityMap = MesCommonUtil.getCodeEntityMap(workCenterRepository, MesExtConstWords.WORK_CENTER_CODE, organizeCode, "生产线表");
        } catch (Exception e) {
            workCenterCodeEntityMap = null;
        }

        List<MesShiftExt> shiftList = shiftExtRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesShiftExt>> shiftMap = CollectionUtils.isEmpty(shiftList) ? null :
                shiftList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> o.getWorkCenterCode() + "&" + o.getShiftCode()));

        List<MesShiftProd> shiftProdList = shiftProdRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        List<String> prodList = CollectionUtils.isEmpty(shiftProdList) ? null :
                shiftProdList.stream().filter(o -> (null != o &&
                        (MesExtEnumUtil.SHIFT_PROD_TYPE.NORMAL_PROD.getValue() == o.getProdType() || MesExtEnumUtil.SHIFT_PROD_TYPE.UNNORMAL_PROD.getValue() == o.getProdType())))
                        .map(MesShiftProd::getProdCode).collect(Collectors.toList());
        List<String> stopCenterList = CollectionUtils.isEmpty(shiftProdList) ? null :
                shiftProdList.stream().filter(o -> (null != o &&
                        (MesExtEnumUtil.SHIFT_PROD_TYPE.NORMAL_STOP_CENTER.getValue() == o.getProdType() || MesExtEnumUtil.SHIFT_PROD_TYPE.UNNORMAL_STOP_CENTER.getValue() == o.getProdType())))
                        .map(MesShiftProd::getProdCode).collect(Collectors.toList());

        List<String> prodCodeList = null;
        if (!CollectionUtils.isEmpty(prodList) || !CollectionUtils.isEmpty(stopCenterList)) {
            prodCodeList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(prodList)) {
                prodCodeList.addAll(prodList);
            }
            if (!CollectionUtils.isEmpty(stopCenterList)) {
                prodCodeList.addAll(stopCenterList);
            }
        }

        //查询班次作业项目表
        List<MesShiftProdCenter> shiftProdCenters = shiftProdCenterRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
        Map<String, List<MesShiftProdCenter>> stopCenterListMap = CollectionUtils.isEmpty(shiftProdCenters) ? null :
                shiftProdCenters.stream().filter(o -> (null != o && stopCenterList.contains(o.getProdCode())))
                        .collect(Collectors.groupingBy(o -> o.getWorkCenterCode() + "&" + o.getShiftCode() + "&1"));
        Map<String, List<MesShiftProdCenter>> prodListMap = CollectionUtils.isEmpty(shiftProdCenters) ? null :
                shiftProdCenters.stream().filter(o -> (null != o && prodList.contains(o.getProdCode())))
                        .collect(Collectors.groupingBy(o -> o.getWorkCenterCode() + "&" + o.getShiftCode() + "&2"));

        //从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 workCenterCode = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                //班次代码
                String shiftCode = null;
                try {
                    row.getCell(1).setCellType(CellType.STRING);
                    shiftCode = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                String shiftName = null;
                //作业内容代码
                String prodCode = null;
                try {
                    row.getCell(2).setCellType(CellType.STRING);
                    prodCode = row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //开始时间
                String startTime = null;
                try {
                    row.getCell(3).setCellType(CellType.STRING);
                    startTime = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }
                //结束时间
                String endTime = null;
                try {
                    row.getCell(4).setCellType(CellType.STRING);
                    endTime = row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
                } catch (Exception e) {
                }

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

                MesShiftExt shiftExt = null;
                if (StringUtils.isEmpty(shiftCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                } else {
                    if (StringUtils.isEmpty(errorInfo)) {
                        if (CollectionUtils.isEmpty(shiftMap) || (!shiftMap.containsKey(workCenterCode + "&" + shiftCode))) {
                            errorNum ++;
                            cellNum += "A+B;";
                            errorInfo += "第A+B列数据无效;";
                        } else {
                            shiftExt = shiftMap.get(workCenterCode + "&" + shiftCode).get(0);
                            shiftName = shiftExt.getShiftName();
                        }
                    }
                }

                if (StringUtils.isEmpty(prodCode)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    if (CollectionUtils.isEmpty(prodCodeList) || !prodCodeList.contains(prodCode)) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据无效;";
                    }
                }

                if (StringUtils.isEmpty(startTime)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                } else {
                    try {
                        sdf.parse(startTime);
                        if ((startTime.split(":")).length != 2) {
                            errorNum ++;
                            cellNum += "D;";
                            errorInfo += "第D列[HH:mm]数据格式错误;";
                        } else {
                            startTime = new StringBuilder().append(startTime).append(MesExtConstWords.APPEND_SECONDS).toString();
                        }
                    } catch (ParseException e) {
                        errorNum ++;
                        cellNum += "D;";
                        errorInfo += "第D列[HH:mm]数据格式错误;";
                    }
                }

                if (StringUtils.isEmpty(endTime)) {
                    errorNum ++;
                    cellNum += "E;";
                    errorInfo += "第E列数据必填;";
                } else {
                    try {
                        sdf.parse(endTime);
                        if ((endTime.split(":")).length != 2) {
                            errorNum ++;
                            cellNum += "E;";
                            errorInfo += "第E列[HH:mm]数据格式错误;";
                        } else {
                            endTime = new StringBuilder().append(endTime).append(MesExtConstWords.APPEND_SECONDS).toString();
                        }
                    } catch (ParseException e) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据格式错误;";
                    }
                }

                ShiftProdCenterModel shiftProdCenterModel = new ShiftProdCenterModel();
                shiftProdCenterModel.setStartTime(startTime);
                shiftProdCenterModel.setEndTime(endTime);
                if (StringUtils.isEmpty(errorInfo)) {
                    if (!StringUtils.isEmpty(shiftProdCenterService.checkTimeIsInShiftTimeComm(shiftProdCenterModel, shiftExt))) {
                        errorNum ++;
                        cellNum += "D+E;";
                        errorInfo += "第D+E列时间[" + startTime  + " - " + endTime + "]不在班次时间[" + shiftExt.getStartTime()  + " - " + shiftExt.getEndTime() + "]范围内;";
                    }
                }

                if (errorNum == 0) {
                    MesShiftProdCenter shiftProdCenter = new MesShiftProdCenter();
                    ConvertBean.serviceModelInitialize(shiftProdCenter, userName);
                    shiftProdCenter.setProdCode(prodCode);
                    shiftProdCenter.setWorkCenterCode(workCenterCode);
                    shiftProdCenter.setShiftCode(shiftCode);
                    shiftProdCenter.setShiftName(shiftName);
                    shiftProdCenter.setProdCode(prodCode);
                    shiftProdCenter.setStartTime(startTime);
                    shiftProdCenter.setEndTime(endTime);
                    shiftProdCenter.setOrganizeCode(organizeCode);

                    String key = workCenterCode + "&" + shiftCode + "&";
                    List<MesShiftProdCenter> itemList;
                    if (stopCenterList.contains(prodCode)) {
                        key += 1;
                        itemList = CollectionUtils.isEmpty(stopCenterListMap) ? null : stopCenterListMap.get(key);
                    } else {
                        key += 2;
                        itemList = CollectionUtils.isEmpty(prodListMap) ? null : prodListMap.get(key);
                    }

                    if (StringUtils.isEmpty(shiftProdCenterService.checkTimeIsOverlapMethod(itemList ,shiftProdCenterModel, shiftExt))) {
                        if (CollectionUtils.isEmpty(itemList)) {
                            itemList = new ArrayList<>();
                        }
                        itemList.add(shiftProdCenter);

                        if (stopCenterList.contains(prodCode)) {
                            if (CollectionUtils.isEmpty(stopCenterListMap)) {
                                stopCenterListMap = new HashMap<>();
                            }
                            stopCenterListMap.put(key, itemList);
                        } else {
                            if (CollectionUtils.isEmpty(prodListMap)) {
                                prodListMap = new HashMap<>();
                            }
                            prodListMap.put(key, itemList);
                        }

                        shiftProdCenterList.add(shiftProdCenter);
                    } else {
                        errorNum ++;
                        cellNum += "D+E;";
                        errorInfo += "第D+E列时间[" + shiftProdCenterModel.getStartTime()  + " - " + shiftProdCenterModel.getEndTime() + "]与数据库中或此行以上的数据存在时间重叠;";
                    }
                }

                //没有错误的时候，封装MesShiftProdCenter
                if (errorNum == 0) {
                    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 : shiftProdCenterList);
        return excelImportResultModel;
    }

    /**
     *产线班次固定作业内容扩展导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesShiftProdCenter(ExcelImportResultExtModel excelImportResultExtModel) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesShiftProdCenter> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesShiftProdCenter shiftProdCenter : excelList) {
                    shiftProdCenterRepository.insert(shiftProdCenter);
                }
            }
        }
    }
}
