<template>
  <el-row style="height: 100%" :gutter="10">
    <el-col :span="18" style="height: 100%">
      <el-row style="height: 66%" :gutter="10">
        <el-col :span="8" style="height: 100%">
          <el-card class="tableHeight">
            <div slot="header" class="clearfix">
              <span>网络组参数设置</span>
              <el-select  v-model="selectedGroupId" size="mini" style="width: 40%;float: right;background-color: #8CC0FB;"
              @change="selectChange">
                    <el-option v-for="item in networkGroupList"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id"/>
                  </el-select>
            </div>
            <el-table height="90%" :data="params" style="width: 100%;overflow-y: auto"  fit size="mini">
              <el-table-column width="80" prop="label" label="属性"></el-table-column>
              <el-table-column width="80" prop="value" label="当前值"></el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <!-- ID不显示操作 -->
                  <template v-if="scope.row.controlType === 'text'">
                    <span>不可修改</span>
                  </template>

                  <!-- 是否在线开关 -->
                  <el-switch
                      v-if="scope.row.controlType === 'switch-online'"
                      v-model="scope.row.value"
                      active-value="开"
                      inactive-value="关"
                      @change="val => handleSwitchChange('isOnline', val)"
                  ></el-switch>

                  <!-- 是否静默开关 -->
                  <el-switch
                      v-if="scope.row.controlType === 'switch-status'"
                      v-model="scope.row.value"
                      active-value="静默"
                      inactive-value="非静默"
                      @change="val => handleSwitchChange('status', val)"
                  ></el-switch>

                  <!-- 连接模式下拉框 -->
                  <el-select
                      v-if="scope.row.controlType === 'select'"
                      v-model="scope.row.value"
                      placeholder="请选择"
                      @change="val => handleSelectChange(val)"
                  >
                    <el-option
                        v-for="item in linkOptions"
                        :key="item"
                        :label="item"
                        :value="item"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
            <div >
              <el-select size="mini" v-model="selectPlatId" @change="getParams">
                <el-option v-for="item in platList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"/>
              </el-select>
              <el-button size="mini" type="success" style="float: right"
                         :disabled="editable()"
                         @click="editParams"
              >修改参数</el-button>
              <el-button size="mini" type="info" style="float: right"
                         :disabled="editable()"
                         @click="getParamsPre"
              >刷新</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="16" style="height: 100%">
          <el-card class="radar" border>
            <div slot="header" class="clearfix" >
              <span>通信状态显示</span>
            </div>
            <div class="echarts-box">
              <div ref="chart" id="radarEchart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row style="height: calc(34% - 6px); margin-top: 6px;" :gutter="10">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="height: 28px">
            <span>已接收消息</span>
          </div>
          <el-table :data="receivedMessage"   size="mini" height="tableHeight">
            <el-table-column prop="time" label="时间"></el-table-column>
            <el-table-column prop="translation" label="传输双方" ></el-table-column>
            <el-table-column prop="type" label="主题"></el-table-column>
            <el-table-column prop="status" label="状态" width="150">
            </el-table-column>
          </el-table>
        </el-card>
      </el-row>
    </el-col>
    <el-col :span="6" style="height: 100%;overflow-y: auto">
      <el-row style="height: calc(36%)">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="height: 28px">
            <span>已发送消息</span>
          </div>
          <el-table :data="sendMessage" fit size="mini" height="sendMessageHeight">
            <el-table-column width="80" prop="time" label="时间"></el-table-column>
            <el-table-column width="90" prop="translation" label="传输双方"></el-table-column>
            <el-table-column prop="type" label="主题"></el-table-column>
            <el-table-column width="60" prop="status" label="状态"></el-table-column>
          </el-table>
        </el-card>
      </el-row>
      <el-row style="height: calc(64% - 6px); margin-top: 6px;">
        <el-card class="target">
          <div slot="header" class="clearfix" style="height: 28px">
            <span>成员列表</span>
          </div>
          <el-table height="tableHeight" :data="members" border fit size="mini">
            <el-table-column prop="id" label="平台ID"> </el-table-column>
            <el-table-column prop="isOnline" label="是否在网"> </el-table-column>
            <el-table-column prop="status" label="静默状态"> </el-table-column>
            <el-table-column prop="linkModel" label="连接方式"> </el-table-column>
          </el-table>
        </el-card>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import {Message} from "element-ui";
