<template>
  <div style="height: calc(100vh)!important; padding: 10px;">
    <div class="w100 h100">
      <div class="w100" style="text-align: right;">
        <el-date-picker
          v-model="timeList"
          :style="{width: '360px!important', marginRight: '10px'}"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          range-separator="至"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="(val) => dateChange(val)"/>
      </div>
      <template v-for="(item,key, index) of echartListData">
        <EchartsLine :lineData="item.dataVal" :title="item.title" class="w100 mt20 mb20" style="border: 1.5px solid #878787;height:200px;" :chartData="(valData, unit) => chartDataEvent(item, unit, key)"></EchartsLine>
      </template>
    </div>
  </div>
</template>

<script>
  import {getNetTraffic, trafficEcharts} from "@/api/disRevenue/resource"
  import EchartsLine from "@/components/echartsList/line.vue";
  export default {
    name: "trafficChart",
    components: {EchartsLine},
    data() {
        return {
          timeList: [],
          paramsData: {},
          currTimeList: {},
          echartListData: {},
          echartData: {
            title: 'GE1/0/1的丢包数',
            dataVal: {
              titleVal: {textAlign: 'center'},
              yAxisName: ' ',
              gridTop: '30%',
              legend: {top: '12%', left: '10%',type: 'scroll',orient: 'horizontal'},
              hiddenTime: true,
              lineXData: [],
              unitSelList: [{label: 'Kb', value: 'Kb'},{label: 'Mb', value: 'Mb'}, {label: 'Gb', value: 'Gb'}],
              dataList: [{
                name: '出战流量',
                data: [],
              },{
                name: '入站流量',
                data: []
              }]
            }
          },
        }
    },
    created() {
      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 hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).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 timeString = `${hours}:${minutes}:${seconds}`;
      const startData = `${prevYear}-${prevMonth}-${prevDay} ${timeString}`;
      const endData = `${year}-${month}-${day} ${timeString}`;

      this.currTimeList = {startTime: startData, endTime: endData};
      this.timeList = [startData, endData];
      this.initData();
    },
    methods: {
      // 时间变化时
      dateChange(val){
        this.currTimeList = {startTime: val[0], endTime: val[1]};
        this.getNetTraffic(this.paramsData.clientIdList);
      },
      initData(){
        this.storageKey = this.$route.query && this.$route.query['storageKey'];
        if (this.storageKey) {
          this.paramsData = JSON.parse(localStorage.getItem(this.storageKey));
          this.getNetTraffic(this.paramsData.clientIdList);
        }
      },
      // 总流量图查询
      getNetTraffic(val) {
        getNetTraffic(Object.assign({},{clientInterfaces: val}, this.currTimeList)).then(res => {
          if (res && res.data && res.data.length > 0) {
            res.data.forEach(item => {
              let netEcharts = JSON.parse(JSON.stringify(this.echartData));
              netEcharts.title = `【${item && item.clientId}】${item && item.interfaceName}`;
              netEcharts.interfaceName = item && item.interfaceName;
              netEcharts.dataVal.yAxisName = item && item.unit ? '单位' + item.unit : ' ';
              netEcharts.dataVal.lineXData = item && item.xData.length > 0 ? item.xData : [];
              netEcharts.dataVal['unitModel'] = item && item.unit || '';
              if (item && item.showRealation) {
                let ledgendArr = [];
                Object.keys(item.showRealation).forEach((key,index) => {
                  ledgendArr.push(item.showRealation[key]);
                  netEcharts.dataVal.dataList[index] = {
                    name: item.showRealation[key],
                    data: item && item.yData[key] || []
                  };
                });
                if (item && item.showRealation && Object.keys(item.showRealation).length > 5) {
                  netEcharts.dataVal.legend = Object.assign({}, netEcharts.dataVal.legend, {show: false, legendSelect: ledgendArr, data: ledgendArr});
                }
              } else {
                netEcharts.dataVal.dataList[0].data = item && item.yData['netOutSpeedData'] || [];
                netEcharts.dataVal.dataList[1].data = item && item.yData['netInSpeedData'] || [];
              }
              this.$set(this.echartListData, item.clientId, netEcharts);
            });
          }
        });
      },
      // 单位查询
      getTrafficChartData(clientIdTitle, titleName, unitData) {
        return trafficEcharts(Object.assign(unitData || {}, {name : titleName,clientId: clientIdTitle}, this.currTimeList)).then(res => {
          if (res && res.data) {
            let netEcharts = JSON.parse(JSON.stringify(this.echartData));
            netEcharts.title = `【${clientIdTitle}】${titleName}`;
            netEcharts.interfaceName = titleName;
            netEcharts.dataVal.yAxisName = res.data && res.data.unit ? '单位' + res.data.unit : ' ';
            netEcharts.dataVal.lineXData = res.data && res.data.xData.length > 0 ? res.data.xData : [];
            netEcharts.dataVal['unitModel'] = res.data && res.data.unit || '';
            if (res.data && res.data.showRealation) {
              let ledgendArr = [];
              Object.keys(res.data.showRealation).forEach((key,index) => {
                ledgendArr.push(res.data.showRealation[key]);
                netEcharts.dataVal.dataList[index] = {
                  name: res.data.showRealation[key],
                  data: res.data && res.data.yData[key] || []
                };
              });
              if (res.data && res.data.showRealation && Object.keys(res.data.showRealation).length > 5) {
                netEcharts.dataVal.legend = Object.assign({}, netEcharts.dataVal.legend, {show: false, legendSelect: ledgendArr, data: ledgendArr});
              }
            } else {
              netEcharts.dataVal.dataList[0].data = res.data && res.data.yData['netOutSpeedData'] || [];
              netEcharts.dataVal.dataList[1].data = res.data && res.data.yData['netInSpeedData'] || [];
            }
            this.$set(this.echartListData, clientIdTitle, netEcharts);
          }
          return true;
        }).catch(() => {
          return true;
        });
      },
      async chartDataEvent(valData, unit, clientIdTitle) {
        if (unit) {
          await Promise.all([
            this.$modal.loading(),
            this.getTrafficChartData(clientIdTitle, valData.interfaceName,{unit: unit}),
          ]);
          this.$modal.closeLoading();
        }
      },
    }
  }
</script>

<style scoped>

</style>
