<template>
  <div class="app-container">
    <div style="height: 90px;">
      <el-form ref="noticeRef" :model="form" label-width="80px">
        <el-form-item label="节点名称" prop="noticeType">
          <!--  allow-create default-first-option： 搜索下拉框中没有的数据并展示查询 -->
          <el-select v-model="form.noticeType" multiple filterable placeholder="请选择节点名称" @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>
      <el-switch v-for="item of switchData" v-model="item.checkType" :activeText="item.label" class="mr20" />
    </div>
    <div style="height: calc(100vh - 130px);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.nodeName + '】【' + item.businessName + '】' + 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.nodeName + '】【' + item.businessName + '】' + switchData[item.indexVal].label" class="w100 h40 mt20 mb20" style="border: 1.5px solid #878787;"></EchartsBar>
        </template>
      </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} from "@/api/disRevenue/earnManage"
  import {listAllResourList} from "@/api/disRevenue/resource";
  export default {
    name: 'DialogView',
    components: {Form, EchartsLine, EchartsBar},
    dicts: ['eps_bandwidth_type'],
    data() {
      return {
        paramsData: {},
        form: {},
        storageKey: '',
        selectChangeList: [],
        switchData: [],
        disabledList: {},
        selectChoose: [],
        echartListData: [],
        typeObj: {},
        paramsVal: {},
        resourceType: '',
        lineDataParams: {
          lineXData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          data: [120, 132, 101, 134, 90, 230, 210]
        },
      }
    },
    created() {},
    mounted() {
      this.storageKey = this.$route.query && this.$route.query['storageKey'];
      if (this.storageKey) {
        this.paramsData = JSON.parse(localStorage.getItem(this.storageKey));
        if (this.paramsData && this.paramsData.dictList) {
          this.switchData = this.paramsData.dictList.map((item,index) => {
            this.typeObj[item.value] = {type: item.value, indexVal: index};
            let obj = {
              label: item.label,
              value: item.value,
              checkType: true
            };
            return obj;
          });
        }
        if (this.paramsData && this.paramsData.list) {
          this.processData(this.paramsData.list);
        }
        if (this.paramsData && this.paramsData.resourceType) {
          this.fnNodeName(this.paramsData.resourceType);
        }
      }
    },
    destroyed() {
      localStorage.removeItem(this.storageKey);
    },
    methods: {
      fnNodeName(type){
        listAllResourList({resourceType: type}).then(val => {
          this.selectChangeList = val && val.map(item => {
            return Object.assign({label: item.resourceName, value: item.resourceName});
          });
        });
      },
      // 下拉数据改变时触发
      handleChange(eventVal) {
        if (this.resourceType === '1') {
          this.paramsVal = {
            nodeNames: eventVal
          };
        } else {
          this.paramsVal = {
            switchNames: eventVal
          };
        }
        let dayList = this.getDaysOfPreviousMonth();
        let monthList = this.getLastMonths();
        this.graDailyList(dayList);
        this.graMonthlyList(monthList);
        this.graPackageList(dayList);
        this.graAvgMonthlyList(monthList);
        this.graEffectiveDailyList(dayList);
        this.graEffectiveMonthlyList(monthList);
        this.graEffectiveAvgMonthlyList(dayList);
      },
      // 初始化
      processData(list) {
        let nameArr = [];
        let nameListArr = [];
        let showNameList = [];
        list.forEach(item => {
          this.resourceType = item.resourceType;
          let name = item.resourceType === '1' ? item.nodeName : item.uplinkSwitch;
          if (!nameArr.includes(name)) {
            item.label = name;
            item.value = name;
            nameArr.push(name);
            nameListArr.push(item);
          }
        });
        if (nameArr && nameArr.length > 0) {
          if (nameListArr.length >=2) {
            this.form.noticeType = [nameListArr[0].label, nameListArr[1].label];
          } else {
            this.form.noticeType = [nameListArr[0].label];
          }
          this.form.noticeType.forEach(item => {
            nameListArr.some(val => {
              if (item === val.label) {
                showNameList.push(val.label);
                this.selectChoose.push(val);
                return true;
              }
            });
          });
          if (this.resourceType === '1') {
            this.paramsVal = {
              nodeNames: showNameList
            };
          } else {
            this.paramsVal = {
              switchNames: showNameList
            };
          }
          let dayList = this.getDaysOfPreviousMonth();
          let monthList = this.getLastMonths();
          this.graDailyList(dayList);
          this.graMonthlyList(monthList);
          this.graPackageList(dayList);
          this.graAvgMonthlyList(monthList);
          this.graEffectiveDailyList(dayList);
          this.graEffectiveMonthlyList(monthList);
          this.graEffectiveAvgMonthlyList(dayList);
        }
      },
      // 95带宽值Mbps/日---图表
      graDailyList(timeArr){
        graDaily(Object.assign({} ,this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graDailyList'},res.data, this.typeObj[1]);
            this.$set(this.echartListData, 0, dataList);
            this.$set(this.disabledList, 0, dataList);
            this.disabledList[1] = {disabled: false};
          } else {
            this.disabledList[1] = {disabled: true};
            this.$set(this.echartListData, 0, {});
          }
        });
      },
      // 95带宽值Mbps/月---图表
      graMonthlyList(timeArr){
        graMonthly(Object.assign({resourceType: 1, bandwidthType: 2}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            let dataList = Object.assign({dateShowType: 'month', fnEvent: 'graMonthlyList'},res.data, this.typeObj[2]);
            this.$set(this.echartListData, 1, dataList);
          } else {
            this.$set(this.echartListData, 1, {});
          }
        });
      },
      // 包端图表
      graPackageList(timeArr){
        graPackage(Object.assign({resourceType: 1, bandwidthType: 3}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            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({}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            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({}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            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({}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            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({}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.resultData) {
            let dataList = Object.assign({dateShowType: 'day', fnEvent: 'graEffectiveAvgMonthlyList'},res.data, this.typeObj[7]);
            this.$set(this.echartListData, 6, dataList);
          } else {
            this.$set(this.echartListData, 6, {});
          }
        });
      },
      chartDataEvent(valData, funcName) {
        // 检查函数是否存在，避免报错
        if (typeof this[funcName] === 'function') {
          // 调用实际函数，并传递参数（如选中的值、当前项）
          this[funcName]({startTime: valData[0], endTime: valData[1]});
        } else {
          console.warn(`函数 ${funcName} 未定义`);
        }
      },
      // 获取前一个月的所有日期
      getDaysOfPreviousMonth(star, end) {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth(); // 0-11 表示 1-12 月

        // 计算前一个月的年份和月份
        const prevMonth = currentMonth - 1;
        const prevYear = prevMonth >= 0 ? currentYear : currentYear - 1;
        const prevMonthActual = prevMonth >= 0 ? prevMonth : 11; // 11 表示 12 月

        // 获取第一天和最后一天
        const firstDay = star ? new Date(star) : new Date(prevYear, prevMonthActual, 1);
        const lastDay = end ? new Date(end) : new Date(prevYear, prevMonthActual + 1, 0); // 下个月首日减 1 天

        // 生成所有日期
        const oneMonthDays = [];
        let currentDay = firstDay;
        while (currentDay <= lastDay) {
          // 格式化为 YYYY-MM-DD
          const formattedDate = currentDay.toISOString().split('T')[0];
          oneMonthDays.push(formattedDate);
          currentDay = new Date(currentDay); // 避免引用同一对象
          currentDay.setDate(currentDay.getDate() + 1);
        }
        return {startTime: oneMonthDays[0], endTime: oneMonthDays[oneMonthDays.length - 1]};
      },
      // 获取前一年的月
      getLastMonths() {
        const threeMonths = [];
        const today = new Date(); // 当前日期
        const currentYear = today.getFullYear();
        const currentMonth = today.getMonth(); // 月份从0开始（0=1月，11=12月）
        // 循环获取前3个月（i=0: 前1个月，i=1: 前2个月，i=2: 前3个月）
        for (let i = 1; i <= 12; 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[threeMonths.length - 1]};
      },
      // 监听事件
      callback(result, dataVal, formVal) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'submit':
              break;
            case 'cancle':
              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;
  }
</style>
