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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProdRuleCfgExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesCellEquipContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IPartService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseSwsService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.IShippingDispatchService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.function.IFsmModuleFunctionService;
import cn.estsh.i3plus.mes.pcn.util.StationKvBeanUtil;
import cn.estsh.i3plus.platform.common.util.MesPcnConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.bean.MesProdRuleNosortCfg;
import cn.estsh.i3plus.pojo.mes.model.ButtonDynamicModel;
import cn.estsh.i3plus.pojo.mes.model.StationKvBean;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
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.*;
import java.util.stream.Collectors;

/**
 * @Description : 工位参数按钮事件接口实现【选择产成零件】
 **/
@Service
public class MesFunctionChooseCavityPartService extends BaseSwsService implements IFsmModuleFunctionService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IShippingDispatchService shippingDispatchService;

    @Autowired
    private IMesProdRuleCfgExtService prodRuleCfgExtService;

    @Autowired
    private IPartService partService;

    @Override
    public Boolean doFunction(StationRequestBean reqBean, StationResultBean resultBean, ButtonDynamicModel buttonDynamicModel) {

        //暂定不需要卡控
        /*//获取生产过程上下文对象
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.getProductionProcessContext(reqBean);

        if (!productionProcessContext.getSuccess()) return false;

        MesWorkCell workCell = productionProcessContext.getWorkCell();

        if (StringUtils.isEmpty(workCell.getIsAllowOrder()) || CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == workCell.getIsAllowOrder()) {
            this.sendMessage(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PICK.getValue()).scanInfo(buttonDynamicModel.getFunctionValue()),
            String.format("生产线[%s]工位[%s]%s失败,工位未设置允许界面选产成零件!", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), buttonDynamicModel.getButtonName()), MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return false;
        }*/

        List<StationKvBean> resultList = checkCavityPartIsValid(buttonDynamicModel.getFunctionValue());
        if (CollectionUtils.isEmpty(resultList)) {
            this.sendMessage(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PICK.getValue()).scanInfo(buttonDynamicModel.getFunctionValue()),
                    String.format("生产线[%s]工位[%s]%s失败,请检查选择的产成零件信息[%s]的有效性!", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), buttonDynamicModel.getButtonName(), buttonDynamicModel.getFunctionValue()),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return false;
        }

        //保存手动选择的腔数及零件信息上下文
        productionProcessContextStepService.dispatchFunctionChooseCavityPartContext(reqBean, resultList);

        this.sendMessage(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PICK.getValue()).scanInfo(buttonDynamicModel.getFunctionValue()),
                String.format("生产线[%s]工位[%s]%s成功,请等待验证!提交信息[%s]", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), buttonDynamicModel.getButtonName(), buttonDynamicModel.getFunctionValue()),
                MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

        reqBean.setClientInfo(shippingDispatchService.getActorClientInfo(reqBean));
        reqBean.setInterfaceType(MesPcnConstWords.SHIPPING);
        reqBean.setBusiType(MesPcnEnumUtil.ACTOR_RECEIVE_STRATEGY.WS_CMD_DO_SCAN.getCode());
        reqBean.setForceJumpProcess(true);
        shippingDispatchService.sendScanQueueNextExec(reqBean);

        return true;

    }

    //腔数=零件个数   数据格式:   腔数;零件1;零件2;零件3
    private List<StationKvBean> checkCavityPartIsValid(String functionValue) {

        List<String> list = !StringUtils.isEmpty(functionValue) ? new ArrayList<>(Arrays.asList(functionValue.split(MesPcnExtConstWords.SEMICOLON))) : null;

        if (CollectionUtils.isEmpty(list)) return null;

        List<StationKvBean> resultList = null;

        try {

            Integer cavity = Integer.valueOf(list.get(0));

            if (cavity != list.size() - 1) return null;

            return StationKvBeanUtil.addStationKvBeanList(new ArrayList<>(),
                    new StationKvBean(MesPcnExtConstWords.CAVITY, "腔数", list.remove(0)),
                    new StationKvBean(MesPcnExtConstWords.CELL_MESSAGE_SOURCE, "工位信息来源", MesExtEnumUtil.CELL_MESSAGE_SOURCE.PICK.getValueStr()),
                    new StationKvBean(MesPcnExtConstWords.PART_NO, "零件编码", list.stream().filter(o -> null != o).collect(Collectors.joining(MesPcnExtConstWords.SEMICOLON))));

        } catch (NumberFormatException e) {

            return null;

        }

    }

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

        Map<String, Object> resultMap = new HashMap<>();

        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.getProductionProcessContext(reqBean);
        MesCellEquipContext cellEquipContext = productionProcessContext.getCurCellEquip();

        if (!productionProcessContext.getSuccess()) resultMap.put(MesPcnExtConstWords.CAVITY, MesPcnExtConstWords.ONE);
        else {
            if (null == cellEquipContext) resultMap.put(MesPcnExtConstWords.CAVITY, MesPcnExtConstWords.ONE);
            else resultMap.put(MesPcnExtConstWords.CAVITY, cellEquipContext.getCavity());
        }

        if (null == cellEquipContext) return resultMap;

        List<MesProdRuleNosortCfg> prodRuleNosortCfgList = prodRuleCfgExtService.getProdRuleNosortCfgListByEquipCode(reqBean.getOrganizeCode(), cellEquipContext.getEquipmentCode());
        if (CollectionUtils.isEmpty(prodRuleNosortCfgList)) return resultMap;

        List<String> outPartNoList = prodRuleNosortCfgList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getOutPartNo()))).map(MesProdRuleNosortCfg::getOutPartNo).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(outPartNoList)) return resultMap;

        List<MesPart> partList = partService.getPartList(reqBean.getOrganizeCode(), outPartNoList);
        if (CollectionUtils.isEmpty(partList)) return resultMap;

        partList = partList.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MesPart::getPartNo))), ArrayList::new));

        resultMap.put(MesPcnExtConstWords.OUT_PART_NO, partList.stream().filter(o -> null != o).collect(Collectors.toMap(MesPart::getPartNo, MesPart::getPartName)));

        return resultMap;

    }

}
