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

import cn.estsh.i3plus.ext.mes.api.base.IExcelImportExtService;
import cn.estsh.i3plus.ext.mes.api.base.jx.IJxTimeSegmentStatisticsService;
import cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.CommonExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesTimeSegmentStatistics;
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.MesTimeSegmentStatisticsRepository;
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.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 分时段统计方式导入
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-04-23
 * @Modify:
 **/
@Service
public class JxTimeSegmentStatisticsExcelService implements IExcelImportExtService {

    @Autowired
    private MesTimeSegmentStatisticsRepository timeSegmentStatisticsRepository;

    @Autowired
    private IJxTimeSegmentStatisticsService timeSegmentStatisticsService;

    @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.sheetExtractMesShiftExt(workbook.getSheetAt(0), organizeCode);
        //数据入库
        this.insertExcelMesShiftExt(excelImportResultExtModel, userName);
        return excelImportResultExtModel;
    }

    /**
     * 分时段统计方式导入-读取表格
     * @param sheetAt
     * @param organizeCode
     * @return
     */
    private ExcelImportResultExtModel sheetExtractMesShiftExt(Sheet sheetAt, String organizeCode) {
        //从0行开始读取
        int totalNumberOfRows = sheetAt.getLastRowNum() + 1;

        //MesTimeSegmentStatistics集合
        List<MesTimeSegmentStatistics> timeSegmentStatisticsList = new ArrayList<>();
        Map<String, List<MesTimeSegmentStatistics>> dataMap = new HashMap<>();

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

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

        SimpleDateFormat sdf = new SimpleDateFormat(MesExtConstWords.TIME_TRUNCATE_SECOND_FORMAT);

        List<MesTimeSegmentStatistics> timeSegmentStatisticsDbList = timeSegmentStatisticsRepository.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<MesTimeSegmentStatistics>> dataDbMap = CollectionUtils.isEmpty(timeSegmentStatisticsDbList) ? null :
                timeSegmentStatisticsDbList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> new StringJoiner(MesExtConstWords.AND).add(o.getWorkCenterCode()).add(o.getShiftCode()).toString()));

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

        String today = TimeTool.getToday();

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

                String startTime = null;
                try {
                    startTime = new DataFormatter().formatCellValue(row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                String endTime = null;
                try {
                    endTime = new DataFormatter().formatCellValue(row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                String timeLength = null;
                try {
                    timeLength = new DataFormatter().formatCellValue(row.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK));
                } catch (Exception e) {
                }

                if (CollectionUtils.isEmpty(workCenterCodeEntityMap) || !workCenterCodeEntityMap.containsKey(workCenterCode)) {
                    errorNum ++;
                    cellNum += "A;";
                    errorInfo += "第A列数据无效;";
                }
                if (StringUtils.isEmpty(shiftCode)) {
                    errorNum ++;
                    cellNum += "B;";
                    errorInfo += "第B列数据必填;";
                }
                if (StringUtils.isEmpty(startTime)) {
                    errorNum ++;
                    cellNum += "C;";
                    errorInfo += "第C列数据必填;";
                } else {
                    if (!timeSegmentStatisticsService.checkTimeFormat(startTime)) {
                        errorNum ++;
                        cellNum += "C;";
                        errorInfo += "第C列数据格式错误,请检查时间格式[HH:mm];";
                    }
                }
                if (StringUtils.isEmpty(endTime)) {
                    errorNum ++;
                    cellNum += "D;";
                    errorInfo += "第D列数据必填;";
                } else {
                    if (!timeSegmentStatisticsService.checkTimeFormat(endTime)) {
                        errorNum ++;
                        cellNum += "D;";
                        errorInfo += "第D列数据格式错误,请检查时间格式[HH:mm];";
                    }
                }

                if (StringUtils.isEmpty(errorInfo) && !timeSegmentStatisticsService.checkTimeStartBeforeEnd(startTime, endTime)) {
                    errorNum ++;
                    cellNum += "C+D;";
                    errorInfo += "第C+D列数据错误,开始时间必须小于结束时间;";
                }

                if (!StringUtils.isEmpty(timeLength)) {
                    try {
                        Integer.valueOf(timeLength);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }

                if (errorNum == 0) {

                    MesTimeSegmentStatistics timeSegmentStatistics = new MesTimeSegmentStatistics();
                    timeSegmentStatistics.setStartTime(startTime + MesExtConstWords.APPEND_SECONDS);
                    timeSegmentStatistics.setEndTime(endTime + MesExtConstWords.APPEND_SECONDS);
                    timeSegmentStatistics.setTimeLength(timeLength);

                    Boolean boo = timeSegmentStatisticsService.checkTimeLengthIsValid(timeSegmentStatistics, today);
                    if (!boo) {
                        errorNum ++;
                        cellNum += "E;";
                        errorInfo += "第E列数据错误,不能大于开始时间与结束时间的分钟差;";
                    }
                    if (!boo) break;

                    timeSegmentStatistics.setOrganizeCode(organizeCode);
                    timeSegmentStatistics.setWorkCenterCode(workCenterCode);
                    timeSegmentStatistics.setShiftCode(shiftCode);
                    timeSegmentStatistics.setOrderByParam(String.valueOf(rowNum));

                    String key = new StringJoiner(MesExtConstWords.AND).add(workCenterCode).add(shiftCode).toString();
                    MesTimeSegmentStatistics item = timeSegmentStatisticsService.checkTimeCompareToDataList(CollectionUtils.isEmpty(dataDbMap) ? null : dataDbMap.get(key), timeSegmentStatistics);
                    if (null != item) {
                        errorNum ++;
                        cellNum += "A+B+C+D;";
                        errorInfo += String.format("第A+B+C+D列开始时间[%s]结束时间[%s]与已维护的生产线[%s]班次代码[%s]配置的开始时间[%s]结束时间[%s]存在时间重叠;", startTime, endTime, item.getWorkCenterCode(), item.getShiftCode(), item.getStartTime(), item.getEndTime());
                    } else {
                        item = timeSegmentStatisticsService.checkTimeCompareToDataList(CollectionUtils.isEmpty(dataMap) ? null : dataMap.get(key), timeSegmentStatistics);
                        if (null != item) {
                            errorNum ++;
                            cellNum += "A+B+C+D;";
                            errorInfo += String.format("第A+B+C+D列开始时间[%s]结束时间[%s]与EXCEL的第[%s]行生产线[%s]班次代码[%s]开始时间[%s]结束时间[%s]存在时间重叠;", startTime, endTime, item.getOrderByParam(), item.getWorkCenterCode(), item.getShiftCode(), item.getStartTime().substring(0, 5), item.getEndTime().substring(0, 5));
                        }
                    }

                    if (null == item) {
                        List<MesTimeSegmentStatistics> itemList = (!CollectionUtils.isEmpty(dataMap) && dataMap.containsKey(key)) ? dataMap.get(key) : new ArrayList<>();
                        itemList.add(timeSegmentStatistics);
                        dataMap.put(key, timeSegmentStatisticsDbList);

                        timeSegmentStatisticsList.add(timeSegmentStatistics);
                    }

                }

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

    /**
     * 分时段统计方式导入-数据入库
     * @param excelImportResultExtModel
     */
    private void insertExcelMesShiftExt(ExcelImportResultExtModel excelImportResultExtModel, String userName) {
        //导入数据
        if (null != excelImportResultExtModel) {
            List<MesTimeSegmentStatistics> excelList = excelImportResultExtModel.getExcelList();
            if (!CollectionUtils.isEmpty(excelList)) {
                for (MesTimeSegmentStatistics timeSegmentStatistics : excelList) {
                    timeSegmentStatistics.setTimeSegmentCode(timeSegmentStatisticsService.getTimeSegmentCode(timeSegmentStatistics));
                    timeSegmentStatistics.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                    ConvertBean.serviceModelInitialize(timeSegmentStatistics, userName);
                    timeSegmentStatisticsRepository.insert(timeSegmentStatistics);
                }
            }
        }
    }
}
