package com.jiayue.ipfcst.dataexchange.tunnelworker.workassist.iec104tcp;

import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
import com.jiayue.ipfcst.console.service.SysParameterService;
import com.jiayue.ipfcst.dataexchange.dataprocesser.datagainerhandler.BaseDataGainer;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.TotalSummonType;
import wei.yigulu.iec104.nettyconfig.Iec104SlaverBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.util.Map;


/**
 * 处理总召唤帧
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@AsduType(typeId = 100)
public class HandleTotalSummon extends TotalSummonType {


  boolean withPulse ="1".equals(SpringContextHolder.getBean(SysParameterService.class).getSysParameter("104WithPulse", "0"));

  @Override
  public byte[][] handleAndAnswer(Apdu apdu) throws Exception {
    apdu.getLog().trace("----------响应总召唤---------");
    BaseProtocolBuilder builder = apdu.getIec104Builder();

    Map<String, Object> confMap = builder.getConfigInfoMap();
    //当该帧是由 SlaverBuilder 或其子类接收到的  且为总召唤原因为激活
    if (builder instanceof Iec104SlaverBuilder) {
      if (apdu.getAsdu().getCot().getNot() == 6) {
        //响应总召唤 激活确认帧
        SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 7, builder.getLog());
        //响应遥信
        if (confMap.get("yx") != null) {
          Map<Integer, BaseDataGainer<Boolean>> yxDataPoints = (Map<Integer, BaseDataGainer<Boolean>>) confMap.get("yx");
          SendDataFrameHelper.sendYxDataFrame(apdu.getChannel(), yxDataPoints, apdu.getAsdu().getCommonAddress(), 20, builder.getLog());
        }
        //响应遥测
        if (confMap.get("yc") != null) {
          Map<Integer, BaseDataGainer<Number>> ycDataPoints = (Map<Integer, BaseDataGainer<Number>>) confMap.get("yc");
          SendDataFrameHelper.sendYcDataFrame(apdu.getChannel(), ycDataPoints, apdu.getAsdu().getCommonAddress(), 20, builder.getLog());
        }
        //响应总召唤 激活停止帧
        SendDataFrameHelper.sendTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 10, builder.getLog());
      }
    } else {
      if (withPulse && apdu.getAsdu().getCot().getNot() == 10 ){
        SendDataFrameHelper.sendPulseTotalSummonFrame(apdu.getChannel(), apdu.getAsdu().getCommonAddress(), 6, builder.getLog());
      }
    }

    return null;
  }


}
