package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.station.function;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesProdShiftRecordService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesShiftService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionCustomContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProductionPartSheetModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseSwsService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.function.IFsmModuleFunctionService;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesProductionRecord;
import cn.estsh.i3plus.pojo.mes.model.ButtonDynamicModel;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.repository.MesProductionRecordRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import com.alibaba.fastjson.JSONObject;
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.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 工位参数按钮事件接口实现【加工零件统计Sheet页】
 **/
@Service
public class MesFunctionProductionPartSheetService extends BaseSwsService implements IFsmModuleFunctionService {

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesShiftService shiftService;

    @Autowired
    private IMesProdShiftRecordService prodShiftRecordService;

    @Autowired
    private MesProductionRecordRepository productionRecordRepository;

    @Override
    public Object doCustomApiDispatch(StationRequestBean reqBean, StationResultBean resultBean, ButtonDynamicModel buttonDynamicModel) {

        //页面渲染数据集
        Map<String, Object> resultMap = new HashMap<>();

        //验证参数
        Map<String, String> paramMap = null;
        try {
            paramMap = StringUtils.isEmpty(buttonDynamicModel.getFunctionValue()) ? null : JSONObject.parseObject(buttonDynamicModel.getFunctionValue(), Map.class);
        } catch (Exception e) {
        }

        //返回客户端作为查询条件
        Map<Integer, String> reportStatusMap = new HashMap<>();
        reportStatusMap.put(REPORT_STATUS.REPORT.getValue(), REPORT_STATUS.REPORT.getDescription());
        reportStatusMap.put(REPORT_STATUS.UN_REPORT.getValue(), REPORT_STATUS.UN_REPORT.getDescription());
        resultMap.put(MesPcnExtConstWords.REPORT_STATUS, reportStatusMap);

        String startTime = !CollectionUtils.isEmpty(paramMap) && !StringUtils.isEmpty(paramMap.get(MesPcnExtConstWords.START_TIME)) ? paramMap.get(MesPcnExtConstWords.START_TIME) : null;
        String endTime = !CollectionUtils.isEmpty(paramMap) && !StringUtils.isEmpty(paramMap.get(MesPcnExtConstWords.END_TIME)) ? paramMap.get(MesPcnExtConstWords.END_TIME) : null;
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            //根据当前时间计算当前班次的时间
            Map<String, String> shiftTimeMap = shiftService.calcCurShiftTimeMapByCurTime(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());
            if (!CollectionUtils.isEmpty(shiftTimeMap)) {
                startTime = shiftTimeMap.get(MesPcnExtConstWords.START_TIME);
                endTime = shiftTimeMap.get(MesPcnExtConstWords.END_TIME);
            } else {
                String today = TimeTool.getToday();
                startTime = today + MesPcnExtConstWords.DATE_FORMAT_APPEND_0;
                endTime = shiftService.calcDay(today, 1) + MesPcnExtConstWords.DATE_FORMAT_APPEND_0;
            }
            //返回客户端作为默认条件
            resultMap.put(MesPcnExtConstWords.START_TIME, startTime);
            resultMap.put(MesPcnExtConstWords.END_TIME, endTime);

            //客户端默认开窗时不查询数据
            return resultMap;
        }

        Boolean checkTime;
        try {
            checkTime = TimeTool.getSecoundsBetweenTime(1, startTime, endTime) <= 86400;
        } catch (ParseException e) {
            checkTime = false;
        }

        if (!checkTime) return packResultMap(resultMap, "时间查询条件限制一天!");

        String partNo = !CollectionUtils.isEmpty(paramMap) && !StringUtils.isEmpty(paramMap.get(MesPcnExtConstWords.PART_NO)) ? paramMap.get(MesPcnExtConstWords.PART_NO) : null;

