package com.jiayue.ipfcst.dataexchange.controller;

import com.alibaba.fastjson.JSON;
import com.jiayue.ipfcst.aop.SaveValidate;
import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.common.data.constant.enums.TunnelType;
import com.jiayue.ipfcst.common.data.entity.BaseTunnelInfo;
import com.jiayue.ipfcst.dataexchange.exception.DataExchangeException;
import com.jiayue.ipfcst.dataexchange.service.ImpactOnContainerOperation;
import com.jiayue.ipfcst.dataexchange.service.TunnelInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import purejavacomm.CommPortIdentifier;

import java.util.*;

/**
 * 通道对外接口
 *
 * @author zy
 * @version 3.0
 */
@RequestMapping("/TunnelInfo")
@RestController
@Slf4j
public class TunnelInfoController {

  @Autowired
  TunnelInfoService tunnelInfoService;

  @Autowired
  ImpactOnContainerOperation impactOnContainerOperation;

  /***
   * 获取所有的通道信息
   *
   * @return ResponseVO  统一返回值格式
   */
  @GetMapping(value = "/getAllTunnel")
  public ResponseVO getAllTunnel() {
    try {
      List<BaseTunnelInfo> list = tunnelInfoService.getAllTunnel();
      return ResponseVO.success(list);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(" 获取所有的通道信息异常");
      return ResponseVO.fail();
    }
  }

  /**
   * 根据通道类型来查询
   */
  @SneakyThrows
  @GetMapping(value = "/getTunnel/{tunnelType}")
  public ResponseVO getTunnel(@PathVariable String tunnelType) {
    try {
      List list = tunnelInfoService.findByTunnelType(tunnelType);
      return ResponseVO.success(list);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(" 获取所有的通道信息异常");
      return ResponseVO.fail();
    }
  }

  /**
   * 保存
   */
  @PostMapping
  @SaveValidate
  public ResponseVO saveTunnelInfo(@RequestBody JSONObject baseTunnelInfo)
    throws DataExchangeException {
    String type = baseTunnelInfo.getString("tunnelType");
    BaseTunnelInfo tunnelInfo = (BaseTunnelInfo) JSONObject.toBean(baseTunnelInfo, TunnelType.valueOf(type).getTunnelInfoClazz());
    System.out.println(JSON.toJSONString(tunnelInfo));
    BaseTunnelInfo baseInfo = tunnelInfoService.saveOrUpdateTunnelInfo(tunnelInfo);
    System.out.println(JSON.toJSONString(baseInfo));
    impactOnContainerOperation.addTunnel(baseInfo);
    return ResponseVO.success(baseInfo);

  }

  /*修改*/
  @PutMapping
  @SaveValidate
  public ResponseVO updateTunnelInfo(@RequestBody JSONObject baseTunnelInfo)
    throws BusinessException {
    String type = baseTunnelInfo.getString("tunnelType");
    BaseTunnelInfo tunnelInfo = (BaseTunnelInfo) JSONObject.toBean(baseTunnelInfo, TunnelType.valueOf(type).getTunnelInfoClazz());
    BaseTunnelInfo baseInfo = tunnelInfoService.saveOrUpdateTunnelInfo(tunnelInfo);
    System.out.println(JSON.toJSONString(baseInfo));
    impactOnContainerOperation.tunnelReBuild(baseInfo);
    return ResponseVO.success(1);
  }

  /**
   * 删除通道
   */
  @SneakyThrows
  @DeleteMapping(value = "/{id}/{tunnelType}")
  @SaveValidate
  public ResponseVO delete(@PathVariable("id") String id, @PathVariable("tunnelType") String tunnelType) {
    try {
      this.tunnelInfoService.delete(id, tunnelType);
      impactOnContainerOperation.deleteTunnel(id);
      return ResponseVO.success(1);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("删除通道信息异常");
      return ResponseVO.fail();
    }

  }

  /**
   * 删除通道
   */
  @SneakyThrows
  @DeleteMapping(value = "/deleteDataPointById/{id}/{tunnelType}")
  @SaveValidate
  public ResponseVO deleteDataPointById(@PathVariable("id") String id, @PathVariable("tunnelType") String tunnelType) {
    try {
      this.tunnelInfoService.deleteDataPointById(id, tunnelType);
      return ResponseVO.success(1);
    } catch (Exception e) {
      e.printStackTrace();
      log.error("删除通道信息异常");
      return ResponseVO.fail();
    }

  }

  /***
   * 获取服务器所有的串口名称
   * @return
   */
  @GetMapping(value = "/getServerSerialPorts")
  public ResponseVO getServerSerialPorts() {
    List<String> ports = new ArrayList<>();
    Enumeration enumeration = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId;
    while (enumeration.hasMoreElements()) {
      portId = (CommPortIdentifier) enumeration.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        ports.add(portId.getName());
      }
    }
    return ResponseVO.success(ports);
  }

  /***
   * 将接入通道封装成映射类型
   * @return
   */
  @GetMapping(value = "/findbyMaster")
  public ResponseVO getByMaster() {
    List<BaseTunnelInfo> baseTunnelInfos = tunnelInfoService.getAllGatherTunnel();
    List<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> nullMap = new HashMap<>();
    nullMap.put("key", null);
    nullMap.put("label", "不绑定");
    nullMap.put("value", null);
    list.add(nullMap);
    for (BaseTunnelInfo baseTunnelInfo : baseTunnelInfos) {
      Map<String, Object> map = new HashMap<>();
      map.put("key", baseTunnelInfo.getId());
      map.put("label", baseTunnelInfo.getTunnelName());
      map.put("value", baseTunnelInfo.getId());
      list.add(map);
    }
    return ResponseVO.success(list);
  }


}
