<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="16">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="0">
          <el-form-item>
            <el-button type="primary" plain @click="timeSelect(0)">今天</el-button>
            <el-button type="primary" plain @click="timeSelect(3)">3天</el-button>
            <el-button type="primary" plain @click="timeSelect(7)">7天</el-button>
            <el-button type="primary" :plain="false" @click="timeSelect(30)">1月</el-button>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker
                v-model="daterangeAlarmTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="objId" style="margin-right:10px">
            <el-select v-model="queryParams.objId" placeholder="请选择告警对象" style="width: 260px" clearable
                       filterable remote reserve-keyword :remote-method="remoteMethod">
              <el-option
                  v-for="dict in objList"
                  :key="dict.objId"
                  :label="dict.objName"
                  :value="dict.objId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="alarmLevel" style="margin-right:10px">
            <el-select v-model="queryParams.alarmType" placeholder="风险状态" clearable style="width:100px;">
              <el-option
                  v-for="dict in alarm_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-right:10px">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="10">
        <el-card>
          <div ref="alarmLeft" style="height: 190px;"></div>
        </el-card>
      </el-col>
      <el-col :span="14" style="text-align: right">
        <el-card>
          <div ref="alarmRight" style="height: 190px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-table ref="recordRef" v-loading="loading" :data="recordList" border :default-sort="defaultSort"
              @sort-change="handleSortChange">
      <!--      <el-table-column label="告警ID" align="left" prop="alarmId" width="80"/>-->
      <el-table-column label="风险对象" align="left" prop="objName" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="风险指标" align="center" prop="metricsName"/>
      <el-table-column label="风险级别" align="center" prop="alarmLevel" sortable="custom"
                       :sort-orders="['descending', 'ascending']">
        <template #default="scope">
          <dict-tag :options="alarm_level" :value="scope.row.alarmLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="风险状态" align="center" prop="alarmType">
        <template #default="scope">
          <dict-tag :options="alarm_type" :value="scope.row.alarmType"/>
        </template>
      </el-table-column>
      <el-table-column label="风险值" align="center" prop="alarmValue" :formatter="rounding"/>
      <el-table-column label="事件时间" align="center" prop="alarmTime" width="220" sortable="custom"
                       :sort-orders="['descending', 'ascending']">
        <template #default="scope">
          <span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d} {h}:{mi}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup name="Record">
import {getLevelSort, listHours, listRecord} from "@/api/alarm/record";
import {listObj} from "@/api/obj/obj.js"
import * as echarts from 'echarts'
import moment from 'moment'

const {proxy} = getCurrentInstance();
const {alarm_level} = proxy.useDict('alarm_level');
const {alarm_type} = proxy.useDict('alarm_type');

const recordList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAlarmTime = ref([]);
const objList = ref([]);
const alarmLeft = ref();
const alarmRight = ref([]);
const defaultSort = ref({prop: "alarmTime", order: "descending"});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    objId: null,
    objMetricsId: null,
    alarmLevel: null,
    alarmTime: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

function remoteMethod(keyword) {
  listObj({pageNum: 1, pageSize: 5, objName: keyword}).then(res => {
    objList.value = res.rows
  })
}

function left() {
  let myChart = echarts.init(alarmLeft.value);
  getLevelSort(queryParams.value).then(res => {
    console.log(res);
    const d_data = [];
    for (let i = 0; i < res.data.length; i++) {
      let d = {value: res.data[i].num, name: res.data[i].name}
      d_data.push(d);
    }
    let legend_style = {
      rich: {
        a: {
          fontFamily: 'PingFangSC-Regular, PingFang SC',
          color: '#4F5860',
          fontSize: 12
        },
        b: {
          fontFamily: 'Arial Black',
          color: '#4F5860',
          fontWeight: 600,
          fontSize: 12
        }
      }
    };
    let option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      title: {
        show: true,
        text: '风险级别统计',
        textStyle: {
          fontFamily: 'PingFangSC-Regular, PingFang SC',
          align: 'center',
          color: '#515961',
          fontSize: 18,
        },
      },
      legend: [{
        icon: 'circle',
        zlevel: 1,
        top: '20%',
        right: '25%',
        itemWidth: 20,
        itemHeight: 20,
        itemGap: 20,
        orient: "vertical", // 图例列表的布局朝向。 'horizontal'  'vertical'
        textStyle: legend_style,
        data: d_data,
        formatter: view_legend,
      }
      ],
      series: [{
        name: '告警数量',
        type: 'pie',
        left: '-45%',
        radius: ['35%', '85%'],
        // color: color_list,
        label: {
          show: false,
        },
        data: d_data
      }]
    };
    myChart.setOption(option);

    function view_legend(name) {
      let x_data;
      let total = 0;
      for (let i in d_data) {
        total += d_data[i].value;
        if (d_data[i].name == name) {
          x_data = d_data[i];
          // console.log(d_data[i])
        }
      }
      let percent = (x_data.value * 100 / total).toFixed(2);
      return '{a|' + name + '} {b|' + percent + '%}     {c|' + x_data.value + '}次';
    }
  })

}

