<template>
  <div :class="open ? 'plr-20' : 'app-container'">
    <el-collapse v-model="activeShowList" @change="collapseChange">
      <template v-for="(val,key, index) of chartDataLit">
        <el-collapse-item :title="`【${val && val.title || ''}】${val && val.jointName || ''}`" :name="val && val.title || ''">
          <div class="mt10 w100">
            <div v-for="item of val && val.echartList || []" :key="`div-${val && val.title || ''}-${item && item.title || ''}-${index}`" class="w100" style="height: 200px;">
              <div v-if="val &&val.failFlag === 1" class="failFlagSty">
                <div class="textAlignCenter">探测失败 <br/>{{val.mtrClientId}}</div>
              </div>
              <div v-else class="w100 h100" style="position: relative;">
                <div style="position: absolute;">最后一跳丢包率：{{item.dataVal.lastYDataNum || item.dataVal.lastYDataNum == 0 ? item.dataVal.lastYDataNum : 'null'}}</div>
                <EchartsLine class="w100 h100" :key="`chart-${val && val.title || ''}-${item && item.title || ''}-${index}`" :lineData="item && item.dataVal || {}" :dateDataTrans="item && item.dateDataTrans || {}" :dateShowType="item && item.dateShowType || 'datetimerange'" :title="item && item.title || '图表数据'" :chartData="(valData) => chartDataEvent(valData,val.title)" @dialogChartTabList="dialogChartTabList" @showChartTabList="showChartTabList"></EchartsLine>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </template>
    </el-collapse>
    <template v-if="open && roleList.length > 0">
      <div style="font-size: 1.2rem;" class="pt5 pb5">{{tagTitle}}</div>
      <TableList :columns="columns" :config="{colTopHiddenIcon: true, colHiddenCheck: true}" :tableList="roleList">
        <template #tempUnit="{ valueKey, row, column }">
          {{row[valueKey]}}{{column.unit}}
        </template>
      </TableList>
    </template>
    <div style="text-align: right;margin-top: 20px;margin-right: 20px;">
      <el-button @click="goBack">返回</el-button>
    </div>
    <!--   弹窗    -->
    <el-dialog :title="tagTitle" :visible.sync="tagOpen" width="900px" append-to-body style="padding-bottom: 20px;">
      <TableList :columns="columns" :config="{colTopHiddenIcon: true, colHiddenCheck: true}" :tableList="roleList">
        <template #tempUnit="{ valueKey, row, column }">
          {{row[valueKey]}}{{column.unit}}
        </template>
      </TableList>
      <div style="text-align: right;margin-right: 20px;margin-top: 20px;">
        <el-button @click="tagOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {mtrCToClientIds, lossRateByMtr} from "@/api/disRevenue/resource"
  import EchartsLine from "@/components/echartsList/line.vue";
  import TableList from '@/components/table/index.vue';
  export default {
    name: "lossRateChart",
    components: {EchartsLine, TableList},
    props: {
      open: {
        type: String,
        default: ''
      },
      dialogRowData: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val === 'type_true') {
            this.activeShowList = [];
            this.paramsData = {};
            let params = {};
            params[this.dialogRowData.clientId] = this.dialogRowData;
            params[this.dialogRowData.clientId]['title'] = this.dialogRowData.clientId;
            params[this.dialogRowData.clientId]['jointName'] = '丢包率';
            this.activeShowList.push(this.dialogRowData.clientId);
            this.chartDataLit = params;
            this.tagTitle = '';
            this.roleList = [];
            this.timeDefault();
            this.$nextTick(() => {
              this.getEchartList(params, 'dialog');
            });
          } else if (val === 'type_false') {
          }
        },
        deep: true,
        immediate: true
      },
    },
    data() {
      return {
        activeShowList: [],
        chartDataLit: {},
        echartList: [{
          title: '  ',
          dateShowType: 'datetimerange',
          dateDataTrans: {transList: true},
          dataVal: {
            titleVal: {textAlign: 'left', left: '1%'},
            yAxisName: ' ',
            gridTop: '35%',
            tooltipFormatter: {customList: true, valueToop: {num: -1, msg: '探测失败'}},
            legend: {},
            lineXData: [],
            dataList: [{
              name: '',
              data: []
            }]
          }
        }],
        paramsData: {},
        currTimeList: {},
        defaultTimes: [],
        tagTitle: '',
        tagOpen: false,
        columns: {
          hopNumber: { label: `路径`, minWidth: '50', visible: true},
          avgLatency:{ label: `平均延迟(ms)`,minWidth: '100', unit: '(ms)', slotName: 'tempUnit', visible: true},
          lossPercent:{ label: `丢包率(%)`,minWidth: '80', unit: '%', slotName: 'tempUnit', visible: true},
          ipAddress: { label: `地址`, minWidth: '120', visible: true },
          country:{ label: `国家`,minWidth: '80', visible: true},
          isp: { label: `运营商`, minWidth: '120', visible: true},
          province: { label: `省`, minWidth: '80', visible: true },
          city: { label: `市`, minWidth: '80', visible: true},
        },
        roleList: [],
      }
    },
    created() {
      this.paramsData = this.$route && this.$route.query;
      this.timeDefault();
      if (!this.open) {
        this.getLossRateChart();
      }
    },
    methods: {
      timeDefault(){
        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.defaultTimes = [startData, endData];
      },
      getLossRateChart() {
        this.activeShowList = [];
        mtrCToClientIds({mtrClientId: this.paramsData.mtrClientId}).then(res => {
          let dataList = {};
          res && res.data.forEach(item => {
            this.activeShowList.push(item.clientId);
            item['title'] = item.clientId;
            item['jointName'] = '丢包率';
            dataList[item.clientId] = item;
          });
          this.chartDataLit = dataList;
          this.getEchartList(dataList);
        });
      },
      getEchartList(resVal, type) {
        if (resVal && Object.keys(resVal).length > 0) {
          Object.keys(resVal).forEach(item => {
            let chartList = JSON.parse(JSON.stringify(this.echartList))[0];
            chartList.dateDataTrans['dateRange'] = this.defaultTimes;
            lossRateByMtr(Object.assign({}, {clientId: resVal[item].clientId, mtrClientId: resVal[item].mtrClientId || null}, this.currTimeList)).then(res => {
              if (res && res.data) {
                let yDataList = [];
                if (res.data.yData && res.data.yData.packetLossRate) {
                  if (res.data.yData && res.data.yData.deployDevice) {
                    yDataList = res.data.yData.packetLossRate.map((yItem,index) => {return {value: yItem, content: res.data.yData.deployDevice[index]}});
                  } else {
                    yDataList = res.data.yData.packetLossRate || [];
                  }
                }
                chartList.dataVal.dialogOpen = this.open ? this.open : null;
                chartList.dataVal.tooltipFormatter['defaultType'] = type ? type : null;
                chartList.dataVal.lineXData = res.data && res.data.xData || [];
                chartList.dataVal.dataList[0].data = yDataList || [];
                chartList.dataVal.lastYDataNum = chartList.dataVal.dataList[0].data.length > 0 ? chartList.dataVal.dataList[0].data[chartList.dataVal.dataList[0].data.length - 1].value : null;
                this.$set(this.chartDataLit, item, Object.assign({}, this.chartDataLit[item], {echartList: [chartList]}));
              }
            });
          })
        }
      },
      collapseChange(val) {
        this.activeShowList = val;
        // if (val && val.length > 0) {
        //   this.$emit("collapseChangeData", val);
        // }
      },
      chartDataEvent(valData, tabName) {
        if (valData && valData.timeArr) {
          this.currTimeList = {startTime: valData.timeArr[0], endTime: valData.timeArr[1]};
          this.defaultTimes = valData.timeArr;
          let params = {};
          params[tabName] = this.chartDataLit[tabName];
          this.getEchartList(params);
        }
      },
      // 点击时
      dialogChartTabList(val) {
        if (val) {
          this.tagTitle = val.value;
          this.tagOpen = true;
          this.roleList = JSON.parse(val.tableVal.content);
        }
      },
      // 鼠标移动时
      showChartTabList(val) {
        if(val && Object.keys(val).length > 0) {
          this.tagTitle = val.value;
          this.roleList = JSON.parse(val.tableVal.content);
        } else {
          this.tagTitle = '';
          this.roleList = [];
        }
      },
      goBack(){
        if (this.open) {
          this.$emit("dialogResult", {open: false});
        } else {
          this.$router.push("/resource/mtrAgent");
        }
      },
    }
  }
</script>

<style scoped>
  ::v-deep .el-collapse-item__header {
    background-color: #d4e3fc!important;
    /*color: #fff!important;*/
    padding-left: 20px;
    font-size: 1rem;
  }
  .failFlagSty {
    height: 100%;
    color: #98989899;
    font-size: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
