<template>
  <div class="app-container">
    <template v-if="activeType === '1'">
      <div class="w100" style="height: 60px;">
        <div class="disInlineBlock" style="width: 210px;">
          <span style="display: inline-block;font-size: 14px;font-weight: 600;">分组：</span>
          <el-select v-model="groupData" placeholder="请选择" style="width: calc(100% - 52px);margin-right: 10px;" @change="fnGroupChange">
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </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 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 || ''"
                           :dateDataTrans="chartItem && chartItem.dateDataTrans || {}" :dateShowType="chartItem && chartItem.dateShowType || 'datetimerange'"
                           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" :activeTypeOne="activeType" :groupDataOne="groupData" @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, getMonitorGroup} 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',
            gridRight: '40px',
            gridBotm: '15%',
            lineXData: [],
            dataList: [
              {name: '入方向总流量', data: []},
              {name: '出方向总流量', data: []}
            ]
          },
          lineDataParams: {},
          btnList: [{title: '详情', value: 'view', hasPermi: 'resource:monitorBoard:view'}, {title: '修改', value: 'edit'}, {title: '删除', value: 'del'}],
          groupData: '',
          groupList: [],
          timesMap: {},
          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() {
      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.currTimeList = {startTime: startData, endTime: endData};
      this.datetimeModel = [startData, endData];
      this.groupListData();
    },
    beforeDestroy() {
      clearInterval(this.timeInterModel);
      this.timeInterModel = null;
    },
    methods: {
      checkPermi,
      // 更新当前售时间
      updateTimes() {
        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.datetimeModel = [startData,endData];
        this.timesMap = {};
      },
      // 查询分组
      groupListData(groupId) {
        getMonitorGroup().then(res => {
          if (res && res.data) {
            this.groupList = res && res.data.map((item,index) => {
              if (index === 0) {
                this.groupData = groupId || item.id;
              }
              return Object.assign({}, item, {value: item.id, label: item.name})
            });
          }
          this.fnChartView(this.currTimeList, null, null, groupId || this.groupData);
        });
      },
      // 查询流量图
      fnChartView(times, unitVal,keyName, groupId) {
        // this.$modal.loading();
        let groupObj = {};
        if (groupId) {
          groupObj = {groupId: groupId};
        }
        monitorViewChart(Object.assign({}, times, unitVal, groupObj)).then(res => {
          let dataList = {};
          res && res.data.forEach(item => {
            let chart = JSON.parse(JSON.stringify(this.echartData));
            let modelVal = item.rmMonitorConfig;
            item['dateShowType'] = 'datetimerange';
            item['dateDataTrans'] = {transList: true, dateRange: [times.startTime, times.endTime], pickerOptions: this.pickerOptions};
            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};
            }
          }
          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(this.currTimeList);
      // },
      // 分组
      fnGroupChange() {
        this.updateTimes();
        this.fnChartView(this.currTimeList, null, null, this.groupData);
      },
      // 定时刷新下拉
      fnTimeInter(val) {
        clearInterval(this.timeInterModel);
        this.timeInterModel = null;
        if (val !== '0') {
          this.timeInterModel = setInterval(() => {
            this.updateTimes();
            this.fnChartView(this.currTimeList, null, null, this.groupData);
          }, Number(val));
        }
      },
      addMonitor() {
        this.title = '添加配置';
        this.open = true;
        // 使用$nextTick确保DOM更新完成后再初始化子组件
        this.$nextTick(() => {
          // 强制更新formModel，确保子组件能接收到
          this.formModel = {groupId: this.groupData};
        });
      },
      // 弹窗关闭
      fnDialogResult(res){
        this.updateTimes();
        // 新增或编辑操作时
        if (res && res.type === 'submit') {
          this.groupListData(this.groupData);
          // this.fnChartView(this.currTimeList, null, null, this.groupData);
        }
        this.open = false;
      },
      // 右上角点击详细视图
      viewMonitorChart(val) {
        this.activeType = val;
        clearInterval(this.timeInterModel);
        this.timeInterModel = null;
      },
      // 子页面点击切换返回该页面
      fnActiveTypeChange(val) {
        this.updateTimes();
        this.timeModel = val && val.timeModel;
        this.activeType = val && val.activeType;
        this.datetimeModel = val && val.datetimeModel;
        this.groupData = val && val.groupData;
        this.groupListData(this.groupData);
        // this.fnChartView(this.currTimeList);
      },
      // 右侧点击下拉按钮
      handleCommand(val, chartKey, chartVal) {
        this.formModel = {};
        if (val && val.value === 'del') {
          this.updateTimes();
          delMonitorConfig(chartVal.rmMonitorConfig.id).then(res => {
            this.fnChartView(this.currTimeList, null, null, this.groupData);
          });
        } 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, groupId: this.groupData}
          });
        }
      },
      chartDataEvent(valData, keyName, unit) {
        if (valData && valData.timeArr) {
          let timeList = {startTime: valData.timeArr[0], endTime: valData.timeArr[1]};
          let params = {monitorId: this.lineDataParams[keyName].rmMonitorConfig.id};
          if (unit) {
            params['unit'] = unit;
          }
          this.$set(this.timesMap, keyName, timeList);
          this.fnChartView(timeList,params,keyName);
        }
      }
    }
  }
</script>

<style scoped>
  .el-button--medium {
    padding: 10px 14px!important;
  }
  ::v-deep .el-range-editor.el-input__inner {
    margin-top: -35px!important;
    margin-right: 15px!important;
  }
</style>
