<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" :defaultTimes="defaultTimes" :matchNum="matchNum" :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: {
          sysDescr: '系统描述', sysLocation: '系统位置', sysObjectID: '系统Object ID', hwStackSystemMac: '系统MAC地址',
          sysUpTime: '系统运行时间', entPhysicalName: '设备名称', sysContact: '系统联系信息', entPhysicalSoftwareRev: '设备软件版本', sysName: '系统名称'
        },
        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: [],
        matchNum: {num: ''},
        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',
            formList: {name: '端口名称', type: '端口类型', status: '端口状态', mbps: '端口适配速率(Mbps)'},
            formModel: {name: 'GE1/0/1', type: 'ETHNET', status: 'up', mbps: '1000'},
            echartFors: [
              {title: 'GE1/0/1的丢包数', oneName: '入站丢包', twoName: '出站丢包'},
              {title: 'GE1/0/1的Bites总数', oneName: '端口发送Bites总数', twoName: '端口接收Bites总数'},
              {title: 'GE1/0/1的错误包数量', oneName: '错误的入站数据包数量', twoName: '错误的出战数据包数量'},
              {title: 'GE1/0/1的网络速率(bites/sec)', oneName: '端口实时接收速率(bites/sec)', twoName: '端口实时发送速率(bites/sec)'},
            ],
            echartList: []
          },
          light: {
            title: '光模块sabc',
            formList: {name: '光模块端口名称'},
            formModel: {name: 'sabc'},
            echartFors: [
              {title: 'sabc的光衰阈值(dBm)', oneName: '光模块发送光衰阈值', twoName: '光模块接收光衰阈值'},
              {title: 'sabc的功率(dBm)', oneName: '光模块接收功率', twoName: '光模块发送功率'}
            ],
            echartList: []
          },
          mpu: {
            title: 'MPU1',
            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',
            formList: {name: '电源名称', status: '电源状态'},
            formModel: {name: 'PW1', status: '正在供电'},
            echartFors: [
              {title: '电源电流(mA)', oneName: '电源电流'},
              {title: '电源电压(mV)', oneName: '电源电压'}
            ],
            echartList: []
          },
          fan: {
            title: '风扇FAN1',
            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
      // 接口名称
      async fnInterFaceNameList(val) {
        this.activeNames = [];
        try {
          const res = await postInterFaceName({clientId: this.paramsData.clientId});
            // .then(res => {
            res && res.forEach(async(item,index) => {
              let oneData = JSON.parse(JSON.stringify(this.linuxSystem['net']));
              oneData.title = item && item.interfaceName;
              this.secondChartList[item.interfaceName] = oneData;
              if (index === 0) {
                this.$modal.loading();
                await Promise.all([
                  this.getNetDiscards(this.currTimeList, item),
                  this.getNetTotal(this.currTimeList, item),
                  this.getNetErrDisc(this.currTimeList, item),
                  this.getNetSpeed(this.currTimeList, item)
                ]);
                setTimeout(() => {
                  if (!this.activeNames.includes(item.interfaceName)) this.activeNames.push(item.interfaceName);
                  this.$modal.closeLoading();
                },2000);
              }
            });
          // });
        } catch (error) {
          this.$modal.closeLoading();
          console.error('获取接口名称列表失败：', error);
          // 可添加错误提示，如this.$message.error('数据加载失败')
        }
      },
      // 基本信息
      getNetData() {
        switchNetDetails({clientId: this.paramsData.clientId}).then(res => {
          if (res && res.data) {
            this.formData['formValue'] = res.data;
          }
        });
      },
      // 丢包
      getNetDiscards(times,val) {
        const interfaceName = val.interfaceName;
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        if (netEcharts && netEcharts.dateDataTrans) {
          netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        }
        netEcharts.fnEvent = 'getNetDiscards';
        switchNetDiscards(Object.assign({}, {name : interfaceName,clientId: this.paramsData.clientId}, times)).then(res => {
          this.$set(this.secondChartList[interfaceName].echartList, 0, []);
          if (res && res.data) {
            this.eventDataMap['interfaceName'] = false;
            netEcharts.title = `${interfaceName}的丢包数`;
            console.log('');
            netEcharts.dataVal.lineXData = res.data?.xData.length > 0 ? res.data.xData : this.firstChartTrans?.timeList || [];
            // 入
            netEcharts.dataVal.dataList[0] = {
              name: this.secondChartList[interfaceName].echartFors[0].oneName,
              data: res.data.yData?.netInDiscardsData || []
            };
            // 出
            netEcharts.dataVal.dataList[1] = {
              name: this.secondChartList[interfaceName].echartFors[0].twoName,
              data: res.data.yData?.netOutDiscardsData || []
            };
            this.$set(this.secondChartList[interfaceName].echartList, 0, netEcharts);
            this.$set(this.eventDataMap, interfaceName, true);
            if (this.firstChartTrans?.timeList) {
              this.matchNum['interfaceName'] = val.interfaceName;
              this.$set(this.matchNum, 'num', Math.floor(Math.random() * 9000));
            }
          }
        });
      },
      // 总数
      getNetTotal(times,val) {
        const interfaceName = val.interfaceName;
        // let netData = JSON.parse(JSON.stringify(this.secondChartList[interfaceName]));
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetTotal';
        switchNeTotal(Object.assign({}, {name : interfaceName,clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = `${interfaceName}的Bites总数`;
            netEcharts.dataVal.lineXData = res.data && res.data.xData || [];
            // 入
            netEcharts.dataVal.dataList[0] = {
              name: this.secondChartList[interfaceName].echartFors[1].oneName,
              data: res.data.yData?.netInTotalData || []
            };
            // 出
            netEcharts.dataVal.dataList[1] = {
              name: this.secondChartList[interfaceName].echartFors[1].twoName,
              data: res.data.yData?.netOutTotalData || []
            };
            this.$set(this.secondChartList[interfaceName].echartList, 1, netEcharts);
          }
        });
      },
      // 错误丢包
      getNetErrDisc(times, val) {
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetErrDisc';
        switchNetErrDiscard(Object.assign({}, {name : val.interfaceName,clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = `${val.interfaceName}的错误包数量`;
            netEcharts.dataVal.lineXData = res.data && res.data.xData || [];
            netEcharts.dataVal.dataList[0].name = this.secondChartList[val.interfaceName].echartFors[2].oneName;
            netEcharts.dataVal.dataList[0].data = res.data && res.data.yData?.netInErrDiscardsData || [];
            netEcharts.dataVal.dataList[1].name = this.secondChartList[val.interfaceName].echartFors[2].twoName;
            netEcharts.dataVal.dataList[1].data = res.data && res.data.yData?.netOutErrDiscardsData || [];
            this.$set(this.secondChartList[val.interfaceName].echartList, 2, netEcharts);
          }
        });
      },
      // 实时流量
      getNetSpeed(times, val) {
        let netEcharts = JSON.parse(JSON.stringify(this.echartData));
        netEcharts.dateDataTrans['dateRange'] = this.defaultTimes;
        netEcharts.fnEvent = 'getNetSpeed';
        switchNetSpeed(Object.assign({}, {name : val.interfaceName,clientId: this.paramsData.clientId}, times)).then(res => {
          if (res && res.data) {
            netEcharts.title = `${val.interfaceName}的网络速率(bites/sec)`;
            netEcharts.dataVal.lineXData = res.data && res.data.xData || [];
            netEcharts.dataVal.dataList[0].name = this.secondChartList[val.interfaceName].echartFors[3].oneName;
            netEcharts.dataVal.dataList[0].data = res.data && res.data.yData?.netInSpeedData || [];
            netEcharts.dataVal.dataList[1].name = this.secondChartList[val.interfaceName].echartFors[3].twoName;
            netEcharts.dataVal.dataList[1].data = res.data && res.data.yData?.netOutSpeedData || [];
            this.$set(this.secondChartList[val.interfaceName].echartList, 3, netEcharts);
        }
        });
      },
      collapseChangeData(valList) {
        valList && valList.forEach(item => {
          if (!this.eventDataMap[item]) {
            this.$modal.loading();
            this.getNetDiscards(this.currTimeList, {interfaceName: item});
            this.getNetTotal(this.currTimeList, {interfaceName: item});
            this.getNetErrDisc(this.currTimeList, {interfaceName: item});
            this.getNetSpeed(this.currTimeList, {interfaceName: item});
            setTimeout(() => {
              if (!this.activeNames.includes(item)) this.activeNames.push(item);
              this.$modal.closeLoading();
            },2500);
          }
        });
      },
      chartFnEvent(valData, fnName, tabName) {
        console.log('ccccc===',fnName,'vvv==', typeof this[fnName] === 'function');
        this.firstChartTrans = valData;
        // 检查函数是否存在，避免报错
        if (typeof this[fnName] === 'function') {
          // 调用实际函数，并传递参数（如选中的值、当前项）
          this[fnName]({startTime: valData.timeArr[0], endTime: valData.timeArr[1]}, {interfaceName: tabName});
        } else {
          console.warn(`函数 ${fnName} 未定义`);
        }
      },
      goBack() {
        this.$router.push("/resource/switchRegister");
      }
    }
  }
</script>

<style scoped>

</style>
