<template>
  <div style="height: calc(100vh)!important">
    <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 - 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>
    </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: 'AnalysisChart',
    components: {Form, EchartsLine, EchartsBar},
    dicts: ['eps_bandwidth_type'],
    props: {
      activeName: {
        type: String,
        default: "1000"
      },
      noticeType: {
        type: Array,
        default: []
      }
    },
    watch: {
      activeName: {
        handler(val) {
          this.initData();
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        paramsData: {},
        form: {},
        storageKey: '',
        selectChangeList: [],
        switchData: [],
        disabledList: {},
        echartListData: [],
        typeObj: {},
        paramsVal: {},
        resourceType: '',
        lineDataParams: {
          lineXData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sa', 'Sun'],
          data: [120, 132, 101, 134, 90, 230, 210]
        },
      }
    },
    created() {},
    mounted() {},
    methods: {
      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.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);
          }
        }
      },
      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
          };
        }
        this.echartListData = [];
        this.paramsVal['calculationMode'] = this.activeName;
        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 => {
          let name = this.resourceType === 1 ? item.nodeName : item.uplinkSwitch;
          if (!nameArr.includes(name)) {
            item.label = name;
            item.value = name;
            nameArr.push(name);
            nameListArr.push(item);
          }
        });
        if (this.noticeType && this.noticeType.length > 0) {
          this.form.noticeType = this.noticeType;
        } else {
          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];
            }
          }
        }
        showNameList = this.form.noticeType;
        this.echartListData = [];
        if (showNameList && showNameList.length > 0) {
          if (this.resourceType === 1) {
            this.paramsVal = {
              nodeNames: showNameList
            };
          } else {
            this.paramsVal = {
              switchNames: showNameList
            };
          }
          this.paramsVal['calculationMode'] = this.activeName;
          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({resourceType: this.resourceType, bandwidthType: 1} ,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: 'graDailyList'},item, this.typeObj[1]);
              this.$set(this.echartListData, index * 7, dataList);
              this.$set(this.disabledList, index * 7, 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: this.resourceType, bandwidthType: 2}, 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: 'graMonthlyList'},item, this.typeObj[2]);
              this.$set(this.echartListData, index * 7 + 1, dataList);
            });
            // 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: 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, {});
          }
        });
      },
      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 endYear = currentDate.getFullYear();
        const endMonth = currentDate.getMonth(); // 0=1月，11=12月
        const endDay = currentDate.getDate();     // 当前日（如8）

        // 2. 计算起点日期（当前日期的“上月同日”，处理边界：如3月31日→2月28/29日）
        const startDate = new Date(endYear, endMonth, endDay);
        // 核心：将当前日期的月份减1（得到上月同日，自动处理天数不足问题）
        startDate.setMonth(startDate.getMonth() - 1);

        // 3. 提取起点日期的年、月、日（用于循环判断）
        const startYear = startDate.getFullYear();
        const startMonth = startDate.getMonth();
        const startDay = startDate.getDate();

        // 4. 循环生成“起点~终点”的所有日期
        const dateCollection = [];
        // 临时日期：从起点日期开始递增
        const tempDate = new Date(startYear, startMonth, startDay);

        // 循环条件：临时日期 <= 当前日期（终点）
        while (tempDate <= currentDate) {
          // 格式化日期为“YYYY-MM-DD”（补零处理：如8月→08，5日→05）
          const year = tempDate.getFullYear();
          const month = String(tempDate.getMonth() + 1).padStart(2, '0');
          const day = String(tempDate.getDate()).padStart(2, '0');
          const formattedDate = `${year}-${month}-${day}`;

          dateCollection.push(formattedDate);

          // 临时日期加1天（进入下一天）
          tempDate.setDate(tempDate.getDate() + 1);
        }
        return {startTime: dateCollection[0], endTime: dateCollection[dateCollection.length - 1]};
      },
      // 获取前一年的月
      getLastMonths() {
        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 <= 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>