        //查询加工记录数据
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        DdlPreparedPack.timeBuilder(startTime, endTime, MesPcnExtConstWords.COMPLETE_DATE_TIME, packBean, false);
        DdlPreparedPack.getStringEqualPack(reqBean.getWorkCenterCode(), MesPcnExtConstWords.WORK_CENTER_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(reqBean.getWorkCellCode(), MesPcnExtConstWords.WORK_CELL_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(partNo, MesPcnExtConstWords.PART_NO, packBean);
        List<MesProductionRecord> productionRecordList = productionRecordRepository.findByHqlWhere(packBean);
        if (CollectionUtils.isEmpty(productionRecordList)) return resultMap;

        Integer reportStatus = !CollectionUtils.isEmpty(paramMap) && !StringUtils.isEmpty(paramMap.get(MesPcnExtConstWords.REPORT_STATUS)) ? Integer.valueOf(paramMap.get(MesPcnExtConstWords.REPORT_STATUS)) : null;

        //搜集需要汇报的加工记录
        List<MesProductionRecord> productionRecordList2Report = (StringUtils.isEmpty(reportStatus) || reportStatus.compareTo(REPORT_STATUS.REPORT.getValue()) == 0)
                ? productionRecordList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo()) && o.getReportStatus().compareTo(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue()) != 0)).collect(Collectors.toList()) : null;

        //搜集无需汇报的加工记录
        List<MesProductionRecord> productionRecordList2NoReport = (StringUtils.isEmpty(reportStatus) || reportStatus.compareTo(REPORT_STATUS.UN_REPORT.getValue()) == 0)
                ? productionRecordList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo()) && o.getReportStatus().compareTo(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue()) == 0)).collect(Collectors.toList()) : null;

        List<MesProductionPartSheetModel> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productionRecordList2Report)) backResultList(resultList, productionRecordList2Report, REPORT_STATUS.REPORT);
        if (!CollectionUtils.isEmpty(productionRecordList2NoReport)) backResultList(resultList, productionRecordList2NoReport, REPORT_STATUS.UN_REPORT);

        if (!CollectionUtils.isEmpty(resultList)) {
            resultList = resultList.stream().filter(o -> null != o).sorted(Comparator.comparing(MesProductionPartSheetModel::getPartNo).thenComparing(MesProductionPartSheetModel::getReportSatus)).collect(Collectors.toList());
            resultMap.put(MesPcnExtConstWords.DATA, resultList);
        }

        return resultMap;

    }

    private void backResultList(List<MesProductionPartSheetModel> resultList, List<MesProductionRecord> productionRecordList, REPORT_STATUS reportStatus) {
        Map<String, List<MesProductionRecord>> prMap = productionRecordList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesProductionRecord::getPartNo));
        for (Map.Entry<String, List<MesProductionRecord>> entry : prMap.entrySet()) {
            if (null == entry) continue;
            MesProductionRecord item = entry.getValue().get(0);
            MesProductionPartSheetModel result = new MesProductionPartSheetModel();
            result.setWorkCenterCode(item.getWorkCenterCode());
            result.setWorkCellCode(item.getWorkCellCode());
            result.setPartNo(item.getPartNo());
            result.setPartName(item.getPartName());
            result.setQty(new Double(entry.getValue().size()));
            result.setReportSatus(reportStatus.getValue());
            result.setReportSatusName(reportStatus.getDescription());
            resultList.add(result);
        }
    }

    //返回提示信息
    private Map<String, Object> packResultMap(Map<String, Object> resultMap, String message) {
        resultMap.put(MesPcnExtConstWords.MESSAGE, message);
        return resultMap;
    }

    //业务操作
    enum REPORT_STATUS {

        REPORT(20, "需要汇报"),

        UN_REPORT(30, "无需汇报");

        private int value;

        private String description;

        REPORT_STATUS(int value, String description) {

            this.value = value;

            this.description = description;

        }

        public int getValue() {
            return value;
        }

        public String getDescription() {
            return description;
        }

        public static String valueOfDescription(int val) {
            if (StringUtils.isEmpty(val)) return null;
            String tmp = null;
            for (int i = 0; i < values().length; i++) {
                if (val == values()[i].value) {
                    tmp = values()[i].description;
                }
            }
            return tmp;
        }

    }

}
