<template>
  <div :class="datetimeModelOne && datetimeModelOne.length > 0 ? 'h100 w100' : 'app-container'">
    <div class="w100" style="height: 60px;">
      <div class="fl" style="text-align: left;">
        <el-select v-model="configModel" placeholder="请选择配置" style="margin-right: 10px;" @change="selectValChange">
          <el-option
            v-for="item in configNameList"
            :key="item.id"
            :label="item.configName"
            :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary" @click="fnFormHandle('add')">添加配置</el-button>
        <el-button @click="fnFormHandle('edit')">修改配置</el-button>
        <el-button @click="fnFormHandle('del')">删除配置</el-button>
      </div>
      <div class="fr" style="text-align: right;">
        <el-date-picker
          v-model="datetimeModel"
          style="width: 360px!important;margin-right: 10px;"
          type="datetimerange"
          unlink-panels
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          :default-time="['00:00:00', '23:59:59']"
          @change="dateChange">
        </el-date-picker>
        <el-select v-model="timeModel" placeholder="请选择" style="width: 100px;margin-right: 10px;" @change="fnTimeInter">
          <el-option
            v-for="item in timeModelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button :type="activeType === '1' ? 'primary' : ''" @click="viewMonitorChart('1')">概览视图</el-button>
        <el-button :type="activeType === '2' ? 'primary' : ''" @click="viewMonitorChart('2')">详情视图</el-button>
      </div>
    </div>
    <div style="height: calc(100% - 60px);" class="w100">
      <div v-for="(chartItem, key, index) of lineDataParams" class="h40 w100" style="min-height: 300px;">
        <div class="w100 h100" style="border: 1px solid #e8e8e8;">
          <EchartsLine :lineData="chartItem || {}" :title="chartItem && chartItem.title || ''" class="w100 h100" @chartClickModel="chartClickModel" :chartData="(valData, unit) => chartDataEvent(valData, unit)"></EchartsLine>
        </div>
      </div>
      <div class="w100 mt20">
        <TableList :columns="columns" :config="config" :queryParams="queryParams" :tableList="roleList" @fnClick="callback" @fnRenderList="getList">
          <template #tempDay="{ valueKey, row, column }">
            <span v-if="row && row[valueKey] || row[valueKey] === 0">{{row[valueKey]}}/{{row.createTime}}</span>
          </template>
        </TableList>
      </div>
    </div>
    <!--    弹窗  -->
    <el-dialog title="添加配置" :visible.sync="open" width="800px" append-to-body>
      <dialogMonitor :formModel="formModel" @dialogResult="fnDialogResult"></dialogMonitor>
    </el-dialog>
  </div>
</template>

