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

import com.jiayue.ipfcst.common.data.constant.enums.TunnelStatus;
import com.jiayue.ipfcst.common.data.entity.ProtocolGatherDataPoint;
import com.jiayue.ipfcst.dataexchange.container.ProtocolDataContainer;
import com.jiayue.ipfcst.dataexchange.tunnelworker.gathers.iml.CdtRtuDataGather;
import lombok.Setter;
import lombok.experimental.Accessors;
import wei.yigulu.cdt.cdtframe.AbstractCDTDataHandler;
import wei.yigulu.cdt.cdtframe.BaseDateType;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 基于数据模块的cdt的数据处理类
 *
 * @author: xiuwei
 * @version:
 */
public class MyCDTDataHandler extends AbstractCDTDataHandler {

  ProtocolDataContainer protocolDataContainer = ProtocolDataContainer.getInstance();

  /**
   * cdt遥测点表
   */
  @Setter
  @Accessors(chain = true)
  private Map<Integer, ProtocolGatherDataPoint> cdtYcDataPoints;

  /**
   * cdt遥信点表
   */
  @Setter
  @Accessors(chain = true)
  private Map<Integer, ProtocolGatherDataPoint> cdtYxDataPoints;

  /**
   * cdt rtu 的数据采集对象 用于采集数据
   */
  private CdtRtuDataGather cdtRtuDataGather;

  /**
   * 构造方法
   *
   * @param cdtRtuDataGather cdt 采集通道实体
   */
  public MyCDTDataHandler(CdtRtuDataGather cdtRtuDataGather) {
    this.cdtRtuDataGather = cdtRtuDataGather;
    this.cdtYcDataPoints = cdtRtuDataGather.getCdtYcDataPoints();
    this.cdtYxDataPoints = cdtRtuDataGather.getCdtYxDataPoints();
  }

  @Override
  protected void processImportantYc(List<BaseDateType> dates) {
    processYc(dates);
  }

  @Override
  protected void processSecondYc(List<BaseDateType> dates) {
    processYc(dates);
  }

  @Override
  protected void processCommonYc(List<BaseDateType> dates) {
    processYc(dates);
  }

  @Override
  protected void processYx(List<BaseDateType> dates) {
    for (BaseDateType dateType : dates) {
      dateType.getDates().forEach((k, v) -> {
        if (this.cdtYxDataPoints.containsKey(k)) {
          protocolDataContainer.putBoolean(this.cdtYxDataPoints.get(k).getId(), (Boolean) v);
        }
      });
    }
  }

  /**
   * 不分重要 次要和普通 统一处理遥测
   *
   * @param dates
   */
  private void processYc(List<BaseDateType> dates) {
    for (BaseDateType dateType : dates) {
      getLog().info("接收到数据：" + dateType.getDates());
      dateType.getDates().forEach((k, v) -> {
        if (this.cdtYcDataPoints.containsKey(k)) {
          protocolDataContainer.putNumber(this.cdtYcDataPoints.get(k).getId(), BigDecimal.valueOf((Integer) v).multiply(BigDecimal.valueOf(this.cdtYcDataPoints.get(k).getMagnification())));
        }
      });
    }
  }


  @Override
  public void connected() {
    this.cdtRtuDataGather.setTunnelStatus(TunnelStatus.LISTENSERIALSUCCESS);
  }


  @Override
  public void disconnected() {
    this.cdtRtuDataGather.setTunnelStatus(TunnelStatus.LISTENSERIALFAIL);
  }
}