function right() {
  let myChart = echarts.init(alarmRight.value);
  listHours(queryParams.value).then(res => {
    let yd=[];
    let xd=[];
    for (let i = 0; i < res.data.length; i++) {
      xd.push(res.data[i].hour);
      yd.push(res.data[i].num);
    }
    let ss = [];
      let xx = {
        // name: xd,
        type: 'line',
        data: yd,
        symbolSize: 1,
        symbol: 'circle',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1,
          type: 'solid', //'dotted'虚线 'solid'实线
        },
        itemStyle: {
        	normal: {
        		color: '#FFB25C',
        		borderColor: '#FFB25C'
        	}
        }
      }
      ss.push(xx);
    let x_data = xd;
    let option = {
      backgroundColor: '#FFFFFF',
      dataZoom: {
        type: 'inside', // 内置型数据区域缩放组件
        start: 0, // 默认为0，表示从头开始
        end: 100 // 默认为100，表示直到末尾
      },
      title: {
        show: true,
        text: '告警趋势',
        // textStyle: {
        //   fontFamily: 'PingFangSC-Regular, PingFang SC',
        //   fontSize: 16,
        //   fontWeight: 600,
        //   color: '#848E98'
        // },
        left: 'left',
        // top: '3%'
      },
      legend: {
        icon: 'rect',
        top: '3%',
        right: '10%',
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 20,
        textStyle: {
          fontFamily: 'PingFangSC-Regular, PingFang SC',
          color: '#848E98'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          label: {
            show: true,
            backgroundColor: '#fff',
            color: '#556677',
            borderColor: 'rgba(0,0,0,0)',
            shadowColor: 'rgba(0,0,0,0)',
            shadowOffsetY: 0
          },
          lineStyle: {
            width: 0
          }
        },
        backgroundColor: '#fff',
        textStyle: {
          color: '#5c6c7c'
        },
        padding: [10, 10],
        extraCssText: 'box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)'
      },
      grid: {
        top: '18%'
      },
      xAxis: [{
        type: 'category',
        data: x_data,
        axisLine: {
          show: false,
          lineStyle: {
            color: '#000000'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 'auto',
          rotate: 45,
          textStyle: {
            color: '#B7C3CE'
          },
          // 默认x轴字体大小
          fontSize: 12,
          // margin:文字到x轴的距离
          margin: 5,
          hideOverlap: true // 隐藏部分标签避免重叠
        }
      }],
      yAxis: [{
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
        },
        axisLabel: {
          fontSize: 12,
          textStyle: {
            color: '#B7C3CE'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed"
          }
        }
      }],
      series: ss
    };
    myChart.setOption(option)
  });
}

/** 查询告警记录列表 */
function getList() {


  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAlarmTime && '' != daterangeAlarmTime) {
    queryParams.value.params["beginAlarmTime"] = daterangeAlarmTime.value[0];
    queryParams.value.params["endAlarmTime"] = daterangeAlarmTime.value[1];
  }
  if (queryParams.value.orderByColumn == null || queryParams.value.orderByColumn == '') {
    queryParams.value.orderByColumn = defaultSort.value.prop;
    queryParams.value.isAsc = defaultSort.value.order;
  }
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    left();
    right();
  });
}

function timeSelect(v) {
  let end = new Date();
  let start = new Date().setDate(end.getDate() - v);
  daterangeAlarmTime.value[0] = moment(start).format('YYYY-MM-DD');
  daterangeAlarmTime.value[1] = moment(end).format('YYYY-MM-DD');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeAlarmTime.value = [];
  proxy.resetForm("queryRef");
  proxy.$refs["recordRef"].sort(defaultSort.value.prop, defaultSort.value.order);
  handleQuery();
}

/** 保留2位小数*/
function rounding(row, column) {
  return parseFloat(row[column.property]).toFixed(2)
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
}
timeSelect(30);
getList();
</script>
