package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.step;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesEquipVariableCollectContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.IStepService;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrderReductionSource;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderReductionSourceRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import lombok.extern.slf4j.Slf4j;
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.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : 装配件获取匹配工单工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesBarcodeWithWorkOrderRelationFindStepService")
public class MesBarcodeWithWorkOrderRelationFindStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private MesWorkOrderReductionSourceRepository workOrderReductionSourceRepository;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

        //获取上下文扫/读信息:装配件条码
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = productionDispatchContextStepService.getScanAssemblySnContext(reqBean);
        //搜集装配件条码
        List<String> assemblySnList = CollectionUtils.isEmpty(equipVariableCollectContextList) ? null :
                equipVariableCollectContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getEquipVariableValue()))).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.toList());

        //没有待验证的装配件条码
        if (CollectionUtils.isEmpty(assemblySnList)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前没有需要验证的装配件条码!");

        try {
            //查询条码与工单对应关系【在前道工序中作为主条码写入次关系表】
            Map<String, List<MesWorkOrderReductionSource>> workOrderReductionSourceMap = getWorkOrderReductionSourceMap(reqBean.getOrganizeCode(), assemblySnList);
            if (CollectionUtils.isEmpty(workOrderReductionSourceMap))
                return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, String.format("读取的装配件条码%s未获取到匹配工单!", assemblySnList.toString()));

            //用于写入加工单
            equipVariableCollectContextList = new ArrayList<>();
            for (Map.Entry<String, List<MesWorkOrderReductionSource>> entry : workOrderReductionSourceMap.entrySet()) {
                if (null == entry) continue;
                //取最新的数据
                MesWorkOrderReductionSource workOrderReductionSource = entry.getValue().stream()
                        .filter(o -> null != o).sorted(Comparator.comparing(MesWorkOrderReductionSource::getCreateDatetime).reversed()).collect(Collectors.toList()).get(0);
                equipVariableCollectContextList.add(new MesEquipVariableCollectContext(reqBean.getOrganizeCode(), workOrderReductionSource.getWorkOrderNo(), MesExtEnumUtil.CELL_MESSAGE_SOURCE.READ.getValue()));
            }

            //保存上下文扫/读信息:加工单
            productionDispatchContextStepService.dispatchScanWorkOrderNoContext(reqBean, equipVariableCollectContextList);

            this.sendMessage(reqBean, new StationResultBean().writeDbLog(), String.format("读取的装配件条码%s获取到匹配工单%s!",
                    assemblySnList.toString(), equipVariableCollectContextList.stream().filter(o -> null != o).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.toList()).toString()),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

            //加工单验证工步 【非排序】
            stepResult = ((IStepService) SpringContextsUtil.getBean("mesWorkOrderCheckNosortStepService")).executeInState(reqBean);

        } finally {

            //验证失败后, 删除上下文扫/读信息:装配件条码
            if (!stepResult.isCompleted()) productionDispatchContextStepService.removeScanAssemblySnContext(reqBean);

        }

        return stepResult;

    }

    //查询条码与工单对应关系【在前道工序中作为主条码写入次关系表】
    private Map<String, List<MesWorkOrderReductionSource>> getWorkOrderReductionSourceMap(String organizeCode, List<String> assemblySnList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (assemblySnList.size() == 1) DdlPreparedPack.getStringEqualPack(assemblySnList.get(0), MesPcnExtConstWords.PRODUCT_SN, packBean);
        else DdlPreparedPack.getInPackList(assemblySnList, MesPcnExtConstWords.PRODUCT_SN, packBean);
        List<MesWorkOrderReductionSource> workOrderReductionSourceList = workOrderReductionSourceRepository.findByHqlWhere(packBean);
        return CollectionUtils.isEmpty(workOrderReductionSourceList) ? null :
                workOrderReductionSourceList.stream().filter(o -> null != o).collect(Collectors.groupingBy(MesWorkOrderReductionSource::getProductSn));
    }

}
