<template>
  <div style="height: calc(100vh)!important">
    <div style="height: 90px;">
      <el-form ref="noticeRef" :model="form" label-width="100px">
        <el-form-item :label="this.resourceType === 1 ? 'ClientID' : '交换机名称'" prop="clientId">
          <!--  allow-create default-first-option： 搜索下拉框中没有的数据并展示查询 -->
          <el-select ref="select" v-model="form.clientId" multiple filterable :placeholder="this.resourceType === 1 ? '请选择ClientID' : '请选择交换机名称'" popper-class="my-custom-select-dropdown" @change="handleChange">
            <el-option
              v-for="item in selectChangeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template v-for="(item,index) of switchData">
        <el-switch v-model="item.checkType" :activeText="item.label" class="mr20" @change="(val) => handleElSwitch(val, item, index)" />
        <el-date-picker
          v-model="timeList[item.value]"
          :style="{width: '300px!important', marginRight: '10px'}"
          :type="item.value === '1' ? 'daterange' : 'monthrange'"
          :start-placeholder="item.value === '2' ? '开始日期' : '开始时间'"
          :end-placeholder="item.value === '2' ? '结束日期' : '结束时间'"
          range-separator="至"
          :format="item.value === '2' ? 'yyyy-MM' : 'yyyy-MM-dd'"
          :value-format="item.value === '2' ? 'yyyy-MM' : 'yyyy-MM-dd'"
          @change="(val) => dateChange(val, item.value)"/>
      </template>
    </div>
    <div style="height: calc(100vh - 160px);overflow: scroll;">
<!--      <template v-for="(item,index) of echartListData">-->
<!--        <template v-if="item && item.dateShowType === 'day'">-->
<!--          <EchartsLine v-show="switchData[item.indexVal].checkType" :chartData="(valData) => chartDataEvent(valData, item.fnEvent)" :dateShowType="item.dateShowType"-->
<!--                       :lineData="item.resultData" :title="item.titleList + switchData[item.indexVal].label" class="w100 h40 mt20 mb20" style="border: 1.5px solid #878787;"></EchartsLine>-->
<!--        </template>-->
<!--        <template v-if="item && item.dateShowType === 'month'">-->
<!--          <EchartsBar v-show="switchData[item.indexVal].checkType" :chartData="(valData) => chartDataEvent(valData, item.fnEvent)" :dateShowType="item.dateShowType"-->
<!--                      :barData="item.resultData" :title="item.titleList + switchData[item.indexVal].label" class="w100 h40 mt20 mb20" style="border: 1.5px solid #878787;"></EchartsBar>-->
<!--        </template>-->
<!--      </template>-->
      <template v-for="(item,index) of echartListData['day']">
        <EchartsLine v-show="switchData[item.indexVal].checkType" :lineData="item" :title="item.title" class="w100 mt20 mb20" style="border: 1.5px solid #878787;height:60%;min-height:350px;" :chartData="(valData, unit) => chartDataEvent(valData, unit, 'day')"></EchartsLine>
      </template>
      <template v-for="(item,index) of echartListData['month']">
        <EchartsLine v-show="switchData[item.indexVal].checkType" :lineData="item" :title="item.title " class="w100 mt20 mb20" style="border: 1.5px solid #878787;height:60%;min-height:350px;" :chartData="(valData, unit) => chartDataEvent(valData, unit, 'month')"></EchartsLine>
      </template>
    </div>
  </div>
</template>

