<script setup lang="ts">
import * as echarts from 'echarts/core';
import {
  TitleComponent,
  TitleComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
} from 'echarts/components';
import {
  PieChart,
  PieSeriesOption,
  BarChart,
  BarSeriesOption,
} from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

import { markRaw, onMounted, ref } from 'vue';
import { origGet, top3Sel } from '@/api/faultManage/actAlarm';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';

const { t } = useI18n();

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  PieChart,
  BarChart,
  CanvasRenderer,
  LabelLayout,
]);

type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | PieSeriesOption
  | BarSeriesOption
>;

/**图DOM节点实例对象 */
const alarmTypeBar = ref<HTMLElement | undefined>(undefined);

/**图实例对象 */
const alarmTypeBarChart = ref<any>(null);

/**告警类型数据 */
const alarmTypeType = ref<any>([
  {
    value: 0,
    name: t('views.index.Critical'),
  },
  {
    value: 0,
    name: t('views.index.Major'),
  },
  {
    value: 0,
    name: t('views.index.Minor'),
  },
  {
    value: 0,
    name: t('views.index.Warning'),
  },
  // {
  //   value: 0,
  //   name: t('views.index.Event'),
  // },
]);

/**告警类型Top数据 */
const alarmTypeTypeTop = ref<any>([
  { name: 'AMF', value: 0 },
  { name: 'UDM', value: 0 },
  { name: 'SMF', value: 0 },
]);

//
function initPicture() {
  Promise.allSettled([origGet(), top3Sel()])
    .then(resArr => {
      if (resArr[0].status === 'fulfilled') {
        const res0 = resArr[0].value;
        if (res0.code === RESULT_CODE_SUCCESS && Array.isArray(res0.data)) {
          for (const item of res0.data) {
            let index = 0;
            switch (item.name) {
              case 'Critical':
                index = 0;
                break;
              case 'Major':
                index = 1;
                break;
              case 'Minor':
                index = 2;
                break;
              case 'Warning':
                index = 3;
                break;
              // case 'Event':
              //   index = 4;
              //   break;
            }
            alarmTypeType.value[index].value = Number(item.value);
          }
        }
      }
      if (resArr[1].status === 'fulfilled') {
        const res1 = resArr[1].value;
        if (res1.code === RESULT_CODE_SUCCESS && Array.isArray(res1.data)) {
          alarmTypeTypeTop.value = alarmTypeTypeTop.value
            .concat(res1.data)
            .sort((a: any, b: any) => {
              return b.value - a.value;
            })
            .slice(0, 3);
        }
      }
    })
    .then(() => {
      const optionData: EChartsOption = {
        title: [
          {
            show: false,
          },
          {
            text: t('views.dashboard.overview.alarmTypeBar.topTitle'),
            textStyle: {
              color: '#fff',
              fontSize: '14',
              fontWeight: 400,
            },
            top: '50%',
            left: '0%',
          },
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}',
        },
        legend: {
          orient: 'vertical',
          right: '2%',
          top: '12%',
          data: alarmTypeType.value.map((item: any) => item.name), //label数组
          textStyle: {
            color: '#A7D6F4', // 设置图例文字颜色
          },
        },
        grid: [
          {
            top: '60%',
            left: '15%',
            right: '25%',
            bottom: '10%',
          },
        ],
        series: [
          //饼图:
          {
            type: 'pie',
            radius: '35%',
            color: ['#f5222d', '#fa8c16', '#fadb14', '#1677ff', '#13c2c2'],
            label: {
              show: true,
              position: 'inner',
              formatter: (params: any) => {
                if (!params.value) return '';
                return `${params.value}`;
              },
            },
            labelLine: {
              show: false,
            },
            center: ['35%', '25%'],
            data: alarmTypeType.value,
            zlevel: 2, // 设置zlevel为1，使得柱状图在下层显示
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          //柱状
          {
            type: 'bar',
            barWidth: 12, // 柱子宽度
            barCategoryGap: '30%', // 控制同一系列的柱间距离
            label: {
              show: true,
              position: 'right', // 位置
              color: '#A7D6F4', //淡蓝色
              fontSize: 14,
              distance: 14, // label与柱子距离
              formatter: '{c}',
            },
            itemStyle: {
              borderRadius: [0, 20, 20, 0], // 圆角（左上、右上、右下、左下）
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#f0f5ff' },
                { offset: 0.5, color: '#adc6ff' },
                { offset: 1, color: '#2f54eb' },
              ]), // 渐变
            },
            data: alarmTypeTypeTop.value,
          },
        ],
        // 柱状图设置
        xAxis: [
          {
            splitLine: {
              show: false,
            },
            type: 'value',
            show: false,
          },
        ],
        yAxis: [
          {
            splitLine: {
              show: false,
            },
            axisLine: {
              //y轴
              show: false,
            },
            type: 'category',
            axisTick: {
              show: false,
            },
            inverse: true,
            data: alarmTypeTypeTop.value.map((item: any) => item.name),
            axisLabel: {
              color: '#A7D6F4',
              fontSize: 14,
            },
          },
        ],
      };

      fnDesign(alarmTypeBar.value, optionData);
    });
}

function fnDesign(container: HTMLElement | undefined, option: any) {
  if (!container) return;

  alarmTypeBarChart.value = markRaw(echarts.init(container, 'light'));
  option && alarmTypeBarChart.value.setOption(option);

  // 创建 ResizeObserver 实例
  var observer = new ResizeObserver(entries => {
    if (alarmTypeBarChart.value) {
      alarmTypeBarChart.value.resize();
    }
  });
  // 监听元素大小变化
  observer.observe(container);
}

onMounted(() => {
  initPicture();
});
</script>

<template>
  <div ref="alarmTypeBar" class="chart-container"></div>
</template>

<style lang="less" scoped>
.chart-container {
  /* 设置图表容器大小和位置 */
  width: 100%;
  height: 100%;
}
</style>
