<template>
  <div class="app-container">
    <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 @click="timeSelect(30)">1月</el-button>
      </el-form-item>
      <el-form-item label="" style="width: 308px;margin-right:10px">
        <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>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="12">
        <div ref="chartAccess" style="height: 600px;"></div>
      </el-col>
      <el-col :span="12">
        <template #header>
          <Tickets style="width: 1em; height: 1em; vertical-align: middle;"/>
          <span style="vertical-align: middle;">{{ title }}</span></template>
        <el-table v-loading="loading" :data="leftList" v-show="sl" border style="height:300px;overflow-y: auto;">
          <el-table-column label="序号" align="center" width="80">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="组件名称" align="left" prop="modelName"/>
          <el-table-column label="系统压力值TPS/QPS" align="center" prop="access" width="150"/>
          <el-table-column label="访问错误次数" align="center" prop="num" width="120"/>
        </el-table>

        <el-table v-loading="loading" :data="rightList" v-show="sr" border style="height:555px;overflow-y: auto;">
          <el-table-column label="序号" align="center" width="120">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="组件名称" align="left" prop="objName"/>
          <el-table-column label="告警数量" align="center" prop="num" width="120">
          <template #default="scope">
            <el-button link type="primary" @click="msDetail(scope.row)">{{ scope.row.num }}</el-button>
          </template>
          </el-table-column>
        </el-table>
        <div ref="asLine" v-show="axx" style="height: 400px;padding-top: 20px;"></div>
      </el-col>
    </el-row>

    <!-- 添加或修改应用程序管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <div ref="alarmMs" style="height: 250px;"></div>
      <el-table v-loading="loading" :data="msList" border style="height:500px;overflow-y: auto;">
        <!--          <el-table-column label="风险对象" align="left" prop="objName"/>-->
        <!--          <el-table-column label="风险指标" align="center" prop="metricsName"/>-->
        <el-table-column label="序号" align="center" width="120">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="指标名称" align="center" prop="metricsName"/>
        <el-table-column label="风险级别" align="center" prop="alarmLevel">
          <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">
          <template #default="scope">
            <span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d} {h}:{mi}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import {calcMs,getBizAccess} from "@/api/alarm/record";
import {useRoute, useRouter} from "vue-router";
import * as echarts from "echarts";
import moment from "moment";
import {getObjAccess, getObjAlarm} from "../../../api/alarm/record.js";

const {proxy} = getCurrentInstance();
const {alarm_level} = proxy.useDict('alarm_level');
const {biz_type} = proxy.useDict('biz_type');
const {alarm_type} = proxy.useDict('alarm_type');
const leftList = ref([]);
const rightList = ref([]);
const open = ref(false);
const sl = ref(true);
const axx = ref(true);
const sr = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const msList = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAlarmTime = ref([]);
const router = useRouter();
const route = useRoute();
const chartAccess = ref();
const asLine = ref();
const alarmMs = ref();

const data = reactive({
  form: {},
  queryParams: {
    start: null,
    end: null,
    modeId: null
  },
});

function handleDetails(row) {
  console.log(row, router)
}
function msDetail(row) {
  open.value = true;
  title.value = "[" + row.objName + "]详情";
  let msParams = {
    objId: row.objId,
    params: {}
  };
  if (null != daterangeAlarmTime && '' != daterangeAlarmTime) {
    msParams.params["beginAlarmTime"] = daterangeAlarmTime.value[0];
    msParams.params["endAlarmTime"] = daterangeAlarmTime.value[1];
  }

  console.error(msParams)
  calcMs(msParams).then(response => {
    initMs(response.data.hour);
    msList.value = response.data.detail;
  });
}
const {queryParams, form} = toRefs(data);

