<template>
  <div class="app-container">
    <template v-if="activeType === '1'">
      <div class="w100" style="height: 60px;">
        <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 v-if="checkPermi(['resource:monitorBoard:view'])" :type="activeType === '2' ? 'primary' : ''" @click="viewMonitorChart('2')">详情视图</el-button>
        </div>
      </div>
      <div style="height: calc(100% - 60px);" class="w100">
        <div class="w50 disInlineBlock plr-10 mtb10" style="height: 200px;vertical-align: middle;">
          <div class="w100 h100" style="border: 1px solid #e8e8e8;display: flex;justify-content: center;align-items: center;flex-direction: column;">
            <el-button type="primary" icon="el-icon-plus" plain circle @click="addMonitor"></el-button>
            <div style="font-size: 1rem;margin-top: 5px;">新增监控配置</div>
          </div>
        </div>
        <div v-for="(chartItem, key, index) of lineDataParams" class="w50 disInlineBlock plr-10 mtb10" style="height: 200px;vertical-align: middle;">
          <div class="w100 h100" style="border: 1px solid #e8e8e8; padding: 10px 10px 2px;">
            <div class="w100" style="height: 20px">
              <span>{{chartItem && chartItem.rmMonitorConfig && chartItem.rmMonitorConfig.configName}}</span>
              <el-dropdown trigger="click" style="float: right;" @command="(command) => handleCommand(command, key, chartItem)">
              <span class="el-dropdown-link">
                <i class="el-icon-more" style="transform: rotate(90deg);"></i>
              </span>
                <el-dropdown-menu slot="dropdown">
                  <template v-for="item of btnList">
                    <el-dropdown-item :command="item" class="clearfix" v-if="item && item.hasPermi ? checkPermi([item.hasPermi]) : true">
                      {{item.title}}
                    </el-dropdown-item>
                  </template>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="w100" style="height: calc(100% - 20px)">
              <EchartsLine :lineData="chartItem && chartItem.echartList || {}" :title="chartItem && chartItem.echartList && chartItem.echartList.title || ''"  class="w100 h100" :chartData="(valData, unit) => chartDataEvent(valData, key, unit)"></EchartsLine>
            </div>
          </div>
        </div>
      </div>
      <!--    弹窗  -->
      <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
        <dialogMonitor :formModel="formModel" @dialogResult="fnDialogResult"></dialogMonitor>
      </el-dialog>
    </template>
    <template v-else>
      <monitorBoardView :timeModelOne="timeModel" :datetimeModelOne="datetimeModel" :activeType="activeType" @activeTypeChange="fnActiveTypeChange"></monitorBoardView>
    </template>
  </div>
</template>

