<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="监控项" name="first">
        <template v-if="activeName === 'first'">
          <FirstMonitor v-if="loading" :formData="formData" :chartList="firstChartList" @chartFnEvent="chartFnEvent"></FirstMonitor>
        </template>
      </el-tab-pane>
      <el-tab-pane label="自动发现项" name="second">
        <template v-if="activeName === 'second'">
          <SecondAutoFind v-if="loading" :secondChartList="secondChartList" :activeNames="activeNames" @collapseChangeData="collapseChangeData" @chartFnEvent="chartFnEvent"></SecondAutoFind>
        </template>
      </el-tab-pane>
    </el-tabs>
    <div style="float: right;margin-top: 20px;">
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script>
  import FirstMonitor from "./firstMonitor";
  import SecondAutoFind from "./secondAutoFind";
  import {switchMonitorData, switchCpuData, switchMemData,switchPowerData, postInterFaceName, switchNetDetails,switchNetDiscards,switchNeTotal,switchNetErrDiscard, switchNetSpeed} from "@/api/disRevenue/resource"
  export default {
    name: "MonitorChart",
    components: {FirstMonitor, SecondAutoFind},
    data() {
      return {
        loading: false,
        currTimeList: {},
        defaultTimes: [],
        activeName: 'second',
        paramsData: {},
        // 第一栏
        firstChartTrans: {},
        formFirst: {
          sysName: '系统名称', sysLocation: '系统位置', sysObjectID: '系统Object ID', hwStackSystemMac: '系统MAC地址',
          sysUpTime: '系统运行时间', entPhysicalName: '设备名称', sysContact: '系统联系信息', entPhysicalSoftwareRev: '设备软件版本', sysDescr: '系统描述'
        },
        formData: {},
        firstChartList: [],
        resultData: [
          {
            title: '设备CPU使用率(%)',
            dateShowType: 'datetimerange',
            dateDataTrans: {transList: true},
            dataVal: {
              titleVal: {textAlign: 'left', left: '1%'},
              yAxisName: ' ',
              gridTop: '35%',
              legend: {top: '15%', left: '10%'},
              lineXData: [],
              dataList: [{
                name: '设备CPU使用率',
                data: [],
              }]
            }
          },{
            title: '设备内存使用率(%)',
            dateShowType: 'datetimerange',
            dateDataTrans: {transList: true},
            dataVal: {
              titleVal: {textAlign: 'left', left: '1%'},
              yAxisName: ' ',
              gridTop: '35%',
              legend: {top: '15%', left: '10%'},
              lineXData: [],
              dataList: [{
                name: '设备内存使用率',
                data: [],
              }]
            }
          },{
            title: '功率',
            dateShowType: 'datetimerange',
            dateDataTrans: {transList: true},
            dataVal: {
              titleVal: {textAlign: 'left', left: '1%'},
              yAxisName: ' ',
              gridTop: '35%',
              legend: {top: '15%', left: '10%'},
              lineXData: [],
              dataList: [{
                name: '系统平均功率(mW)',
                data: [],
              },{
                name: '系统实时功率(mW)',
                data: []
              }]
            }
          }
        ],
        //  第二栏
        activeNames: [],
        secondChartList: {},
        eventDataMap: {},
        echartData: {
          title: 'GE1/0/1的丢包数',
          dateShowType: 'datetimerange',
          dateDataTrans: {transList: true},
          dataVal: {
            titleVal: {textAlign: 'left', left: '1%'},
            yAxisName: ' ',
            gridTop: '35%',
            legend: {top: '15%', left: '10%'},
            lineXData: ['2025-9-1', '2025-9-2', '2025-9-3', '2025-9-4', '2025-9-5', '2025-9-6', '2025-9-7'],
            dataList: [{
              name: '入站丢包',
              data: [120, 132, 101, 134, 90, 230, 210],
            },{
              name: '出站丢包',
              data: [220, 182, 191, 234, 290, 330, 310]
            }]
          }
        },
        linuxSystem: {
          net: {
            title: '网络端口GE1/0/1',
            type: 'net',
            formList: {name: '端口名称', type: '端口类型', status: '端口状态', mbps: '端口适配速率(Mbps)'},
            formModel: {name: 'GE1/0/1', type: 'ETHNET', status: 'up', mbps: '1000'},
            echartFors: [
              {title: '的丢包数', oneName: '入站丢包', twoName: '出站丢包'},
              {title: '的Bites总数', oneName: '端口发送Bites总数', twoName: '端口接收Bites总数'},
              {title: '的错误包数量', oneName: '错误的入站数据包数量', twoName: '错误的出战数据包数量'},
              {title: '的网络速率', oneName: '端口实时接收速率', twoName: '端口实时发送速率'},
            ],
            echartList: []
          },
          light: {
            title: '光模块sabc',
            type: 'light',
            formList: {name: '光模块端口名称'},
            formModel: {name: 'sabc'},
            echartFors: [
              {title: 'sabc的光衰阈值(dBm)', oneName: '光模块发送光衰阈值', twoName: '光模块接收光衰阈值'},
              {title: 'sabc的功率(dBm)', oneName: '光模块接收功率', twoName: '光模块发送功率'}
            ],
            echartList: []
          },
          mpu: {
            title: 'MPU1',
            type: 'mpu',
            formList: {name: 'MPU名称', system: 'MPU的操作系统'},
            formModel: {name: 'MPU1', system: 'xxxx'},
            echartFors: [
              {title: 'MPU1的CPU使用率(%)', oneName: 'CPU利用率'},
              {title: 'MPU1的内存使用率(%)', oneName: '内存利用率'},
              {title: 'MPU1的温度(°C)', oneName: '温度'},
            ],
            echartList: []
          },
          pw: {
            title: '电源PW1',
            type: 'pw',
            formList: {name: '电源名称', status: '电源状态'},
            formModel: {name: 'PW1', status: '正在供电'},
            echartFors: [
              {title: '电源电流(mA)', oneName: '电源电流'},
              {title: '电源电压(mV)', oneName: '电源电压'}
            ],
            echartList: []
          },
          fan: {
            title: '风扇FAN1',
            type: 'fan',
            formList: {name: '风扇名称', status: '风扇状态'},
            formModel: {name: 'FAN1', status: 'xxx'},
            echartFors: [],
            echartList: []
          }
        },
      }
    },
    created() {
      let startData = '';
      let endData = '';
      const year = new Date().getFullYear();
      const month = String(new Date().getMonth() + 1).padStart(2, '0'); // 0=1月，11=12月
      const day = String(new Date().getDate()).padStart(2, '0');     // 当前日（如8）
      const prevDay = String(new Date().getDate() - 1).padStart(2, '0');
      startData = `${year}-${month}-${prevDay} 00:00:00`;
      endData = `${year}-${month}-${day} 00:00:00`;
      this.currTimeList = {startTime: startData, endTime: endData};
      this.defaultTimes = [startData, endData];
      this.paramsData = this.$route && this.$route.query;
      this.handleClick();
    },
    methods: {
      async handleClick(tab, event) {
        this.loading = false;
        if (this.activeName === 'first') {
          await Promise.all([
            this.getMonitorData(),
            this.getCpuData(),
            this.getMemData(),
            this.getPowerData()
          ]);
          this.loading = true;
        } else {
          await this.fnInterFaceNameList();
          this.loading = true;
        }
      },
      getMonitorData() {
        this.formData = {formFirst: this.formFirst};
        switchMonitorData({clientId: this.paramsData.clientId}).then(res => {
          if (res && res.data) {
            this.formData['formValue'] = res.data;
          }
        });
      },
      getCpuData(val) {
        let cpuData = JSON.parse(JSON.stringify(this.resultData[0]));
        switchCpuData(Object.assign({},{clientId: this.paramsData.clientId}, val)).then(res => {
          cpuData['fnEvent'] = 'getCpuData';
          if (res && res.data) {
            cpuData.dataVal.lineXData = res.data && res.data['xData'] && res.data['xData'].length > 0 ? res.data['xData'] :
              this.firstChartTrans && this.firstChartTrans['timeList'] && this.firstChartTrans['timeList'].length > 0 ? this.firstChartTrans['timeList'] : [];
            cpuData.dataVal.dataList[0].data = res.data && res.data['yData'] && res.data['yData']['switchCpuUse'] && res.data['yData']['switchCpuUse'].length > 0 ? res.data['yData']['switchCpuUse'] : [];
          }
          // this.firstChartList[0] = cpuData;
          this.$set(this.firstChartList, 0, cpuData);
        }).catch(() => {
          this.firstChartList[0] = cpuData;
        });
      },
      getMemData(val) {
        let memData = JSON.parse(JSON.stringify(this.resultData[1]));
        switchMemData(Object.assign({},{clientId: this.paramsData.clientId}, val)).then(res => {
          memData['fnEvent'] = 'getMemData';
          if (res && res.data) {
            memData.dataVal.lineXData = res.data && res.data['xData'] && res.data['xData'].length > 0 ? res.data['xData'] :
              this.firstChartTrans && this.firstChartTrans['timeList'] && this.firstChartTrans['timeList'].length > 0 ? this.firstChartTrans['timeList'] : [];
            memData.dataVal.dataList[0].data = res.data && res.data['yData'] && res.data['yData']['switchMemUse'] && res.data['yData']['switchMemUse'].length > 0 ? res.data['yData']['switchMemUse'] : [];
          }
          // this.firstChartList[1] = memData;
          this.$set(this.firstChartList, 1, memData);
        }).catch(() => {
          this.firstChartList[1] = memData;
        });
      },
      getPowerData(val) {
        let powerData = JSON.parse(JSON.stringify(this.resultData[2]));
        switchPowerData(Object.assign({},{clientId: this.paramsData.clientId}, val)).then(res => {
          powerData['fnEvent'] = 'getPowerData';
          if (res && res.data) {
            powerData.dataVal.lineXData = res.data && res.data['xData'] && res.data['xData'].length > 0 ? res.data['xData'] :
              this.firstChartTrans && this.firstChartTrans['timeList'] && this.firstChartTrans['timeList'].length > 0 ? this.firstChartTrans['timeList'] : [];
            powerData.dataVal.dataList[0].data = res.data && res.data['yData'] && res.data['yData']['switchAvgPower'] && res.data['yData']['switchAvgPower'].length > 0 ? res.data['yData']['switchAvgPower'] : [];
            powerData.dataVal.dataList[1].data = res.data && res.data['yData'] && res.data['yData']['switchcurrentPower'] && res.data['yData']['switchcurrentPower'].length > 0 ? res.data['yData']['switchcurrentPower'] : [];
          }
          // this.firstChartList[2] = powerData;
          this.$set(this.firstChartList, 2, powerData);
        }).catch(() => {
          this.firstChartList[2] = powerData;
        });
      },
      // two
      // 接口名称
      fnInterFaceNameList(val) {
        this.activeNames = [];
        postInterFaceName({clientId: this.paramsData.clientId}).then(res => {
          let tabNameList = {};
          res && res.forEach(async(item,index) => {
            let oneData = JSON.parse(JSON.stringify(this.linuxSystem['net']));
            oneData.title = item && item.interfaceName;
            tabNameList[item.interfaceName] = oneData;
          });
          this.secondChartList = {...tabNameList};
          this.activeNames = [Object.keys(tabNameList)[0]];
          this.getNetDetailsData(this.currTimeList, Object.keys(tabNameList)[0]);
          // this.fnSwitchNetNames(); // 第二模块名称
          // setTimeout(() => {
          //   this.fnDiskNames(); // 第三模块名称
          //   setTimeout(() => {
          //     this.fnDockerNames(); // 第四模块名称
          //   },500);
          // },500);
        }).catch((error) => {

        });
      },
      // 基本信息
      getNetDetailsData(times, titleName) {
        this.$modal.loading();
        this.eventDataMap[titleName] = true;
        switchNetDetails({clientId: this.paramsData.clientId, name: titleName}).then(async res => {
          this.secondChartList[titleName].formModel = res && res.data || [];
          if (await this.getNetDiscards(times ,titleName)) {
            if (await this.getNetTotal(times, titleName)) {
              if (await this.getNetErrDisc(times, titleName)) {
                this.getNetSpeed(times, titleName);
              }
            }
          }
        }).catch(() => {
          this.getSpaceEcharts(times ,titleName);
          setTimeout(() => {
            this.getNetTotal(times, titleName);
            setTimeout(() => {
              this.getNetErrDisc(times, titleName);
              setTimeout(() => {
                this.getNetSpeed(times, titleName);
              },500);
            },500);
          },500);
        });
      },
      // 丢包
      getNetDiscards(times,titleName) {
        let mountCollect = JSON.parse(JSON.stringify(this.secondChartList[titleName]));
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        let content = JSON.parse(JSON.stringify(this.linuxSystem['net']));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetDiscards';
        return switchNetDiscards(Object.assign({}, {name : titleName,clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = titleName + content.echartFors[0].title;
            netEcharts.dataVal.lineXData = res.data && res.data.xData.length > 0 ? res.data.xData : this.firstChartTrans && this.firstChartTrans['timeList'] || [];
            // 入
            netEcharts.dataVal.dataList[0] = {
              name: content.echartFors[0].oneName,
              data: res.data && res.data.yData['netInDiscardsData'] || []
            };
            // 出
            netEcharts.dataVal.dataList[1] = {
              name: content.echartFors[0].twoName,
              data: res.data && res.data.yData['netOutDiscardsData'] || []
            };
            mountCollect['echartList'][0] = netEcharts;
            this.$set(this.secondChartList, titleName, mountCollect);
            return true;
          }
        }).catch(() => {
          return true;
        });
      },
      // 总数
      getNetTotal(times,titleName) {
        let mountCollect = JSON.parse(JSON.stringify(this.secondChartList[titleName]));
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        let content = JSON.parse(JSON.stringify(this.linuxSystem['net']));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetTotal';
        return switchNeTotal(Object.assign({}, {name : titleName, clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = titleName + content.echartFors[1].title;
            netEcharts.dataVal.lineXData = res.data && res.data.xData.length > 0 ? res.data.xData : this.firstChartTrans && this.firstChartTrans['timeList'] || [];
            // 入
            netEcharts.dataVal.dataList[0] = {
              name: content.echartFors[1].oneName,
              data: res.data && res.data.yData['netInTotalData'] || []
            };
            // 出
            netEcharts.dataVal.dataList[1] = {
              name: content.echartFors[1].twoName,
              data: res.data && res.data.yData['netOutTotalData'] || []
            };
            mountCollect['echartList'][1] = netEcharts;
            this.$set(this.secondChartList, titleName, mountCollect);
            return true;
          }
        }).catch(() => {
          return true;
        });
      },
      // 错误丢包
      getNetErrDisc(times, titleName) {
        let mountCollect = JSON.parse(JSON.stringify(this.secondChartList[titleName]));
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        let content = JSON.parse(JSON.stringify(this.linuxSystem['net']));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetErrDisc';
        return switchNetErrDiscard(Object.assign({}, {name : titleName, clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = titleName + content.echartFors[2].title;
            netEcharts.dataVal.lineXData = res.data && res.data.xData.length > 0 ? res.data.xData : this.firstChartTrans && this.firstChartTrans['timeList'] || [];
            netEcharts.dataVal.dataList[0] = {
              name: content.echartFors[2].oneName,
              data: res.data && res.data.yData['netInErrDiscardsData'] || []
            };
            netEcharts.dataVal.dataList[1] = {
              name: content.echartFors[2].twoName,
              data: res.data && res.data.yData['netOutErrDiscardsData'] || []
            };
            mountCollect['echartList'][2] = netEcharts;
            this.$set(this.secondChartList, titleName, mountCollect);
            return true;
          }
        }).catch(() => {
          return true;
        });
      },
      // 实时流量
      getNetSpeed(times, titleName) {
        let mountCollect = JSON.parse(JSON.stringify(this.secondChartList[titleName]));
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        let content = JSON.parse(JSON.stringify(this.linuxSystem['net']));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetSpeed';
        switchNetSpeed(Object.assign({}, {name : titleName, clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = titleName + content.echartFors[3].title;
            netEcharts.dataVal.lineXData = res.data && res.data.xData.length > 0 ? res.data.xData : this.firstChartTrans && this.firstChartTrans['timeList'] || [];
            netEcharts.dataVal.dataList[0] = {
              name: content.echartFors[3].oneName,
              data: res.data && res.data.yData['netInSpeedData'] || []
            };
            netEcharts.dataVal.dataList[1] = {
              name: content.echartFors[3].twoName,
              data: res.data && res.data.yData['netOutSpeedData'] || []
            };
            mountCollect['echartList'][3] = netEcharts;
            this.$set(this.secondChartList, titleName, mountCollect);
            this.$modal.closeLoading();
          }
        }).catch(() => {
          this.$modal.closeLoading();
        });
      },

      collapseChangeData(valList) {
        valList && valList.forEach(item => {
          if (!this.eventDataMap[item]) {
            this.$modal.loading();
            if (this.secondChartList[item].type === 'net') {
              this.getNetDetailsData(this.currTimeList, item);
            }
          }
        });
      },
      chartFnEvent(valData, fnName, tabName) {
        this.firstChartTrans = valData;
        // 检查函数是否存在，避免报错
        if (typeof this[fnName] === 'function') {
          this.defaultTimes = valData.timeArr;
          // 调用实际函数，并传递参数（如选中的值、当前项）
          this[fnName]({startTime: valData.timeArr[0], endTime: valData.timeArr[1]}, tabName);
        } else {
          console.warn(`函数 ${fnName} 未定义`);
        }
      },
      goBack() {
        this.$router.push("/resource/switchRegister");
      }
    }
  }
</script>

<style scoped>

</style>