<script setup>
  import Form from '@/components/form/index.vue';
  import EchartsLine from "@/components/echartsList/line.vue";
  import EchartsBar from "@/components/echartsList/bar.vue";
  import {graPackage, graMonthly, graEffectiveMonthly, graEffectiveDaily, graEffectiveAvgMonthly, graDaily, graAvgMonthly, serverGraphDaily, serverGraphMonth, switchGraphDaily, switchGraphMonth} from "@/api/disRevenue/earnManage"
  import {listAllSwitchName, getRegistList} from "@/api/disRevenue/resource";
  export default {
    name: 'AnalysisChart',
    components: {Form, EchartsLine, EchartsBar},
    dicts: ['eps_bandwidth_type'],
    props: {
      activeName: {
        type: String,
        default: "1000"
      },
      clientId: {
        type: Array,
        default: []
      }
    },
    watch: {
      activeName: {
        handler(val) {
          this.initData();
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        timeList: {'1': [], '2': []},
        paramsData: {},
        form: {},
        storageKey: '',
        selectChangeList: [],
        switchData: [],
        echartListData: {},
        typeObj: {},
        paramsVal: {},
        resourceType: '',
        echartData: [
          {
            title: 'tux',
            titleSubtext: {subtext: '', bottom: '17%', x: '50%', textAlign: 'center', subtextStyle: {fontWeight: 'bold', fontSize: 14}},
            yAxisName: ' ',
            content: {},
            legend: {orient: 'vertical',bottom: '0%', formatter: true},
            gridTop: '60px',
            gridBotm: '25%',
            hiddenTime: true,
            lineXData: [],
            unitSelList: [{label: 'Kb', value: 'Kb'},{label: 'Mb', value: 'Mb'}, {label: 'Gb', value: 'Gb'}],
            dataList: [
              {name: '发送流量值', data: []},
              {name: '金山API记录的发送流量值', data: []},
              {name: '95带宽值/日', areaStyleNone: true, symbol: 'none', data: []},
            ]
          },
          {
            title: 'tux',
            titleSubtext: {subtext: '', bottom: '17%', x: '50%', textAlign: 'center', subtextStyle: {fontWeight: 'bold', fontSize: 14}},
            yAxisName: ' ',
            content: {},
            legend: {orient: 'vertical',bottom: '0%', formatter: true},
            gridTop: '60px',
            gridBotm: '25%',
            hiddenTime: true,
            lineXData: [],
            unitSelList: [{label: 'Kb', value: 'Kb'},{label: 'Mb', value: 'Mb'}, {label: 'Gb', value: 'Gb'}],
            dataList: [
              {name: '入方向流量', data: []},
              {name: '出方向流量', data: []},
              {name: '95带宽值/日', areaStyleNone: true, symbol: 'none', data: []},
            ]
          }
        ],
        lineDataParams: {chart: {}},
        observer: '',
      }
    },
    created() {},
    mounted() {
      const tagContainer = this.$refs.select.$el.querySelector('.el-select__tags > span');
      // 确保容器有相对定位，方便计数标签定位
      tagContainer.style.position = 'relative';
      this.observer = new MutationObserver(() => {
        this.calculateVisibleTags(tagContainer);
      });
      this.observer.observe(tagContainer, { childList: true });
      // 初始计算一次
      this.$nextTick(() => {
        this.calculateVisibleTags(tagContainer);
      });
    },
    beforeDestroy() {
      if (this.observer) {
        this.observer.disconnect();
      }
    },
    methods: {
      calculateVisibleTags(tagContainer) {
        // 断开观察器避免循环
        this.observer.disconnect();
        this.$nextTick(() => {
          const container = tagContainer.parentNode;
          const allTags = Array.from(tagContainer.children).filter(tag =>
            !tag.classList.contains('count-node')
          );
          // 更精确的容器宽度计算（减去内边距和边框）
          const containerStyle = window.getComputedStyle(container);
          const paddingLeft = parseFloat(containerStyle.paddingLeft) || 0;
          const paddingRight = parseFloat(containerStyle.paddingRight) || 0;
          const borderLeft = parseFloat(containerStyle.borderLeftWidth) || 0;
          const borderRight = parseFloat(containerStyle.borderRightWidth) || 0;
          const availableWidth = container.offsetWidth - paddingLeft - paddingRight - borderLeft - borderRight - 10; // 预留10px余量
          let totalWidth = 0;
          let visibleCount = 0;
          let lastVisibleIndex = -1;
          // 第一轮：计算可以显示多少个标签
          for (let i = 0; i < allTags.length; i++) {
            const tag = allTags[i];
            tag.style.display = 'inline-block';
            // 更精确的标签宽度计算（包括margin、border、padding）
            const tagStyle = window.getComputedStyle(tag);
            const tagWidth = tag.offsetWidth +
              parseFloat(tagStyle.marginLeft || 0) +
              parseFloat(tagStyle.marginRight || 0);
            if (totalWidth + tagWidth <= availableWidth) {
              totalWidth += tagWidth;
              lastVisibleIndex = i;
              visibleCount++;
            } else {
              break;
            }
          }
          // 第二轮：应用显示/隐藏
          for (let i = 0; i < allTags.length; i++) {
            if (i <= lastVisibleIndex) {
              allTags[i].style.display = 'inline-block';
              allTags[i].style.visibility = 'visible';
            } else {
              allTags[i].style.display = 'none';
              allTags[i].style.visibility = 'hidden';
            }
          }
          // 处理计数标签
          this.updateCountTag(tagContainer, allTags.length, visibleCount, totalWidth, availableWidth);
          // 重新连接观察器
          this.$nextTick(() => {
            this.observer.observe(tagContainer, { childList: true });
          });
        });
      },

      updateCountTag(tagContainer, totalCount, visibleCount, usedWidth, availableWidth) {
        // 移除已有的计数标签
        let existingCountTag = tagContainer.querySelector('.count-node');
        if (existingCountTag) {
          existingCountTag.remove();
        }
        // 如果有隐藏的标签，添加计数标签
        if (totalCount > visibleCount && visibleCount > 0) {
          const countTag = document.createElement('span');
          countTag.className = 'count-node';
          countTag.textContent = `+${totalCount - visibleCount}`;
          // 先添加到DOM中获取实际宽度
          tagContainer.appendChild(countTag);
          const countTagWidth = countTag.offsetWidth + 10; // 加上margin
          // 检查是否有足够空间显示计数标签
          if (usedWidth + countTagWidth > availableWidth && visibleCount > 1) {
            // 空间不足，需要隐藏最后一个标签来为计数标签腾出空间
            const lastVisibleTag = tagContainer.children[visibleCount - 1];
            if (lastVisibleTag && !lastVisibleTag.classList.contains('count-node')) {
              lastVisibleTag.style.display = 'none';
              lastVisibleTag.style.visibility = 'hidden';
              visibleCount--;
            }
          }
          // 更新计数标签文本
          countTag.textContent = `+${totalCount - visibleCount}`;
        } else if (totalCount > visibleCount && visibleCount === 0) {
          // 没有可见标签，但需要显示计数标签的特殊情况
          const countTag = document.createElement('span');
          countTag.className = 'count-node';
          countTag.textContent = `+${totalCount}`;
          countTag.style.display = 'inline-block';
          tagContainer.appendChild(countTag);
        }
      },
      initData(){
        this.storageKey = this.$route.query && this.$route.query['storageKey'];
        if (this.storageKey) {
          this.paramsData = JSON.parse(localStorage.getItem(this.storageKey));
          this.resourceType = this.paramsData && this.paramsData.resourceType;
          if (this.paramsData && this.paramsData.dictList) {
             this.paramsData.dictList.forEach((item,index) => {
              if (item.value === '1' || item.value === '2') {
                this.typeObj[item.value] = {type: item.value, indexVal: index};
                this.switchData.push({
                  label: item.label,
                  value: item.value,
                  checkType: true
                });
              }
            });
          }
          if (this.paramsData && this.paramsData.list) {
            this.processData(this.paramsData.list);
          }
          if (this.paramsData && this.paramsData.resourceType) {
            this.fnNodeName(this.paramsData.resourceType);
          }
        }
      },
      fnNodeName(type){
        if (type === 1) {
          getRegistList({resourceType: type}).then(val => {
            this.selectChangeList = val && val.data.map(item => {
              return Object.assign({label: item.clientId, value: item.clientId});
            });
          });
        } else if (type === 2) {
          listAllSwitchName({}).then(val => {
            this.selectChangeList = val && val.data.map(item => {
              return Object.assign({label: item.switchName, value: item.clientId});
            });
          });
        }
      },
      // 切换开关
      async handleElSwitch(check,item, indexNum) {
        let timeStr = {};
        if (check && item.getType) {
          if (indexNum === 0) {
            timeStr = {startTime: this.timeList['1'][0], endTime: this.timeList['1'][1]};
            await Promise.all([
              this.$modal.loading(),
              this.graDailyList(timeStr)
            ]);
            this.$modal.closeLoading();
          } else if (indexNum === 1) {
            timeStr = {startTime: this.timeList['2'][0], endTime: this.timeList['2'][1]};
            await Promise.all([
              this.$modal.loading(),
              this.graMonthlyList(timeStr)
            ]);
            this.$modal.closeLoading();
          }
        }
      },
      // 下拉数据改变时触发
      async handleChange(eventVal) {
        this.paramsVal = {
          clientIds: eventVal.toString()
        };
        this.echartListData = {};
        this.paramsVal['calculationMode'] = this.activeName;
        let dayList = {startTime: this.timeList['1'][0], endTime: this.timeList['1'][1]};
        let monthList = {startTime: this.timeList['2'][0], endTime: this.timeList['2'][1]};
        await Promise.all([
          this.$modal.loading(),
          this.graDailyList(dayList),
          this.graMonthlyList(monthList),
        ]);
        this.$modal.closeLoading();
        // this.graPackageList(dayList);
        // this.graAvgMonthlyList(monthList);
        // this.graEffectiveDailyList(dayList);
        // this.graEffectiveMonthlyList(monthList);
        // this.graEffectiveAvgMonthlyList(dayList);
      },
      // 时间变化时
      dateChange(val, idNum){
        // console.log('id=====',idNum, 'val===',val);
        this.paramsVal['calculationMode'] = this.activeName;
        let timeStr = {startTime: val[0], endTime: val[1]};
        if (idNum === '1') {
          this.timeList['1'] = val;
          if (this.paramsVal && this.paramsVal.clientIds) {
            this.graDailyList(timeStr);
          }
        } else if (idNum === '2') {
          this.timeList['2'] = val;
          if (this.paramsVal && this.paramsVal.clientIds) {
            this.graMonthlyList(timeStr);
          }
        }
      },
      // 初始化
      async processData(list) {
        let nameArr = [];
        let nameListArr = [];
        let showNameList = [];
        list.forEach(item => {
          let name = this.resourceType === 1 ? item.clientId : item.clientId;
          if (!nameArr.includes(name)) {
            item.label = name;
            item.value = name;
            nameArr.push(name);
            nameListArr.push(item);
          }
        });
        if (this.clientId && this.clientId.length > 0) {
          this.form.clientId = this.clientId;
        } else {
          if (nameArr && nameArr.length > 0) {
            this.form.clientId = [];
            nameListArr && nameListArr.forEach(item => {
              this.form.clientId.push(item.label);
            });
            // if (nameListArr.length >=2) {
            //   this.form.clientId = [nameListArr[0].label, nameListArr[1].label];
            // } else {
            //   this.form.clientId = [nameListArr[0].label];
            // }
          }
        }
        showNameList = this.form.clientId;
        this.echartListData = {};
        let dayList = this.getBeforDay();
        let monthList = this.getLastMonths(2);
        this.timeList['1'] = [dayList.startTime, dayList.endTime];
        this.timeList['2'] = [monthList.startTime, monthList.endTime];
        if (showNameList && showNameList.length > 0) {
          this.paramsVal = {
            clientIds: showNameList.toString()
          };
          this.paramsVal['calculationMode'] = this.activeName;
          await Promise.all([
            this.$modal.loading(),
            this.graDailyList(dayList),
            this.graMonthlyList(monthList),
          ]);
          this.$modal.closeLoading();
          // this.graPackageList(dayList);
          // this.graAvgMonthlyList(monthList);
          // this.graEffectiveDailyList(dayList);
          // this.graEffectiveMonthlyList(monthList);
          // this.graEffectiveAvgMonthlyList(dayList);
        }
      },
      // 95带宽值Mbps/日---图表 serverGraphDaily, serverGraphMonth, switchGraphDaily, switchGraphMonth
      graDailyList(timeArr, unit){
        if (!this.switchData[0].checkType) {
          this.switchData[0]['getType'] = true;
          return;
        }
        this.switchData[0]['getType'] = false;
        let fnType = serverGraphDaily;
        if (this.resourceType === 2) {
          fnType = switchGraphDaily;
        }
        return fnType(Object.assign(unit || {} ,this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            let chartList = [];
            res.data.forEach((item, index) => {
              let newChartData = JSON.parse(JSON.stringify(this.echartData[this.resourceType === 2 ? 1 : 0]));
              let outContent = `最后一个值：${item && item.other && item.other.lastOutSpeedGb ? item.other.lastOutSpeedGb + 'G' : '0G'}   平均值：${item && item.other && item.other.avgOutSpeedGb ? item.other.avgOutSpeedGb + 'G' : '0G'}   最大值：${item && item.other && item.other.maxOutSpeedGb ? item.other.maxOutSpeedGb + 'G' : '0G'}`;
              let inContent = `最后一个值：${item && item.other && item.other.lastInSpeedGb ? item.other.lastInSpeedGb + 'G' : '0G'}   平均值：${item && item.other && item.other.avgInSpeedGb ? item.other.avgInSpeedGb + 'G' : '0G'}   最大值：${item && item.other && item.other.maxInSpeedGb ? item.other.maxInSpeedGb + 'G' : '0G'}`;
              let kdContent = `(${item && item['95value'] ? item['95value'] + 'mbit' : '0mbit'}    ${this.resourceType === 2 ? 'in+out' : 'out'})`;
              newChartData.title = item && item.name;
              newChartData.yAxisName = item && item.other && item.other.recommendedUnit ? '单位' + item.other.recommendedUnit : ' ';
              newChartData['unitModel'] = item && item.other && item.other.recommendedUnit || '';
              newChartData.titleSubtext.subtext = item && item.timeRange || ' ';
              newChartData.content[newChartData.dataList[0].name] = outContent;
              newChartData.content[newChartData.dataList[1].name] = inContent;
              newChartData.content[newChartData.dataList[2].name] = kdContent;
              newChartData.lineXData = item && item.xData || [];
              newChartData.dataList[0].data = item && item.yData && item.yData['netOutSpeedData'] || [];
              newChartData.dataList[1].data = item && item.yData && item.yData['netInSpeedData'] || [];
              newChartData.dataList[2].data = item && item.yData && item.yData['percentile95'] || [];
              let dataList = Object.assign({}, newChartData, this.typeObj[1]);
              chartList.push(dataList);
            });
            this.$set(this.echartListData, 'day', chartList);
          } else {
            this.$set(this.echartListData, 'day', []);
          }
        }).catch(() => {
          this.$modal.closeLoading();
        });
      },
      // 95带宽值Mbps/月---图表 serverGraphDaily, serverGraphMonth, switchGraphDaily, switchGraphMonth
      graMonthlyList(timeArr, unit){
        if (!this.switchData[1].checkType) {
          this.switchData[1]['getType'] = true;
          return;
        }
        this.switchData[1]['getType'] = false;
        let fnType = serverGraphMonth;
        if (this.resourceType === 2) {
          fnType = switchGraphMonth;
        }
        return fnType(Object.assign(unit || {}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            let chartList = [];
            res.data.forEach((item, index) => {
              let newChartData = JSON.parse(JSON.stringify(this.echartData[this.resourceType === 2 ? 1 : 0]));
              newChartData.dataList[newChartData.dataList.length - 1].name = '95带宽值/月';
              let outContent = `最后一个值：${item && item.other && item.other.lastOutSpeedGb ? item.other.lastOutSpeedGb + 'G' : '0G'}   平均值：${item && item.other && item.other.avgOutSpeedGb ? item.other.avgOutSpeedGb + 'G' : '0G'}   最大值：${item && item.other && item.other.maxOutSpeedGb ? item.other.maxOutSpeedGb + 'G' : '0G'}`;
              let inContent = `最后一个值：${item && item.other && item.other.lastInSpeedGb ? item.other.lastInSpeedGb + 'G' : '0G'}   平均值：${item && item.other && item.other.avgInSpeedGb ? item.other.avgInSpeedGb + 'G' : '0G'}   最大值：${item && item.other && item.other.maxInSpeedGb ? item.other.maxInSpeedGb + 'G' : '0G'}`;
              let kdContent = `(${item && item['95value'] ? item['95value'] + 'mbit' : '0mbit'}    ${this.resourceType === 2 ? 'in+out' : 'out'})`;
              newChartData.title = item && item.name;
              newChartData.yAxisName = item && item.other && item.other.recommendedUnit ? '单位' + item.other.recommendedUnit : ' ';
              newChartData['unitModel'] = item && item.other && item.other.recommendedUnit || '';
              newChartData.titleSubtext.subtext = item && item.timeRange || ' ';
              newChartData.content[newChartData.dataList[0].name] = outContent;
              newChartData.content[newChartData.dataList[1].name] = inContent;
              newChartData.content[newChartData.dataList[2].name] = kdContent;
              newChartData.lineXData = item && item.xData || [];
              newChartData.dataList[0].data = item && item.yData && item.yData['netOutSpeedData'] || [];
              newChartData.dataList[1].data = item && item.yData && item.yData['netInSpeedData'] || [];
              newChartData.dataList[2].data = item && item.yData && item.yData['percentile95'] || [];
              let dataList = Object.assign({}, newChartData, this.typeObj[2]);
              chartList.push(dataList);
            });
            this.$set(this.echartListData, 'month', chartList);
          } else {
            this.$set(this.echartListData, 'month', []);
          }
        }).catch(() => {
          this.$modal.closeLoading();
        });
      },
      // 包端图表
      graPackageList(timeArr){
        graPackage(Object.assign({resourceType: this.resourceType, bandwidthType: 3}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach((item, index) => {
              item.targetName = this.resourceType === 1 ? item.nodeName : item.switchName;
              item.targetInter = item.interfaceName;
              let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graPackageList'}, item, this.typeObj[3]);
              this.$set(this.echartListData, index * 7 + 2, dataList);
            });
            // let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graPackageList'},res.data, this.typeObj[3]);
            // this.$set(this.echartListData, 2, dataList);
          } else {
            this.$set(this.echartListData, 2, {});
          }
        });
      },
      // 月均日95值Mbps---图表
      graAvgMonthlyList(timeArr){
        graAvgMonthly(Object.assign({resourceType: this.resourceType, bandwidthType: 4}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach((item, index) => {
              item.titleList = this.resourceType === 1 ? '【' + item.nodeName + '】【' + item.businessName + '】' : '【' + item.nodeName + '】【' + item.interfaceName + '】【' + item.businessName + '】';
              let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graAvgMonthlyList'}, item, this.typeObj[4]);
              this.$set(this.echartListData, index * 7 + 3, dataList);
            });
            // let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graAvgMonthlyList'},res.data, this.typeObj[4]);
            // this.$set(this.echartListData, 3, dataList);
          } else {
            this.$set(this.echartListData, 3, {});
          }
        });
      },
      // 有效-95带宽值Mbps/日---图表
      graEffectiveDailyList(timeArr){
        graEffectiveDaily(Object.assign({resourceType: this.resourceType, bandwidthType: 5}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach((item, index) => {
              item.titleList = this.resourceType === 1 ? '【' + item.nodeName + '】【' + item.businessName + '】' : '【' + item.nodeName + '】【' + item.interfaceName + '】【' + item.businessName + '】';
              let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graEffectiveDailyList'}, item, this.typeObj[5]);
              this.$set(this.echartListData, index * 7 + 4, dataList);
            });
            // let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graEffectiveDailyList'},res.data, this.typeObj[5]);
            // this.$set(this.echartListData, 4, dataList);
          } else {
            this.$set(this.echartListData, 4, {});
          }
        });
      },
      // 有效-95带宽值Mbps/月----图表
      graEffectiveMonthlyList(timeArr){
        graEffectiveMonthly(Object.assign({resourceType: this.resourceType, bandwidthType: 6}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach((item, index) => {
              item.titleList = this.resourceType === 1 ? '【' + item.nodeName + '】【' + item.businessName + '】' : '【' + item.nodeName + '】【' + item.interfaceName + '】【' + item.businessName + '】';
              let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graEffectiveMonthlyList'}, item, this.typeObj[6]);
              this.$set(this.echartListData, index * 7 + 5, dataList);
            });
            // let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graEffectiveMonthlyList'},res.data, this.typeObj[6]);
            // this.$set(this.echartListData, 5, dataList);
          } else {
            this.$set(this.echartListData, 5, {});
          }
        });
      },
      // 有效-月均日95值Mbps----图表
      graEffectiveAvgMonthlyList(timeArr){
        graEffectiveAvgMonthly(Object.assign({resourceType: this.resourceType, bandwidthType: 7}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach((item, index) => {
              item.titleList = this.resourceType === 1 ? '【' + item.nodeName + '】【' + item.businessName + '】' : '【' + item.nodeName + '】【' + item.interfaceName + '】【' + item.businessName + '】';
              let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graEffectiveAvgMonthlyList'}, item, this.typeObj[7]);
              this.$set(this.echartListData, index * 7 + 6, dataList);
            });
            // let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graEffectiveAvgMonthlyList'},res.data, this.typeObj[7]);
            // this.$set(this.echartListData, 6, dataList);
          } else {
            this.$set(this.echartListData, 6, {});
          }
        });
      },
      async chartDataEvent(valData, unit, type) {
        if (type === 'day') {
          await Promise.all([
            this.$modal.loading(),
            this.graDailyList({startTime: this.timeList[1][0], endTime: this.timeList[1][1]}, {unit: unit}),
          ]);
          this.$modal.closeLoading();
        } else {
          await Promise.all([
            this.$modal.loading(),
            this.graMonthlyList({startTime: this.timeList[2][0], endTime: this.timeList[2][1]}, {unit: unit}),
          ]);
          this.$modal.closeLoading();
        }
        // // 检查函数是否存在，避免报错
        // if (typeof this[funcName] === 'function') {
        //   // 调用实际函数，并传递参数（如选中的值、当前项）
        //   this[funcName]({startTime: valData[0], endTime: valData[1]});
        // } else {
        //   console.warn(`函数 ${funcName} 未定义`);
        // }
      },
      // 获取前一天的
      getBeforDay() {
        const now = new Date();
        // 获取当前时间
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        // 正确计算前一天（处理跨月情况）
        const prevDate = new Date(now);
        prevDate.setDate(now.getDate() - 1);
        const prevYear = prevDate.getFullYear();
        const prevMonth = String(prevDate.getMonth() + 1).padStart(2, '0');
        const prevDay = String(prevDate.getDate()).padStart(2, '0');
        // 构建时间字符串
        const startData = `${prevYear}-${prevMonth}-${prevDay}`;
        const endData = `${year}-${month}-${day}`;
        return {startTime: startData, endTime: startData};
      },
      // 获取前一年的月
      getLastMonths(num) {
        const threeMonths = [];
        const today = new Date(); // 当前日期
        const currentYear = today.getFullYear();
        const currentMonth = today.getMonth() + 1; // 月份从0开始（0=1月，11=12月）
        // 循环获取前3个月（i=0: 前1个月，i=1: 前2个月，i=2: 前3个月）
        for (let i = 1; i <= num; i++) {
          // 计算目标月份（当前月 - i）
          let targetMonth = currentMonth - i;
          let targetYear = currentYear;
          // 处理月份溢出（如1月-1=12月，年份减1）
          if (targetMonth < 0) {
            targetMonth += 12;
            targetYear -= 1;
          }
          // 格式化月份为两位数（如5月→'05'）
          const monthStr = String(targetMonth + 1).padStart(2, '0'); // 加1是因为月份从0开始
          threeMonths.unshift(`${targetYear}-${monthStr}`);
        }
        return {startTime: threeMonths[0], endTime: threeMonths[0]};
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'submit':
              break;
            case 'cancel':
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .ultabs .el-range-editor .el-range-input {
    vertical-align: super!important;
  }
  ::v-deep .ultabs .el-date-editor .el-range-separator {
    vertical-align: super!important;
  }
  ::-webkit-scrollbar {
    width: 0px!important;
    height: 0px!important;
  }
  /* 设置下拉多选不闪烁问题 */
  ::v-deep .el-tag {
    margin: 1px 1px 1px 4px !important;
  }
  ::v-deep .el-select .el-input__inner {
    min-height: 36px;
    height: 100% !important; /* 强制高度为100% */
  }
</style>