<script>
  import dialogMonitor from './dialogMonitor';
  import EchartsLine from "@/components/echartsList/line.vue";
  import TableList from '@/components/table/index.vue';
  import {monitorViewChart, monitorConfigList, delMonitorConfig, getBandWidthList, getSwitchInfoList} from "@/api/disRevenue/resource";
  export default {
    name: "monitorBoardView",
    components: {dialogMonitor, EchartsLine, TableList},
    props: {
      timeModelOne: {
        type: String,
        default: '30000'
      },
      datetimeModelOne: {
        type: Array,
        default: () => []
      },
      activeTypeOne: {
        type: String,
        default: '2'
      }
    },
    data() {
      return {
        paramsData: {},
        configModel: '',
        configNameList: [],
        formModel: {},
        reserveForm: {},
        datetimeModel: [],
        timeModel: '30000',
        timeInterModel: null,
        activeType: '2',
        open: false,
        timeModelOptions: [
          {value: '30000', label: '30s刷新'},
          {value: '10000', label: '10s刷新'},
          {value: '0', label: '不刷新'},
        ],
        echartData: {
          title: ' ',
          yAxisName: ' ',
          unitModel: 'Kb',
          highlight: true,
          unitSelList: [{label: 'Kb', value: 'Kb'},{label: 'Mb', value: 'Mb'}, {label: 'Gb', value: 'Gb'}],
          legend: {bottom: '0%'},
          gridTop: '40px',
          gridBotm: '15%',
          hiddenTime: true,
          lineXData: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sa', 'Sun'],
          dataList: [
            {name: '入方向总流量', data: []},
            {name: '出方向总流量', data: []}
          ]
        },
        lineDataParams: {},
        btnList: [{title: '详情', value: 'view'}, {title: '修改', value: 'edit'}, {title: '删除', value: 'del'}],
        // 列显隐信息
        columns: {},
        config: {},
        roleList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
      }
    },
    created() {
      this.activeType = this.activeTypeOne;
      this.paramsData = this.$route && this.$route.query;
      this.configModel = this.paramsData && this.paramsData.id ? Number(this.paramsData.id) : '';
      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');
      const hours = String(new Date().getHours()).padStart(2, '0') + ':';
      const minutes = String(new Date().getMinutes()).padStart(2, '0') + ':';
      const seconds = String(new Date().getSeconds()).padStart(2, '0');
      startData = `${year}-${month}-${prevDay}` + ' ' + hours + minutes + seconds;
      endData = `${year}-${month}-${day}` + ' ' + hours + minutes + seconds;
      this.currTimeList = this.datetimeModelOne && this.datetimeModelOne.length > 0 ? {startTime: this.datetimeModelOne[0], endTime: this.datetimeModelOne[1]} : {startTime: startData, endTime: endData};
      this.datetimeModel = this.datetimeModelOne && this.datetimeModelOne.length > 0 ? this.datetimeModelOne : [startData, endData];
      this.timeModel = this.timeModelOne;
      this.fnConfigName();
      if (this.configModel) {
        this.fnChartView();
      }
    },
    beforeDestroy() {
      clearInterval(this.timeInterModel);
      this.timeInterModel = null;
    },
    methods: {
      // 查询流量图
      fnChartView(unitData) {
        this.lineDataParams = {};
        monitorViewChart(Object.assign(unitData || {},this.currTimeList, {monitorId: this.configModel})).then(res => {
          let dataList = {};
          let searchListData = {};
          res && res.data.forEach(item => {
            let chart = JSON.parse(JSON.stringify(this.echartData));
            let modelVal = item && item.rmMonitorConfig || {id: 'one', configName: 'one'};
            this.reserveForm = modelVal;
            this.columns = {};
            this.config = {};
            this.tableShowModel(modelVal);
            dataList[modelVal && modelVal.configName + '_' + modelVal.id] = {};
            if (item && item.unit) {
              chart.unitModel = item.unit;
              chart.unitSelList = [{label: 'Kb', value: 'Kb'},{label: 'Mb', value: 'Mb'}, {label: 'Gb', value: 'Gb'}];
            }
            chart.lineXData = item && item.xData || [];
            let netInSpeedData = [];
            let netOutSpeedData = [];
            if (item && item.yData && item.yData.netInSpeedData) {
              if (!item.yData.netInSpeedData.some(item => item && typeof Number(item) === 'number' && !isNaN(item))) {
                item.yData.netInSpeedData[0] = '0';
              }
            }
            if (item && item.yData && item.yData.netOutSpeedData) {
              if (!item.yData.netOutSpeedData.some(item => item && typeof Number(item) === 'number' && !isNaN(item))) {
                item.yData.netOutSpeedData[0] = '0';
              }
            }
            if (item && item.yData && item.yData.deployDevice && item.yData.deployDevice.length > 0) {
              item && item.yData && item.yData.netInSpeedData.map((valData,index) => {
                netInSpeedData.push({value: valData, clientId: item.yData['deployDevice'][index] || null});
              });
              item && item.yData  && item.yData.netOutSpeedData.map((valData,index) => {
                netOutSpeedData.push({value: valData, clientId: item.yData['deployDevice'][index] || null});
              });
            }
            searchListData = {content: netInSpeedData && netInSpeedData[0], name: item && item.xData[0]};
            chart.dataList[0].data = netInSpeedData || [];
            chart.dataList[1].data = netOutSpeedData || [];
            dataList[modelVal.configName + '_' + modelVal.id] = chart;
          });
          if (dataList && Object.keys(dataList).length > 0) {
            this.lineDataParams = {...dataList};
          } else {
            this.lineDataParams['one'] = this.echartData;
          }
          this.roleList = [];
          this.queryParams.total = 0;
          // // 默认展示第一个点的数据
          this.chartClickModel({params: {value: searchListData.content.value, name: searchListData.name, data: {clientId: searchListData.content.clientId}}});
          // 循环定时查询
          this.fnTimeInter(this.timeModel);
        }).catch(() => {
          // 循环定时查询
          this.fnTimeInter(this.timeModel);
        });
      },
      // 列表数据展示
      tableShowModel(modelVal){
        let showColVal = false;
        if (modelVal && modelVal.resourceType && (modelVal.resourceType === '1' || modelVal.resourceType === '3')) {
          showColVal = true;
          this.config = {
            colTopHiddenIcon: true,
            tableButton: {
              line: [
                {content: '详情', fnCode: 'details', type: 'text', icon: 'el-icon-view', hasPermi: 'resource:monitorBoardView:details'},
              ]
            }
          };
        } else if (modelVal && modelVal.resourceType && modelVal.resourceType === '2') {
          this.config = {colTopHiddenIcon: true};
        }
        this.columns = {
          id: { label: `ID`,width: '50'},
          clientId: { label: `ClientID`, minWidth: '120', visible: showColVal},
          businessName: {label: `业务名称`, minWidth: '150', visible: showColVal},
          bandwidth95Daily: {label: `95带宽值/日(Mbit)`, minWidth: '150', slotName: 'tempDay', visible: showColVal},
          switchName: {label: `交换机名称`, minWidth: '150', visible: !showColVal},
          name: {label: `端口名称`, minWidth: '150', visible: !showColVal},
          inSpeed: {label: `接收速率值(bits/s)`, minWidth: '150', visible: !showColVal},
          outSpeed: {label: `发送速率值(bits/s)`, minWidth: '150', visible: !showColVal},
          createTime: {label: `时间`, minWidth: '150', visible: !showColVal},
        };
      },
      // 下拉
      fnConfigName() {
        monitorConfigList({}).then(res => {
          if (res && res.data && res.data.length > 0) {
            this.configNameList = res && res.data;
            let index = 0;
            res && res.data.forEach(item => {
              if (item.id === this.configModel) {
                index = 1;
              }
            });
            if (index === 0) {
              this.configModel = this.configNameList[0].id;
              this.fnChartView();
            }
          }
        });
      },
      // 定时刷新下拉
      fnTimeInter(val) {
        clearInterval(this.timeInterModel);
        this.timeInterModel = null;
        if (val !== '0') {
          this.timeInterModel = setInterval(() => {
            this.fnChartView();
          }, Number(val));
        }
      },
      // 按钮操作弹窗
      fnFormHandle(val) {
        if (val === 'add') {
          this.open = true;
          // 使用$nextTick确保DOM更新完成后再初始化子组件
          this.$nextTick(() => {
            // 强制更新formModel，确保子组件能接收到
            this.formModel = {};
          });
        } else if (val === 'edit') {
          this.open = true;
          // 使用$nextTick确保DOM更新完成后再初始化子组件
          this.$nextTick(() => {
            // 强制更新formModel，确保子组件能接收到
            this.formModel = this.reserveForm;
          });
        } else if (val === 'del') {
          let content = '<p style="font-size: 1rem;font-weight: 600;">确认删除 ' + this.reserveForm.configName + '</p>' +
            '<p style="height: 0px;margin-bottom: 50px;">删除 ' + this.reserveForm.configName + ' 配置后，相应的服务器/交换机集合的总流量的相关数据都将删除</p>';
          this.$modal.confirm(content).then(() => {
            delMonitorConfig(this.reserveForm.id).then(res => {
              this.fnConfigName();
            });
          }).catch(() => {});
        }
      },
      // 时间选择器
      dateChange() {
        this.currTimeList = {startTime: this.datetimeModel[0], endTime: this.datetimeModel[1]};
        this.fnChartView({});
      },
      // 下拉值变化事件
      selectValChange(val) {
        this.fnChartView();
      },
      addMonitor() {
        this.open = true;
      },
      fnDialogResult(res){
        this.open = false;
        this.fnConfigName();
        this.fnChartView();
      },
      // 详细视图
      viewMonitorChart(val) {
        this.activeType = val;
        if (val && val === '1') {
          if (this.paramsData && this.paramsData.id) {
            this.$router.push({
              path: '/resource/monitorBoard',
            });
          } else {
            this.$emit("activeTypeChange", {activeType: val, timeModel: this.timeModel, datetimeModel: this.datetimeModel});
          }
        }
      },
      // 点击图表
      chartClickModel(chart) {
        if (Number(chart.params.value) !== 0) {
          let paramsModel = {clientIds: chart.params.data.clientId, startTime: chart.params.name, endTime: chart.params.name};
          this.getList(paramsModel);
        }
      },
      getList(val) {
        this.queryParams = Object.assign({}, this.queryParams, val);
        if (this.reserveForm && (this.reserveForm.resourceType === '1' || this.reserveForm.resourceType === '3')) {
          this.$modal.loading();
          getBandWidthList(this.queryParams).then(response => {
            this.roleList = response.rows;
            this.queryParams.total = response.total;
            this.$modal.closeLoading();
          }).catch(() => {
            this.$modal.closeLoading();
          });
        } else if (this.reserveForm.resourceType === '2') {
          this.$modal.loading();
          getSwitchInfoList(this.queryParams).then(response => {
            this.roleList = response.rows;
            this.queryParams.total = response.total;
            this.$modal.closeLoading();
          }).catch(() => {
            this.$modal.closeLoading();
          });
        }
      },
      chartDataEvent(valData, unit) {
        if (unit) {
          let unitData = {unit: unit};
          this.fnChartView(unitData);
        }
      },
      callback(result, rowData) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'details':
              this.$router.push({
                path:'/resource/serverRegister/edit',
                query: {id: rowData.clientId, readonly: true, type: 'alarmLog'}
              });
              break;
            default:
          }
        }
      },
    }
  }
</script>

<style scoped>
  .el-button--medium {
    padding: 10px!important;
  }
</style>