function initChart(res) {
  let myChart = echarts.init(chartAccess.value);
  let img = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/PjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+PHN2ZyB0PSIxNjUzOTAwNTEzMjYyIiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjIxNjkiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCI+PGRlZnM+PHN0eWxlIHR5cGU9InRleHQvY3NzIj5AZm9udC1mYWNlIHsgZm9udC1mYW1pbHk6IGZlZWRiYWNrLWljb25mb250OyBzcmM6IHVybCgiLy9hdC5hbGljZG4uY29tL3QvZm9udF8xMDMxMTU4X3U2OXc4eWh4ZHUud29mZjI/dD0xNjMwMDMzNzU5OTQ0IikgZm9ybWF0KCJ3b2ZmMiIpLCB1cmwoIi8vYXQuYWxpY2RuLmNvbS90L2ZvbnRfMTAzMTE1OF91Njl3OHloeGR1LndvZmY/dD0xNjMwMDMzNzU5OTQ0IikgZm9ybWF0KCJ3b2ZmIiksIHVybCgiLy9hdC5hbGljZG4uY29tL3QvZm9udF8xMDMxMTU4X3U2OXc4eWh4ZHUudHRmP3Q9MTYzMDAzMzc1OTk0NCIpIGZvcm1hdCgidHJ1ZXR5cGUiKTsgfQo8L3N0eWxlPjwvZGVmcz48cGF0aCBkPSJNNTEyIDBoMzJ2MTYwaC0zMnpNNTEyIDI1NmgzMnYxNjBoLTMyek01MTIgNTEyaDMydjE2MGgtMzJ6TTUxMiA3NjhoMzJ2MTYwaC0zMnoiIGZpbGw9IiNkODFlMDYiIHAtaWQ9IjIxNzAiPjwvcGF0aD48L3N2Zz4=";
  let datas = [];
  let legendData1 = [];
  let legendData2 = [];
  let xMax1 = 50;
  let xMax2 = 50;

  for (let i in res.data) {
    let obj = res.data[i];
    datas.push(obj.modelName);
    legendData1.push({id: obj.modelId, value: obj.access});
    legendData2.push({id: obj.modelId, value: obj.num});
    if (i == 0) {
      dl(obj.modelId, obj.modelName);
    }
    if (obj.access > xMax1) {
      xMax1 = obj.access;
    }
    if (obj.num > xMax2) {
      xMax2 = obj.num;
    }
  }
  let dataheng = [xMax1 + 2, xMax1 + 2, xMax1 + 2, xMax1 + 2, xMax1 + 2];
  let option = {
    backgroundColor: '#fff',
    tooltip: {
      show: true,
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(210,219,238,0.2)',
        },
      },
    },
    legend: {},
    grid: [{
      show: false,
      left: '0',
      top: 0,
      bottom: 22,
      width: '15%',
    },
      {
        containLabel: true,
        top: 0,
        left: '20%',
        bottom: '0%',
        width: '40%',
        show: false
      },
      {
        left: '64%',
        right: '10%',
        top: 0,
        bottom: '0%',
        containLabel: true,
        show: false
      },
    ],
    xAxis: [{
      gridIndex: 0,
      show: false,
    },
      {
        gridIndex: 1,
        show: false,
        max: xMax1,
      },
      {

        gridIndex: 2,
        show: false,
        max: xMax2,
      },
    ],
    yAxis: [{
      gridIndex: 0,
      type: 'category',
      inverse: true,
      position: 'right',
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      data: datas.map(function (value) {
        return {
          value: value,
          textStyle: {
            align: 'right',
          },
        };
      }),
      axisLabel: {
        fontSize: 14,
        align: 'left',
        rich: {
          a: {
            color: '#fff',
            backgroundColor: '#49a2ff',
            width: 24,
            height: 24,
            align: 'center',
            borderRadius: 3,
          },
          a1: {
            color: '#fff',
            backgroundColor: '#f5576c',
            width: 24,
            height: 24,
            align: 'center',
            borderRadius: 3,
          },
          a2: {
            color: '#fff',
            backgroundColor: '#fee140',
            width: 24,
            height: 24,
            align: 'center',
            borderRadius: 3,
          },
          a3: {
            color: '#fff',
            backgroundColor: '#96fbc4',
            width: 24,
            height: 24,
            align: 'center',
            borderRadius: 3,
          },
          b: {
            color: '#333',
            width: 100,
            height: 30,
            align: 'right',
          },
        },
        formatter: function (params) {
          let index = datas.map((item) => item).indexOf(params);
          index = index + 1;
          if (index < 4) {
            return [`{a${index}|${index}}{b|${params}}`].join('\n');
          } else {
            return [`{a|${index}}{b|${params}}`].join('\n');
          }
        },
      },
    },
      {
        inverse: true,
        gridIndex: 1,
        data: datas,
        // max:10,
        axisLabel: {
          // margin: 80,
          show: false
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisPointer: {
          label: {
            show: false,
            margin: 30,
          },
        },
      },
      {
        gridIndex: 2,
        inverse: true,
        data: datas,
        //   max:10,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        axisPointer: {
          label: {
            show: false,
            margin: 30,
          },
        },
      },
    ],
    series: [{
      type: 'bar',
      name: '系统压力值（次）',
      stack: '2',
      barWidth: 20,
      z: 10,
      barCategoryGap: 15,
      // barGap:i==1?'-100%':'0',
      xAxisIndex: 1,
      yAxisIndex: 1,
      itemStyle: {
        color: '#419491',
        barBorderRadius: [0, 10, 10, 0],
        // barBorderRadius: legendData[i].barBorderRadius,
        emphasis: {
          color: '#419491',
        },
      },
      // 数字
      label: {
        show: true,
        position: 'inside',
        right: 0,
        color: '#fff',
        formatter: function (params) {
          if (params.value == 0) {
            return '';
          } else {
            return params.value;
          }
        },
      },
      data: legendData1,
    },
      //虚线
      {
        name: '',
        type: 'pictorialBar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        symbolSize: [7, 30],
        symbolOffset: [15, 0],
        symbol: 'image://' + img,
        symbolPosition: 'end',
        barWidth: "20",
        z: 12,
        color: '#fe5959',
        data: dataheng,
        tooltip: {
          show: false,
        },
      },
      //右边的柱状图
      {
        xAxisIndex: 2,
        yAxisIndex: 2,
        type: 'bar',
        name: '告警数量（次）',
        stack: '3',
        barWidth: 30,
        barCategoryGap: 15,
        // barGap:i==1?'-100%':'0',
        itemStyle: {
          color: '#FFB25C',
          barBorderRadius: [0, 20, 20, 0],
          emphasis: {
            color: '#FFB25C',
          },
        },
        // 数字
        label: {
          normal: {
            color: '#000',
            show: true,
            position: 'right',
            distance: 4,
            textStyle: {
              fontSize: 16,
            },
            formatter: '{c}',
          },
        },
        data: legendData2,
      },
    ],
  };
  // 3.配置项和数据给实例化对象
  myChart.setOption(option);
  myChart.on("click", function (param) {
    if (param.seriesIndex == 0) {
      dl(param.data.id, param.name);
    } else {
      dr(param.data.id, param.name);
    }
    console.log(param);
    // console.error(param,param.data.id,param.data.value,param.name);
    // let url = '/zabbix/zabbix.php?action=map.view&sysmapid=2&kiosk=1&line';
  });
}

