<template>
  <div style="height: calc(100vh)!important">
    <div style="height: 90px;">
      <el-form ref="noticeRef" :model="form" label-width="80px">
        <el-form-item label="ClientID" prop="clientId">
          <!--  allow-create default-first-option： 搜索下拉框中没有的数据并展示查询 -->
          <el-select v-model="form.clientId" multiple filterable placeholder="请选择ClientID" @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 of switchData">
        <el-switch v-model="item.checkType" :activeText="item.label" class="mr20" />
        <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%;"></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%;"></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 {listAllResourList, 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: '14%', 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: [],
          dataList: [
            {name: '发送流量值', data: []},
            {name: '金山API记录的发送流量值', data: []},
            {name: '95带宽值/日', areaStyleNone: true, data: []},
          ]
        },
        lineDataParams: {chart: {}},
      }
    },
    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.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){
        getRegistList({resourceType: type}).then(val => {
          this.selectChangeList = val && val.data.map(item => {
            return Object.assign({label: item.clientId, value: item.clientId});
          });
        });
      },
      // 下拉数据改变时触发
      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]};
        this.graDailyList(dayList);
        this.graMonthlyList(monthList);
        // 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);
          }
        }
      },
      // 初始化
      processData(list) {
        let nameArr = [];
        let nameListArr = [];
        let showNameList = [];
        list.forEach(item => {
          if (this.paramsData && this.paramsData.resourceType === '1') {
            if (item && item.clientId) {
              let name = item.clientId;
              if (!nameArr.includes(name)) {
                item.label = name;
                item.value = name;
                nameArr.push(name);
                nameListArr.push(item);
              }
            }
          } else if (this.paramsData && this.paramsData.resourceType === '2') {
            if (item && item.serverClientId) {
              let name = item.serverClientId;
              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) {
            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) {
          if (this.resourceType === 1) {
            this.paramsVal = {
              clientIds: showNameList.toString()
            };
          } else {
            this.paramsVal = {
              clientIds: showNameList.toString()
            };
          }
          this.paramsVal['calculationMode'] = this.activeName;
          this.graDailyList(dayList);
          this.graMonthlyList(monthList);
          // this.graPackageList(dayList);
          // this.graAvgMonthlyList(monthList);
          // this.graEffectiveDailyList(dayList);
          // this.graEffectiveMonthlyList(monthList);
          // this.graEffectiveAvgMonthlyList(dayList);
        }
      },
      // 95带宽值Mbps/日---图表 serverGraphDaily, serverGraphMonth, switchGraphDaily, switchGraphMonth
      graDailyList(timeArr){
        let fnType = serverGraphDaily;
        if (this.resourceType === 2) {
          fnType = switchGraphDaily;
        }
        let newChartData = JSON.parse(JSON.stringify(this.echartData));
        fnType(Object.assign({} ,this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            let chartList = [];
            res.data.forEach((item, index) => {
              let outContent = `最后一个值：${item && item.other && item.other.lastOutSpeedGb ? item.other.lastOutSpeedGb + 'G' : '0'}   平均值：${item && item.other && item.other.avgOutSpeedGb ? item.other.avgOutSpeedGb + 'G' : '0'}   最大值：${item && item.other && item.other.maxOutSpeedGb ? item.other.maxOutSpeedGb + 'G' : '0'}`;
              let inContent = `最后一个值：${item && item.other && item.other.lastInSpeedGb ? item.other.lastInSpeedGb + 'G' : '0'}   平均值：${item && item.other && item.other.avgInSpeedGb ? item.other.avgInSpeedGb + 'G' : '0'}   最大值：${item && item.other && item.other.maxInSpeedGb ? item.other.maxInSpeedGb + 'G' : '0'}`;
              let kdContent = `(${item && item.percentile95 ? item.percentile95 + 'mbit' : '0'}    out)`;
              newChartData.title = item && item.name;
              newChartData.yAxisName = item && item.other && item.other.recommendedUnit ? '单位' + 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', []);
          }
        });
      },
      // 95带宽值Mbps/月---图表 serverGraphDaily, serverGraphMonth, switchGraphDaily, switchGraphMonth
      graMonthlyList(timeArr){
        let fnType = serverGraphMonth;
        if (this.resourceType === 2) {
          fnType = switchGraphMonth;
        }
        let newChartData = JSON.parse(JSON.stringify(this.echartData));
        newChartData.dataList[newChartData.dataList.length - 1].name = '95带宽值/月';
        fnType(Object.assign({}, this.paramsVal, timeArr)).then(res => {
          if (res && res.data && res.data.length > 0) {
            let chartList = [];
            res.data.forEach((item, index) => {
              let outContent = `最后一个值：${item && item.other && item.other.lastOutSpeedGb ? item.other.lastOutSpeedGb + 'G' : '0'}   平均值：${item && item.other && item.other.avgOutSpeedGb ? item.other.avgOutSpeedGb + 'G' : '0'}   最大值：${item && item.other && item.other.maxOutSpeedGb ? item.other.maxOutSpeedGb + 'G' : '0'}`;
              let inContent = `最后一个值：${item && item.other && item.other.lastInSpeedGb ? item.other.lastInSpeedGb + 'G' : '0'}   平均值：${item && item.other && item.other.avgInSpeedGb ? item.other.avgInSpeedGb + 'G' : '0'}   最大值：${item && item.other && item.other.maxInSpeedGb ? item.other.maxInSpeedGb + 'G' : '0'}`;
              let kdContent = `(${item && item.percentile95 ? item.percentile95 + 'mbit' : '0'}    out)`;
              newChartData.title = item && item.name;
              newChartData.yAxisName = item && item.other && item.other.recommendedUnit ? '单位' + 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', []);
          }
        });
      },
      // 包端图表
      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} 未定义`);
        }
      },
      // 获取前一天的
      getBeforDay() {
        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}`;
        endData = `${year}-${month}-${day}`;
        return {startTime: startData, endTime: endData};
      },
      // 获取前一个月的所有日期
      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(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[threeMonths.length - 1]};
      },
      // 监听事件
      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;
  }
</style>