<script>
  import dialogMonitor from './dialogMonitor';
  import monitorBoardView from './monitorBoardView';
  import EchartsLine from "@/components/echartsList/line.vue";
  import {monitorViewChart, delMonitorConfig} from "@/api/disRevenue/resource";
  import { checkPermi } from "@/utils/permission";
  export default {
    name: "monitor-board",
    components: {dialogMonitor,monitorBoardView, EchartsLine},
    props: {
      timeModelDefault: {
        type: String,
        default: '30000'
      },
      datetimeModelDefault: {
        type: Array,
        default: () => []
      },
      activeTypeDefault: {
        type: String,
        default: '1'
      }
    },
    data() {
        return {
          formModel: {},
          currTimeList: {},
          datetimeModel: [],
          timeModel: '30000',
          timeInterModel: null,
          open: false,
          title: '',
          activeType: '1',
          timeModelOptions: [
            {value: '30000', label: '30s刷新'},
            {value: '10000', label: '10s刷新'},
            {value: '0', label: '不刷新'},
          ],
          echartData: {
            title: ' ',
            yAxisName: ' ',
            unitModel: 'Kb',
            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', hasPermi: 'resource:monitorBoard:view'}, {title: '修改', value: 'edit'}, {title: '删除', value: 'del'}],
        }
    },
    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 = this.datetimeModelDefault && this.datetimeModelDefault.length > 0 ? {startTime: this.datetimeModelDefault[0], endTime: this.datetimeModelDefault[1]} : {startTime: startData, endTime: endData};
      this.datetimeModel = this.datetimeModelDefault && this.datetimeModelDefault.length > 0 ? this.datetimeModelDefault : [startData, endData];
      this.fnChartView({});
    },
    beforeDestroy() {
      clearInterval(this.timeInterModel);
      this.timeInterModel = null;
    },
    methods: {
      checkPermi,
      // 查询流量图
      fnChartView(unitVal,keyName) {
        this.$modal.loading();
        monitorViewChart(Object.assign({}, this.currTimeList, unitVal)).then(res => {
          let dataList = {};
          res && res.data.forEach(item => {
            let chart = JSON.parse(JSON.stringify(this.echartData));
            let modelVal = item.rmMonitorConfig;
            dataList[modelVal.configName + '_' + modelVal.id] = item;
            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 || [];
            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';
              }
            }
            chart.dataList[0].data = item && item.yData  && item.yData.netInSpeedData || [];
            chart.dataList[1].data = item && item.yData  && item.yData.netOutSpeedData || [];
            dataList[modelVal.configName + '_' + modelVal.id]['echartList'] = chart;
          });
          if (keyName) {
            this.$set(this.lineDataParams, keyName, dataList[keyName]);
          } else {
            if (dataList && Object.keys(dataList).length > 0) {
              this.lineDataParams = {...dataList};
            } else {
              this.lineDataParams['one'] = {
                echartList: this.echartData
              };
            }
          }
          this.$modal.closeLoading();
          // 循环定时查询
          this.fnTimeInter(this.timeModel);
        }).catch(() => {
          this.$modal.closeLoading();
          // 循环定时查询
          this.fnTimeInter(this.timeModel);
        });
      },
      // 时间选择器
      dateChange() {
        this.currTimeList = {startTime: this.datetimeModel[0], endTime: this.datetimeModel[1]};
        this.fnChartView({});
      },
      // 定时刷新下拉
      fnTimeInter(val) {
        clearInterval(this.timeInterModel);
        this.timeInterModel = null;
        if (val !== '0') {
          this.timeInterModel = setInterval(() => {
            this.fnChartView();
          }, Number(val));
        }
      },
      addMonitor() {
        this.title = '添加配置';
        this.open = true;
        // 使用$nextTick确保DOM更新完成后再初始化子组件
        this.$nextTick(() => {
          // 强制更新formModel，确保子组件能接收到
          this.formModel = {};
        });
      },
      // 弹窗关闭
      fnDialogResult(res){
        // 新增或编辑操作时
        if (res && res.type === 'submit') {
          this.fnChartView({});
        }
        this.open = false;
      },
      // 右上角点击详细视图
      viewMonitorChart(val) {
        this.activeType = val;
        clearInterval(this.timeInterModel);
        this.timeInterModel = null;
      },
      // 子页面点击切换返回该页面
      fnActiveTypeChange(val) {
        this.timeModel = val && val.timeModel;
        this.activeType = val && val.activeType;
        this.datetimeModel = val && val.datetimeModel;
        this.fnChartView({});
      },
      // 右侧点击下拉按钮
      handleCommand(val, chartKey, chartVal) {
        this.formModel = {};
        if (val && val.value === 'del') {
          delMonitorConfig(chartVal.rmMonitorConfig.id).then(res => {
            this.fnChartView({});
          });
        } else if (val && val.value === 'edit') {
          this.title = '修改配置';
          this.open = true;
          // 使用$nextTick确保DOM更新完成后再初始化子组件
          this.$nextTick(() => {
            // 强制更新formModel，确保子组件能接收到
            this.formModel = chartVal && chartVal.rmMonitorConfig;
          });
        } else if (val && val.value === 'view') {
          this.$router.push({
            path: '/resource/monitorBoard/view',
            query: {id: chartVal.rmMonitorConfig.id}
          });
        }
      },
      chartDataEvent(valData, keyName, unit) {
        if (unit) {
          let params = {unit: unit, monitorId: this.lineDataParams[keyName].rmMonitorConfig.id};
          this.fnChartView(params,keyName);
        }
      }
    }
  }
</script>

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