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;
import java.util.stream.Collectors;

/**
 * @Description : 扫描装配件条码工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesAssemblyScanStepService")
public class MesAssemblyScanStepService 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<MesProductionPsInContext> productionPsInContextList = productionDispatchContextStepService.getProductionPsInContext(reqBean);
        //剔除空腔主条码
        List<MesProductionPsInContext> productionPsInContextListNoFinishCode = CollectionUtils.isEmpty(productionPsInContextList) ? null :
                productionPsInContextList.stream().filter(o -> (null != o && o.getIsFinishCode().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0)).collect(Collectors.toList());
        //当前未匹配的主条码
        List<MesProductionPsInContext> curProductionPsInContextList = CollectionUtils.isEmpty(productionPsInContextList) ? null :
                productionPsInContextList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getForeignKey()) && o.getIsFinishCode().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0)).collect(Collectors.toList());

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

        //判断业务场景: 1=唯一加工规则场景/排序; 2=无进无出扫装配件生成零件号场景; 3=有进未匹配加工规则扫装配件生成零件号场景
        Integer busiType = getBusiType(productionPsInContextListNoFinishCode, prodRuleContextList);

        //验证场景1 当前是否需要扫描装配件条码: 是否存在装配件清单 【当前验证只能对内部触发生效】
        if (busiType == BUSI_TYPE.ONE.value && !CollectionUtils.isEmpty(prodRuleContextList) && !checkIsNeedScanAssembly(prodRuleContextList)) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, "当前加工规则无装配件清单,当前无需扫描装配件条码!");
        }

        //场景1 处理装配件的装配爆炸图和音频文件
        if (busiType == BUSI_TYPE.ONE.value) doHandleAssemblyFile(reqBean, productionProcessContext.getWorkCenter(), prodRuleContextList);

        //验证场景1 当前是否需要扫描装配件条码: 验证是否存在待绑定数据 【当前验证只能对内部触发生效】
        if (busiType == BUSI_TYPE.ONE.value && !CollectionUtils.isEmpty(prodRuleContextList) && !hasUnBindAssembly(prodRuleContextList)) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, "当前加工规则对应的装配件清单已扫描完毕,当前无需扫描装配件条码!");
        }

        //验证场景3的当前未匹配的主条码是否是空腔码
        if (busiType == BUSI_TYPE.THREE.value && CollectionUtils.isEmpty(curProductionPsInContextList)) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, "当前主条码对应的装配件清单已扫描完毕,当前无需扫描装配件条码!");
        }

        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, productionProcessContext, scanInfo);

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

        //需要扫描的绑定数量
        Integer needQty = getNeedQty(busiType, cellEquipContext, curProductionPsInContextList);

        //非场景1的情况下代表需要反向匹配出加工规则, 需要根据设备腔数直接批量扫描 生成零件号
        Integer repeatAssemblySnAmount = 0;
        if (busiType != BUSI_TYPE.ONE.value) {

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

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

            //当前已扫描的装配件条码数量 + 可复用数量 * 当前未匹配的主条码数量
            repeatAssemblySnAmount = repeatAssemblySnCount * (!CollectionUtils.isEmpty(curProductionPsInContextList) ? curProductionPsInContextList.size() : cellEquipContext.getCavity());
            Integer scanedQty = (!CollectionUtils.isEmpty(cachedEquipVariableCollectContextList) ? cachedEquipVariableCollectContextList.size() : MesPcnExtConstWords.ZERO) + repeatAssemblySnAmount;

            //判断当前已存在数量是否超过需要数量
            String suffix = !CollectionUtils.isEmpty(curProductionPsInContextList) ? String.format("主条码数量[%s]", curProductionPsInContextList.size()) : MesPcnExtConstWords.EMPTY;
            if (scanedQty > needQty) stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(), String.format(
                    "%s设备可复用条码数量[%s]设备腔数[%s]每腔个数[%s]此前已扫描的装配件条码数量[%s],当前计算数量[%s]已超过扫描需求总数量[%s],请重新扫描装配件条码!",
                    suffix, repeatAssemblySnCount, cellEquipContext.getCavity(), cellEquipContext.getBindQty(), cachedEquipVariableCollectContextList.size(), scanedQty, needQty));

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

        }

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

        //唯一加工规则场景 默认扫描一次 匹配一次 循环处理直到当前的加工规则全部匹配完毕
        if (busiType == BUSI_TYPE.ONE.value) {
            //排序线可疑码场景下,该数据为空,验证生产线是否忽略质量状态
            if (CollectionUtils.isEmpty(equipVariableCollectContextList)) {
                //保存上下文加工结果:可疑
                productionDispatchContextStepService.dispatchProductResultContext(reqBean, MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS.getValue() + MesPcnExtConstWords.EMPTY);
                this.sendMessage(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).scanInfo(scanInfo), "当前扫描信息[排序线可疑码]!", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                if (StringUtils.isEmpty(productionProcessContext.getWorkCenter().getIsIgnoreQc()) || productionProcessContext.getWorkCenter().getIsIgnoreQc().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0) return stepResult;
                else stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "请扫描装配件条码!");
            }
            return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).scanInfo(scanInfo), stepResult, String.format("当前扫描信息装配件条码[%s]!", scanInfo));
        }

        String suffix = repeatAssemblySnAmount == 0 ? MesPcnExtConstWords.EMPTY : String.format(",可复用个数[%s]", repeatAssemblySnAmount);

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

        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]%s!", scanInfo, equipVariableCollectContextList.size() + "/" + needQty, suffix));

    }

    //判断业务场景: 1=唯一加工规则场景/排序线; 2=无进无出扫装配件生成零件号场景; 3=有进未匹配加工规则扫装配件生成零件号场景
    private Integer getBusiType(List<MesProductionPsInContext> productionPsInContextListNoFinishCode, List<MesProdRuleContext> prodRuleContextList) {
        if (CollectionUtils.isEmpty(productionPsInContextListNoFinishCode) && CollectionUtils.isEmpty(prodRuleContextList)) return BUSI_TYPE.TWO.value;
        if (!CollectionUtils.isEmpty(productionPsInContextListNoFinishCode) && (CollectionUtils.isEmpty(prodRuleContextList) || productionPsInContextListNoFinishCode.size() != prodRuleContextList.size())) return BUSI_TYPE.THREE.value;
        return BUSI_TYPE.ONE.value;
    }

    //需要扫描的绑定数量
    private Integer getNeedQty(Integer busiType, MesCellEquipContext cellEquipContext, List<MesProductionPsInContext> curProductionPsInContextList) {
        if (busiType == BUSI_TYPE.ONE.value) return 1;
        if (busiType == BUSI_TYPE.TWO.value) return cellEquipContext.getCavity() * cellEquipContext.getBindQty();
        return curProductionPsInContextList.size() * cellEquipContext.getBindQty();
    }

    //处理装配件的装配爆炸图和音频文件
    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, MesProductionProcessContext productionProcessContext, String scanInfo) {

        //排序线可疑码
        if (productionProcessContext.getWorkCenter().getCenterType().compareTo(MesExtEnumUtil.WORK_CENTER_TYPE.SORT.getValue()) == 0 && scanInfo.equals(productionProcessContext.getSortSuspiciousCode())) return null;

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

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

        return equipVariableCollectContextList;

    }

    //装配件扫描的业务场景
    enum BUSI_TYPE {

        ONE(1, "唯一加工规则场景或排序线"),//通过 产出零件 + 进料条码零件 + 设备 找到唯一的非排序产品加工规则, 产出零件与进料条码零件至少存在1个  或者 排序线

        TWO(2, "无出无进扫装配件,非排序无显示装配件匹配场景"),//产出零件与进料条码零件均不扫描, 直接扫描装配件, 通过非排序无显示装配件匹配工步反向匹配非排序产品加工规则

        THREE(3, "无出有进扫装配件,非排序无显示装配件匹配场景");//产出零件不扫描, 扫描进料条码零件, 扫描装配, 通过非排序无显示装配件匹配工步反向匹配非排序产品加工规则, 将匹配的规则再匹配进料条码零件

        private Integer value;

        private String description;

        BUSI_TYPE(Integer value, String description) {

            this.value = value;

            this.description = description;

        }

        public Integer getValue() {
            return value;
        }

        public String getDescription() {
            return description;
        }

    }

}