function initMs(res) {
  let myChart = echarts.init(alarmMs.value);
  let yd = [];
  let xd = [];
  for (let i = 0; i < res.length; i++) {
    xd.push(res[i].hour);
    yd.push(res[i].num);
  }
  let ss = [];
  let xx = {
    // name: xd,
    type: 'line',
    data: yd,
    symbolSize: 1,
    symbol: 'circle',
    smooth: true,
    showSymbol: false,
  }
  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 dl(modelId, name) {
  title.value = "[" + name + "] 组件压力排行";
  sl.value = true;
  axx.value = true;
  sr.value = false;
  queryParams.value.modelId = modelId;
  queryParams.value.params = {};
  if (null != daterangeAlarmTime && '' != daterangeAlarmTime) {
    queryParams.value.start = daterangeAlarmTime.value[0];
    queryParams.value.end = daterangeAlarmTime.value[1];
  }
  getObjAccess(queryParams.value).then(response => {
    loading.value = false;
    leftList.value = response.data.objs;
    line(response.data.datas);
  });

}

function dr(modelId, name) {
  title.value = "[" + name + "] 组件告警数量排行";
  sl.value = false;
  axx.value = false;
  sr.value = true;
  queryParams.value.modelId = modelId;
  queryParams.value.params = {};
  if (null != daterangeAlarmTime && '' != daterangeAlarmTime) {
    queryParams.value.start = daterangeAlarmTime.value[0];
    queryParams.value.end = daterangeAlarmTime.value[1];
  }
  getObjAlarm(queryParams.value).then(response => {
    loading.value = false;
    rightList.value = response.data;
  });

}

function line(data) {
  let myChart = echarts.init(asLine.value);
  let colorList = [
    '#419491',
    '#3581F8',
    '#FFB25C',
  ];
  let x_data = [];
  let max_data = [];
  let avg_data = [];
  let err_data = [];
  for (let i = 0; i < data.length; i++) {
    x_data.push(data[i].time);
    max_data.push(data[i].max);
    avg_data.push(data[i].avg);
    err_data.push(data[i].error);
  }
  let option = {
    backgroundColor: '#FFFFFF',
    dataZoom: {
      type: 'inside', // 内置型数据区域缩放组件
      start: 0, // 默认为0，表示从头开始
      end: 50 // 默认为100，表示直到末尾
    },
    title: {
      show: true,
      text: '系统压力值趋势',
      // subtext:'分配总量：18041核\n释放总量：5288核',
      // textStyle: {
      //   fontFamily: 'PingFangSC-Regular, PingFang SC',
      //   fontSize: 14,
      //   fontWeight: 400,
      //   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
      }
    }],
    yAxis: [{
      type: 'value',
      // name: "核数",
      // position: 'left',
      // offset: 55,
      axisTick: {
        show: false
      },
      axisLine: {
        show: false,
      },
      axisLabel: {
        fontSize: 12,
        textStyle: {
          color: '#B7C3CE'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed"
        }
      }
    }],
    series: [{
      name: '最大值',
      type: 'line',
      data: max_data,
      symbolSize: 1,
      symbol: 'circle',
      smooth: true,
      showSymbol: false,
      lineStyle: {
        width: 1,
        type: 'dotted', //'dotted'虚线 'solid'实线
      },
      itemStyle: {
        normal: {
          color: colorList[0],
          borderColor: colorList[0]
        }
      }
    }, {
      name: '平均值',
      type: 'line',
      data: avg_data,
      symbolSize: 1,
      symbol: 'circle',
      smooth: true,
      showSymbol: false,
      lineStyle: {
        width: 1,
      },
      itemStyle: {
        normal: {
          color: colorList[1],
          borderColor: colorList[1]
        }
      }
    },
      {
        name: '错误次数',
        type: 'line',
        data: err_data,
        symbolSize: 1,
        symbol: 'circle',
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1,
        },
        itemStyle: {
          normal: {
            color: colorList[2],
            borderColor: colorList[2]
          }
        }
      }
    ]
  };
  myChart.setOption(option);
}

/** 查询告警记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAlarmTime && '' != daterangeAlarmTime) {
    queryParams.value.start = daterangeAlarmTime.value[0];
    queryParams.value.end = daterangeAlarmTime.value[1];
  }
  getBizAccess(queryParams.value).then(response => {
    // recordList.value = response.rows;
    // total.value = response.total;
    loading.value = false;
    initChart(response);
  });
}


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

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 resetQuery() {
  daterangeAlarmTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

if (route.query.today) {
  timeSelect(0);
} else {
  timeSelect(30);
}
getList();
</script>