export default {
  data() {
    return {
      selectedGroupId: null,
      selectedGroup: null,
      networkGroupList: [],

      chartInstance: null,
      nodes: [],
      edges: [],

      sendMessage: [],
      receivedMessage: [],
      members: [],

      tableHeight: "calc(100vh - 30px)",

      selectPlatId: null,
      platList: [],
      params: [],
      originData: {},
      linkOptions: ['实时性','可靠性'],

    };
  },
  created() {
  },
  activated() {
    this.init();
    this.interval=setInterval(this.fetchData, 5000)

  },
  deactivated() {
    if(this.interval){
      clearInterval(this.interval)
    }
  },
  mounted() {
    this.init();
    // 页面加载设置高度自适应
    window.onresize = () => {
      this.resizeDom();
    };
    // 页面加载设置高度自适应
    this.resizeDom();
  },
  methods: {
    async init() {
      await this.getNetworkGroupList();
      this.initGroup()
      if (this.selectedGroupId != null) {
        this.initChart()
        this.initSend()
        this.initReceived()
        this.initMembers()
        this.getParams()
      }else {
        this.selectPlatId = null;
      }
    },
    initGroup() {
      let flag = true;
      if (this.selectedGroupId !== 0) {
        for (let i = 0; i < this.networkGroupList.length; i++) {
          if (this.selectedGroupId === this.networkGroupList[i].id) {
            flag = false;
            this.selectedGroup = this.networkGroupList[i]
          }
        }
        if (flag) {
          this.selectedGroupId = null;
          this.selectedGroup = null;
        }
      }
    },
    selectChange() {
      for (let i = 0; i < this.networkGroupList.length; i++) {
        if (this.selectedGroupId === this.networkGroupList[i].id) {
          this.selectedGroup = this.networkGroupList[i];
          break
        }
      }
      this.selectPlatId=null;
      this.originData=null;
      this.params=[];
      this.initPlatList();
      this.initChart();
      this.initSend();
      this.initReceived();
      this.initMembers();
    },
    async getParamsPre(){
      try {
        await this.getParams();
        // 请求成功后显示提示
        this.$message({
          message: "刷新成功",
          type: "success",
          duration: 1500,
        });
      } catch (error) {
        // 可选：添加错误处理
        this.$message.error('操作失败: ' + error.message);
      }
    },
    getParams(){
      this.$http({
        url: this.$http.adornUrl("/communication/getParams?id=" + this.selectPlatId),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.produceData(data.data)
          return data
        }else {
          throw new Error(data.msg || '请求失败')
        }
      })
    },
    produceData(data){
      this.originData = {...data}
      this.params = [
        {
          propKey: 'id',
          label: '平台ID',
          value: data.id,
          controlType: 'text'
        },
        {
          propKey: 'isOnline',
          label: '链路开关',
          value: data.isOnline,
          controlType: 'switch-online'
        },
        {
          propKey: 'status',
          label: '静默状态',
          value: data.status,
          controlType: 'switch-status'
        },
        {
          propKey: 'linkModel',
          label: '连接模式',
          value: data.linkModel,
          controlType: 'select'
        }
      ];
    },
    editParams(){
      this.$http({
        url: this.$http.adornUrl("/communication/updateParams"),
        method: "post",
        data: this.originData,
      }).then(({ data }) => {
        if (data && data.code === 0) {
          Message({
            message: "操作成功",
            type: "success",
            duration: 1500,
          });
        } else {
          Message.error(data.msg);
        }
        this.getParams();
      });
    },
    // 开关修改事件
    handleSwitchChange(key, value) {
      this.originData[key] = value;
    },
    // 下拉框修改事件
    handleSelectChange(value) {
      this.originData.linkModel = value;
    },
    getNetworkGroupList() {
      this.$http({
        url: this.$http.adornUrl("/communication/getNetworkGroups"),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.networkGroupList = data.data;
          if (this.networkGroupList.length === 0) {
            Message.info("暂未设置网络组信息")
          }
        } else {
          this.networkGroupList = [];
          Message.error("无法获取网络组信息")
        }
      })
    },
    editable() {
      return this.selectPlatId===null || this.selectPlatId === 0;
    },
    fetchData(){
      if(this.selectedGroupId!=null){
        this.initMembers();
        this.initChart();
        this.initSend();
        this.initReceived();
      }
    },
    initPlatList(){
      if(this.selectedGroupId!=null){
        this.$http({
          url: this.$http.adornUrl("/communication/getMembers?id=" + this.selectedGroupId),
          method: "get",
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.platList = data.data;
          }
        })
      }
    },
    initChart() {
      this.$http({
        url: this.$http.adornUrl("/communication/getChart?id=" + this.selectedGroupId),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.nodes = data.nodes;
          this.edges = data.edges;
          if (this.chartInstance == null) {
            this.createChartInstance(this.$refs.chart);
          }
          this.chartInstance.setOption({
            series: [{
              data: this.nodes,
              links: this.edges,
            }]
          })
        }
      })
    },
    initSend() {
      this.$http({
        url: this.$http.adornUrl("/communication/getSendMessage?id=" + this.selectedGroupId),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.sendMessage = data.data;
        }
      })
    },
    initReceived() {
      this.$http({
        url: this.$http.adornUrl("/communication/getSendMessage?id=" + this.selectedGroupId),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.receivedMessage = data.data;
        }
      })
    },
    initMembers(){
      this.$http({
        url: this.$http.adornUrl("/communication/getMembers?id=" + this.selectedGroupId),
        method: "get",
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.members = data.data;
        }
      })
    },
    createChartInstance(dom) {
      this.chartInstance = this.$echarts.init(dom)
      const chartOption = {
        title: {},
        animation: true,
        series: [
          {
            type: "graph",
            layout: "force",
            symbolSize: 30,
            roam: true,
            label: {
              show: true,
            },
            edgeSymbol: ["circle"],
            edgeSymbolSize: [4, 10],
            edgeLabel: {
              fontSize: 12,
            },
            emphasis: {
              focus: "adjacency",
              lineStyle: {
                width: 10,
              },
            },
            force: {
              repulsion: 1000,
              edgeLength: [10, 50],
            },
            draggable: true,
            cursor: "pointer",
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0.2,
            },
          },
        ],
      };
      this.chartInstance.setOption(chartOption)
    },
    //通过窗体高宽计算容器高宽，渲染echart图表的div的宽高度以达到自适应目的
    resizeDom() {
      const boxHeight =
          document.getElementsByClassName("echarts-box")[0].clientHeight;
      var Echart = document.getElementById("radarEchart");
      Echart.style.height = boxHeight - 65 + "px";
      this.$echarts.init(document.getElementById("radarEchart")).resize();
    },
  }
}

</script>
<style scoped>

.echarts-box {
  height: 100%;
  width: 100%;
}

.radar {
  height: 100%;
}
</style>
