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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.jx.JxSnFinalInspectionModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.actor.shipping.dispatch.IFsmCommonService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.model.ButtonBean;
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 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.Map;
import java.util.StringJoiner;

/**
 * @Description : 嘉兴条码终检外观检查工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("jxSnFinalInspectionAspectCheckStepService")
public class JxSnFinalInspectionAspectCheckStepService extends BaseStepService {

    @Autowired
    private JxSnFinalInspectionModuleService snFinalInspectionModuleService;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Override
    public StepResult init(StationRequestBean reqBean) {
        clearStepContent(reqBean);
        return super.init(reqBean);
    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        log.info("工厂{}生产线{}工位{}: --- STEP EXECUTE --- JxSnFinalInspectionAspectCheckStepService --- START --- ", reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());

        StationResultBean resultBean = new StationResultBean();
        StepResult stepResult = StepResult.getSuccessComplete();

        String busiFlag = (String) snFinalInspectionModuleService.doHandleBusiFlag(reqBean, 1, null);
        if (!StringUtils.isEmpty(busiFlag)) snFinalInspectionModuleService.doHandleBusiFlag(reqBean, 3, null);

        String suffixSn = StringUtils.isEmpty(reqBean.getProductSn()) ? getManageCode(reqBean.getTray(), 1) : reqBean.getProductSn();
        String suffix = String.format("当前产品:%s[%s]外观检查", StringUtils.isEmpty(reqBean.getProductSn()) ? "管理编码" : "产品条码", suffixSn);

        if (!StringUtils.isEmpty(reqBean.getScanInfo())) busiFlag = getBusiFlagByScanInfo(reqBean, resultBean, suffix, suffixSn, stepResult);

        if (StringUtils.isEmpty(busiFlag)) execSendAspectCheckBusiFlag(reqBean, resultBean, suffix, suffixSn, stepResult);

        reqBean.setScanInfo(null);

        log.info("工厂{}生产线{}工位{}: --- STEP EXECUTE --- JxSnFinalInspectionAspectCheckStepService --- SUCCESS --- ", reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());

        BUSI_FLAG item = BUSI_FLAG.getByValue(busiFlag);

        if (!item.getIsComplete()) reqBean.getDataMap().put(MesPcnExtConstWords.PLC_PASS_VALUE, new StringJoiner(MesPcnExtConstWords.E_UNDERLINE).add(MesPcnExtConstWords.PLC_PASS_VALUE).add(busiFlag).toString());

        return execDynamicsCompleteAndSendMsgReturn(reqBean, resultBean, stepResult, item.getIsComplete(), String.format("%s[%s]!", suffix, item.getDescription()));

    }

    private String getBusiFlagByScanInfo(StationRequestBean reqBean, StationResultBean resultBean, String suffix, String suffixSn, StepResult stepResult) {
        fsmCommonService.checkWcpcMapForDoScan(reqBean);
        String busiFlagCodeCfg = reqBean.getWcpcMap().get(BUSI_FLAG.BUSI_FLAG_CODE.getValue());
        Map<String, String> busiFlagCodeMap = StringUtils.isEmpty(busiFlagCodeCfg) ? null : JSONObject.parseObject(busiFlagCodeCfg, Map.class);
        String busiFlag = CollectionUtils.isEmpty(busiFlagCodeMap) ? null : busiFlagCodeMap.get(reqBean.getScanInfo());
        if (CollectionUtils.isEmpty(busiFlagCodeMap) || !BUSI_FLAG.BUSI_FLAG_CODE.check(busiFlag))
            execSendAspectCheckBusiFlag(reqBean, resultBean, suffix, suffixSn, stepResult.msg(String.format("%s操作失败!生产线[%s]工位[%s]未配置有效的检查业务码工位参数[%s]!", suffix, reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), BUSI_FLAG.BUSI_FLAG_CODE.getValue())));
        if (StringUtils.isEmpty(busiFlag))
            execSendAspectCheckBusiFlag(reqBean, resultBean, suffix, suffixSn, stepResult.msg(String.format("%s操作失败!扫描的检测业务码[%s]验证失败!", suffix, reqBean.getScanInfo())));
        return busiFlag;
    }

    private void execSendAspectCheckBusiFlag(StationRequestBean reqBean, StationResultBean resultBean, String suffix, String suffixSn, StepResult stepResult) {

        if (StringUtils.isEmpty(stepResult.getMsg())) this.sendMessage(reqBean, resultBean, String.format("请对%s!", suffix), MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        else this.sendMessage(reqBean, resultBean, stepResult.getMsg(), MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);

        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.STEP_CONTENT.getValue());
        resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.BUTTON.getValue());
        List<ButtonBean> buttonBeanList = new ArrayList<>();
        buttonBeanList.add(ButtonBean.builder().buttonCode(BUSI_FLAG.QUALIFIED.value).buttonName(BUSI_FLAG.QUALIFIED.description).methodContent(suffixSn).buttonDesc(BUSI_FLAG.QUALIFIED.description).build());
        buttonBeanList.add(ButtonBean.builder().buttonCode(BUSI_FLAG.REPAIR.value).buttonName(BUSI_FLAG.REPAIR.description).methodContent(suffixSn).buttonDesc(BUSI_FLAG.REPAIR.description).build());
        resultBean.setResultList(buttonBeanList);
        this.sendMessage(reqBean, resultBean);

        execSendGuideAndThrowEx(reqBean, resultBean, "请扫描检测业务码或点击业务按钮!");

    }

    private String getManageCode(String manageCode, Integer length) {
        if (StringUtils.isEmpty(manageCode)) return null;
        String[] manageCodeArr = manageCode.split(MesPcnExtConstWords.AND);
        if (manageCodeArr.length >= length) return manageCodeArr[length - 1];
        else return null;
    }

    enum BUSI_FLAG {

        BUSI_FLAG_CODE("BUSI_FLAG_CODE", "检测业务码", true),
        QUALIFIED("QUALIFIED", "检查合格", true),
        REPAIR("REPAIR", "返修", false);

        private String value;
        private String description;
        private Boolean isComplete;

        BUSI_FLAG(String value, String description, Boolean isComplete) {
            this.value = value;
            this.description = description;
            this.isComplete = isComplete;
        }

        public String getValue() {
            return value;
        }

        public String getDescription() {
            return description;
        }

        public Boolean getIsComplete() {
            return isComplete;
        }

        public static BUSI_FLAG getByValue(String value) {
            for (BUSI_FLAG item : values()) {
                if (item.getValue().equals(value)) {
                    return item;
                }
            }
            return null;
        }

        public Boolean check(String busiFlag) {
            if (StringUtils.isEmpty(busiFlag)) return true;
            if (!busiFlag.equals(QUALIFIED.getValue()) && !busiFlag.equals(REPAIR.getValue())) return false;
            return true;
        }
    }

}
