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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionCustomContextStepService;
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.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCenter;
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.util.MesExtEnumUtil;
import com.alibaba.fastjson.JSONObject;
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.List;
import java.util.Optional;

/**
 * @Description : 扫描装配件条码工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesAssemblyScanStepServiceBak")
public class MesAssemblyScanStepServiceBak extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Override
    public StepResult guide(StationRequestBean reqBean) {

        productionCustomContextStepService.sendStepContextMessage(reqBean);

        return stepSuccessCompleteAndSendGuideReturn(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "请扫描装配件条码!");

    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

        //扫描信息置空
        String scanInfo = reqBean.resetScanInfo(reqBean.getScanInfo());

        //获取上下文信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.dispatchCurCellEquipment(reqBean);

        //配置错误 抛出异常
        if (!productionProcessContext.getSuccess()) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //存储生产过程上下文对象
        productionProcessContextStepService.dispatchProductionProcessContext(reqBean, productionProcessContext);

        //获取上下文产品加工规则数据信息集合
        List<MesProdRuleContext> prodRuleContextList = productionDispatchContextStepService.getProdRuleDataContext(reqBean);

        //验证当前是否需要扫描装配件条码: 是否存在装配件清单 【当前验证只能对内部触发生效】
        if (!CollectionUtils.isEmpty(prodRuleContextList) && !checkIsNeedScanAssembly(prodRuleContextList))
            return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前加工规则无配置装配件清单,当前无需扫描装配件条码!");

        //处理装配件的装配爆炸图和音频文件
        doHandleAssemblyFile(reqBean, productionProcessContext.getWorkCenter(), prodRuleContextList);

        //验证当前是否需要读装配件条码: 验证是否存在待绑定数据 【当前验证只能对内部触发生效】
        if (!CollectionUtils.isEmpty(prodRuleContextList) && !hasUnBindAssembly(prodRuleContextList))
            return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前加工规则对应的装配件清单已扫描完毕,当前无需扫描装配件条码!");

        if (StringUtils.isEmpty(scanInfo)) stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "请扫描装配件条码!");

        //发送工步内容
        productionCustomContextStepService.sendStepContextMessage(reqBean, scanInfo, MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN);

        //封装当前扫描的装配件信息
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = getAssemblySnJson(reqBean, scanInfo);

        //从上下文中取出工位当前要使用的设备
        MesCellEquipContext cellEquipContext = productionProcessContext.getCurCellEquip();

        //需要扫描的绑定数量 [没有加工规则场景]
        Integer needQty = cellEquipContext.getCavity() * cellEquipContext.getBindQty();

        //没有加工规则代表需要反向匹配出加工规则, 需要根据设备腔数直接批量扫描 生成零件号
        if (CollectionUtils.isEmpty(prodRuleContextList)) {

            //根据设备代码获取可复用条码的个数
            Integer count = productionCustomContextStepService.getRepeatAssemblySnCount(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), cellEquipContext.getEquipmentCode());

            //获取上下文生产扫/读信息:装配件条码
            List<MesEquipVariableCollectContext> cachedEquipVariableCollectContextList = productionDispatchContextStepService.getScanAssemblySnContext(reqBean);
            //删除上下文扫/读信息:装配件条码
            productionDispatchContextStepService.removeScanAssemblySnContext(reqBean);

            Integer scanedQty = (!CollectionUtils.isEmpty(cachedEquipVariableCollectContextList) ? cachedEquipVariableCollectContextList.size() : MesPcnExtConstWords.ZERO) + count;

            //判断当前已存在数量是否超过需要数量
            if (scanedQty > needQty) stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(), String.format(
                    "当前可复用条码数量[%s]加上装配件条码数量[%s]已经超过设备腔数[%s]每腔个数[%s]配置,请重新扫描装配件条码!", count, cachedEquipVariableCollectContextList.size(), cellEquipContext.getCavity(), cellEquipContext.getBindQty()));

            if (!CollectionUtils.isEmpty(cachedEquipVariableCollectContextList)) {
                if (scanedQty == needQty) equipVariableCollectContextList = cachedEquipVariableCollectContextList;
                else equipVariableCollectContextList.addAll(cachedEquipVariableCollectContextList);
            }

        }

        //保存上下文扫/读信息:装配件条码
        productionDispatchContextStepService.dispatchScanAssemblySnContext(reqBean, equipVariableCollectContextList);

        //存在加工规则 默认扫描一次 匹配一次 循环处理直到当前的加工规则全部匹配完毕
        if (!CollectionUtils.isEmpty(prodRuleContextList)) return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).scanInfo(scanInfo), stepResult, String.format("当前扫描信息装配件条码[%s]!", scanInfo));

        if (equipVariableCollectContextList.size() == needQty) return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).scanInfo(scanInfo), stepResult, String.format("当前扫描信息装配件条码[%s],已扫描个数[%s]!", scanInfo, equipVariableCollectContextList.size() + "/" + needQty));

        return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).scanInfo(scanInfo), stepResult, false,
                MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, String.format("当前扫描信息装配件条码[%s],请继续扫描装配件条码,已扫描个数[%s]!", scanInfo, equipVariableCollectContextList.size() + "/" + needQty));

    }

    //处理装配件的装配爆炸图和音频文件
    private void doHandleAssemblyFile(StationRequestBean reqBean, MesWorkCenter workCenter, List<MesProdRuleContext> prodRuleContextList) {

        if (CollectionUtils.isEmpty(prodRuleContextList)) return;

        Boolean isSendFile = false;
        Boolean isBreakLoop = false;
        LOOP:
        for (MesProdRuleContext prodRuleContext : prodRuleContextList) {
            if (null == prodRuleContext || StringUtils.isEmpty(prodRuleContext.getAssemblyDataJson())) continue;
            if (MesExtEnumUtil.WORK_CENTER_TYPE.NOSORT.getValue() == workCenter.getCenterType()) {
                List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList = prodRuleContext.getNosortAssemblyDataContext();
                for (MesProductionAssemblyNosortContext productionAssemblyNosortContext : productionAssemblyNosortContextList) {
                    if (null == productionAssemblyNosortContext ||
                            productionAssemblyNosortContext.getFileIsFinished().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0 ||
                            MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.checkIsNoShow(productionAssemblyNosortContext.getMatchType()) ||
                            (StringUtils.isEmpty(productionAssemblyNosortContext.getImageFileUrl()) && StringUtils.isEmpty(productionAssemblyNosortContext.getAudioFileUrl()))) continue;
                    //不扫描的默认直接被标记绿色已装配, 但是文件也需要发送
                    if (productionAssemblyNosortContext.getMatchType().compareTo(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_50.getValue()) != 0) isBreakLoop = true;
                    isSendFile = true;
                    //发送文件到客户端
                    sendFile(reqBean, productionAssemblyNosortContext.fileIsFinished());
                    if (isBreakLoop) break LOOP;
                }
                prodRuleContext.assemblyDataJson(productionAssemblyNosortContextList);
            } else {
                List<MesProductionAssemblySortContext> productionAssemblySortContextList = prodRuleContext.getSortAssemblyDataContext();
                for (MesProductionAssemblySortContext productionAssemblySortContext : productionAssemblySortContextList) {
                    if (null == productionAssemblySortContext ||
                            productionAssemblySortContext.getFileIsFinished().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0 ||
                            MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.checkIsNoShow(productionAssemblySortContext.getMatchType()) ||
                            (StringUtils.isEmpty(productionAssemblySortContext.getImageFileUrl()) && StringUtils.isEmpty(productionAssemblySortContext.getAudioFileUrl()))) continue;
                    //不扫描的默认直接被标记绿色已装配, 但是文件也需要发送
                    if (productionAssemblySortContext.getMatchType().compareTo(MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.MATCH_TYPE_50.getValue()) != 0) isBreakLoop = true;
                    isSendFile = true;
                    //发送文件到客户端
                    sendFile(reqBean, productionAssemblySortContext.fileIsFinished());
                    if (isBreakLoop) break LOOP;
                }
                prodRuleContext.assemblyDataJson(productionAssemblySortContextList);
            }
        }
        //保存上下文产品加工规则信息集合
        if (isSendFile) productionDispatchContextStepService.dispatchProdRuleDataContext(reqBean, prodRuleContextList);
    }

    //发送文件到客户端
    private void sendFile(StationRequestBean reqBean, MesProductionAssemblyContext productionAssemblyContext) {
        if (!StringUtils.isEmpty(productionAssemblyContext.getImageFileUrl()))
            this.sendMessage(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue())
                    .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MODULE_CUSTOM_CONTENT.getValue())
                    .dataType(MesPcnEnumUtil.STATION_DATA_TYPE.IMAGE.getValue())
                    .customPageName(MesPcnExtConstWords.CUSTOM_PAGE_NAME_ASSEMBLY)
                    .message(String.format("装配件信息来源ID[%s],装配件爆炸图URL[%s]", productionAssemblyContext.getSourceId(), productionAssemblyContext.getImageFileUrl()))
                    .resultObj(new JSONObject().put(MesPcnExtConstWords.URL, productionAssemblyContext.getImageFileUrl())));
        if (!StringUtils.isEmpty(productionAssemblyContext.getAudioFileUrl()))
            this.sendMessage(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue())
                    .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.CUSTOM_COMPONENT.getValue())
                    .dataType(MesPcnEnumUtil.STATION_DATA_TYPE.SOUND.getValue())
                    .message(String.format("装配件信息来源ID[%s],装配件音频文件URL[%s]", productionAssemblyContext.getSourceId(), productionAssemblyContext.getAudioFileUrl()))
                    .resultObj(new JSONObject().put(MesPcnExtConstWords.URL, productionAssemblyContext.getAudioFileUrl())));
    }

    //判断是否存在装配件清单
    private Boolean checkIsNeedScanAssembly(List<MesProdRuleContext> prodRuleContextList) {
        Optional<MesProdRuleContext> optional = prodRuleContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getAssemblyDataJson()))).findFirst();
        return (null == optional || !optional.isPresent()) ? false : true;
    }

    //验证是否存在待绑定数据
    private Boolean hasUnBindAssembly(List<MesProdRuleContext> prodRuleContextList) {
        Boolean hasUnBindAssembly = false;
        for (MesProdRuleContext prodRuleContext : prodRuleContextList) {
            if (null == prodRuleContext || StringUtils.isEmpty(prodRuleContext.getAssemblyDataJson())) continue;
            List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList = prodRuleContext.getNosortAssemblyDataContext();
            Optional<MesProductionAssemblyNosortContext> optional = productionAssemblyNosortContextList.stream().filter(o -> (null != o && o.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_30.getValue()) == 0)).findFirst();
            if (null == optional || !optional.isPresent()) continue;

            hasUnBindAssembly = true;
            break;
        }
        return hasUnBindAssembly;
    }

    //封装当前扫描的装配件信息
    private List<MesEquipVariableCollectContext> getAssemblySnJson(StationRequestBean reqBean, String scanInfo) {

        List<MesEquipVariableCollectContext> equipVariableCollectContextList = new ArrayList<>();

        equipVariableCollectContextList.add(new MesEquipVariableCollectContext(reqBean.getOrganizeCode(), scanInfo, MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue()));

        return equipVariableCollectContextList;

    }

}
