<template>
  <div :class="datetimeModelOne && datetimeModelOne.length > 0 ? 'h100 w100' : 'app-container'">
    <div class="w100" style="height: 60px;">
      <div class="fl" style="text-align: left;">
        <div class="disInlineBlock" style="width: 150px;padding-right: 8px;">
          <el-select v-model="groupData" placeholder="请选择" style="width: 100%;" @change="fnGroupChange">
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <el-select v-model="configModel" placeholder="请选择配置" style="margin-right: 8px;width: 150px;" @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: 355px!important;margin-right: 8px;"
          type="datetimerange"
          unlink-panels
          :picker-options="pickerOptions"
          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: 90px;margin-right: 8px;" @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="title" :visible.sync="open" width="800px" append-to-body>
      <dialogMonitor v-if="open" :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, getMonitorGroup} 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'
      },
      groupDataOne: {
        type: [String, Number],
        default: ''
      }
    },
    data() {
      return {
        paramsData: {},
        configModel: '',
        configNameList: [],
        formModel: {},
        reserveForm: {},
        datetimeModel: [],
        timeModel: '30000',
        timeInterModel: null,
        activeType: '2',
        open: false,
        title: '',
        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
        },
        groupData: '',
        groupList: [{value:'g1', label: '分组1'},{value:'g2', label: '分组2'}],
        pickerOptions: {
          shortcuts: [{
            text: '最近30分钟',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 0.5), new Date()]);}
          },{
            text: '最近1小时',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 1), new Date()]);}
          },{
            text: '最近3小时',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 3), new Date()]);}
          },{
            text: '最近6小时',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 6), new Date()]);}
          },{
            text: '最近12小时',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 12), new Date()]);}
          },{
            text: '最近24小时',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 24), new Date()]);}
          },{
            text: '最近2天',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 24 * 2), new Date()]);}
          },{
            text: '最近7天',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), new Date()]);}
          }, {
            text: '最近30天',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 24 * 30), new Date()]);}
          }, {
            text: '最近90天',
            onClick(picker) {picker.$emit('pick', [new Date(new Date().getTime() - 3600 * 1000 * 24 * 90), new Date()]);}
          }, {
            text: '最近6个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(new Date().getMonth() - 6);
              if (start.getDate() !== end.getDate()) {
                start.setDate(0);
              }
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近1年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(new Date().getMonth() - 12);
              if (start.getDate() !== end.getDate()) {
                start.setDate(0);
              }
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    created() {
      this.activeType = this.activeTypeOne;
      this.paramsData = this.$route && this.$route.query;
      this.configModel = this.paramsData && this.paramsData.id ? Number(this.paramsData.id) : '';
      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 = 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.groupData = this.paramsData && this.paramsData.groupId ? Number(this.paramsData.groupId) : Number(this.groupDataOne);
      // this.fnConfigName(this.groupDataOne);
      // if (this.configModel) {
      //   this.fnChartView();
      // }
      this.groupListData();
    },
    beforeDestroy() {
      clearInterval(this.timeInterModel);
      this.timeInterModel = null;
    },
    methods: {
      // 查询分组
      groupListData() {
        getMonitorGroup().then(res => {
          if (res && res.data) {
            let newVal = '';
            this.groupList = res && res.data.map((item,index) => {
              if (index === 0) {
                newVal = item.id;
              }
              return Object.assign({}, item, {value: item.id, label: item.name})
            });
            this.fnConfigName(this.groupData || newVal);
          }
        });
      },
      // 查询流量图
      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(groupId) {
        monitorConfigList({groupId: groupId}).then(res => {
          if (res && res.data) {
            this.configNameList = res && res.data;
            let index = 0;
            res && res.data.forEach(item => {
              if (item.id === this.configModel) {
                index = 1;
              }
            });
            if (index === 0 && this.configNameList.length > 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) {
        this.formModel = {};
        if (val === 'add') {
          this.title = '添加配置';
          this.open = true;
          // 使用$nextTick确保DOM更新完成后再初始化子组件
          this.$nextTick(() => {
            // 强制更新formModel，确保子组件能接收到
            this.formModel = {groupId: this.groupData};
          });
        } else if (val === 'edit') {
          this.title = '修改配置';
          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.reserveForm = {};
              this.lineDataParams = {};
              this.configModel = '';
              this.fnConfigName(this.groupData);
            });
          }).catch(() => {});
        }
      },
      // 时间选择器
      dateChange() {
        this.currTimeList = {startTime: this.datetimeModel[0], endTime: this.datetimeModel[1]};
        this.fnChartView({});
      },
      // 下拉值变化事件
      selectValChange(val) {
        this.fnChartView();
      },
      // 分组
      fnGroupChange(val) {
        // this.groupData
        this.configModel = '';
        this.fnConfigName(val);
      },
      addMonitor() {
        this.open = true;
      },
      fnDialogResult(res){
        this.open = false;
        if (res && res.type === 'submit') {
          this.groupListData();
        }
        // this.fnConfigName(this.groupData);
        // 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, groupData: this.groupData});
          }
        }
      },
      // 点击图表
      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 5px!important;
    width: 70px;
  }
  ::v-deep .el-input--suffix .el-input__inner {
    padding-right: 20px!important;
  }
  ::v-deep .el-input__suffix {
    right: 0!important;
  }
</style>
