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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.jx.SxNoumenonSnPopUpOnlineModuleService;
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.api.iservice.busi.IStepCommonMethodService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.platform.plugin.opc.iservice.IOpcUAService;
import cn.estsh.i3plus.platform.plugin.opc.service.OpcUAService;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.hardswitch.bean.OpcUAParam;
import cn.estsh.i3plus.pojo.mes.bean.MesPlc;
import cn.estsh.i3plus.pojo.mes.bean.MesProdRouteOptParam;
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.MesPlcRepository;
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.text.MessageFormat;
import java.util.Map;

/**
 * @Description : 工步业务-本体条码上线PLC放行工步
 * @Reference :
 * @Author : xinwang.yi
 * @CreateDate : 2023-10-16
 * @Modify:
 **/
@Slf4j
@Service("sxPlcOutStepService")
public class SxPlcOutStepService extends BaseStepService {

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Autowired
    private MesPlcRepository plcRepository;

    @Autowired
    private SxNoumenonSnPopUpOnlineModuleService snPopUpOnlineModuleService;


    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("SxPlcOutStepService[execute] 参数：{}", reqBean);

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

        Map<String, MesProdRouteOptParam> codeValueMap = stepCommonMethodService.getStepCfgInfo(reqBean);
        log.info("SxPlcOutStepService --- 产线[{}]工位[{}]:工步参数 [{}]", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), codeValueMap);

        String plcCode = (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.DATA_COLLECT_PLC_SN)) ?
                codeValueMap.get("PCN_OUT_CODE").getParamValue() : null;

        String plcOutData = (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.DATA_COLLECT_PLC_SN)) ?
                codeValueMap.get("PLC_OUT_DATA").getParamValue() : null;

        //Map<String, String> wcpcMap = fsmCommonService.getCachedWorkCellParam(reqBean);

        if (StringUtils.isEmpty(plcCode)) {
            return execNonCompleteAndSendMsgReturn(reqBean, resultBean, stepResult, "当前工位未维护PLC代码");
        }
        MesPlc plc = getPlc(reqBean.getOrganizeCode(), plcCode);
        if (plc == null) {
            return execNonCompleteAndSendMsgReturn(reqBean, resultBean, stepResult, String.format("PLC代码[%s]不存在", plcCode));
        }

        Boolean writeResult = doWriteOpcParamValue(plc, plcOutData);

        log.info("SxPlcOutStepService --- 放行结果：{} ", writeResult);

        return stepResult;

    }

    public Boolean doWriteOpcParamValue(MesPlc plc, String value) {
        IOpcUAService opcService = new OpcUAService();
        String tagAddress = MessageFormat.format("{0}.{1}.{2}", plc.getChannel(), plc.getDevice(), plc.getTagAddress());
        OpcUAParam opcParam = new OpcUAParam();
        opcParam.setServerUrl(plc.getOpcUrl());
        opcParam.setTagAddress(tagAddress);
        opcParam.setNamespaceIndex(plc.getNameSpaceIndex());
        opcParam.setTagValueType(plc.getDataType());
        opcParam.setTagValue(value);
        Boolean result = opcService.editOpcParamValue(opcParam);
        opcService.disConnection();
        return result;
    }

    public MesPlc getPlc(String organizeCode, String plcCode) {

        return plcRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.PLC_CODE},
                new Object[]{organizeCode, CommonEnumUtil.IS_VAILD.VAILD.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), plcCode});
    }

}
