<template>
  <div>
    <div class="algo-header">
      <span class="algo-tit">算法数据分析</span>
      <CensusTabs @check-tab="onCheckTab" />
    </div>
    <el-divider />
    <div style="flex-grow: 1; display: flex">
      <v-chart
        ref="myChart"
        class="chart"
        :option="option"
        @highlight="handleHighlight"
        @downplay="handleDownPlay"
        @click="handleClickChart"
        @mouseover="handleMouseOver"
        @mouseout="handleMouseOut" />
      <el-divider direction="vertical" border-style="solid" />
      <div class="stat-show">
        <ViolationStatItem :data="getVioStatData(0)" class="stat-data" />
        <div class="stat-divider"></div>
        <ViolationStatItem :data="getVioStatData(1)" class="stat-data" />
        <ViolationStatItem :data="getVioStatData(2)" class="stat-data" />
        <div class="stat-divider"></div>
        <ViolationStatItem :data="getVioStatData(3)" class="stat-data" /> </div
    ></div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, onMounted } from 'vue';
  import CensusTabs from './AlgoCensusTabs.vue';
  import ViolationStatItem from './ViolationStatItem.vue';
  import { TimeTabEnum, violationHandleCounts } from '../types';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { PieChart } from 'echarts/charts';
  import { TooltipComponent, LegendComponent, TitleComponent } from 'echarts/components';
  import { ViolationCount } from '@/api/home/home.ts';
  import VChart from 'vue-echarts';
  import * as echarts from 'echarts'; // 保留此行引入，防止诸如*labelLayout*等属性打包后不生效问题

  console.log(echarts); // 此行仅为消除上一行import代码的eslint警告

  const props = defineProps<{
    data: ViolationCount;
    getViolations: (range: string[]) => void;
  }>();

  use([CanvasRenderer, PieChart, TooltipComponent, TitleComponent, LegendComponent]);

  const algoData = computed(() => {
    let newData: any[] = [];
    const vioList = props.data.violationAlgoList;
    if (vioList && vioList.length) {
      newData = vioList.map((item) => {
        return {
          value: item.proportion,
          name: item.name,
        };
      });
    }
    return newData;
  });

  const algoLegendData = computed(() => {
    return algoData.value.map((item) => item.name);
  });

  const statData = computed(() => props.data.statusCountList);

  const getVioStatData = (index) => {
    let count = 0;
    if (statData.value && statData.value.length) {
      const matchItem = statData.value.find(
        (item) => item.name === violationHandleCounts[index].value,
      );
      if (matchItem) {
        count = matchItem.value;
      }
    }
    return { ...violationHandleCounts[index], count };
  };

  // const titleLeft = ref('');
  const myChart = ref();
  let timer;
  const index = ref(0);

  onMounted(() => {
    // const contentChart = document.querySelector('.echarts.chart') as HTMLDivElement;
    // titleLeft.value = contentChart?.offsetWidth * 0.3 + 'px';
    if (myChart.value) startAutoPlay();
  });

  function startAutoPlay() {
    stopAutoPlay();
    timer = setInterval(function () {
      myChart.value.dispatchAction({
        type: 'highlight',
        dataIndex: index.value,
      });
      myChart.value.dispatchAction({
        type: 'downplay',
        dataIndex: index.value === 0 ? algoData.value.length - 1 : index.value - 1,
      });
      index.value++;

      if (index.value === algoData.value.length) {
        index.value = 0;
      }
    }, 2500);
  }

  function stopAutoPlay() {
    clearInterval(timer);
    let length = algoData.value.length;
    myChart.value.dispatchAction({
      type: 'downplay',
      dataIndex: Array.from({ length }, (_, i) => i),
    });
  }

  function pauseAutoPlay(argIndex) {
    if (myChart.value) {
      let length = algoData.value.length;
      index.value = argIndex;
      stopAutoPlay();
      myChart.value.dispatchAction({
        type: 'highlight',
        dataIndex: index.value,
      });
      myChart.value.dispatchAction({
        type: 'downplay',
        dataIndex: Array.from({ length }, (_, i) => i).filter((item) => item !== index.value),
      });
    }
  }

  function continueAutoPlay(argIndex) {
    if (myChart.value) {
      let length = algoData.value.length;
      myChart.value.dispatchAction({
        type: 'downplay',
        dataIndex: argIndex,
      });
      index.value = argIndex + 1 === length ? 0 : argIndex + 1;
      startAutoPlay();
    }
  }

  const handleHighlight = (event) => {
    if ('name' in event) {
      const tempIndex = algoData.value.findIndex((item) => item.name === event.name);
      if (myChart.value) pauseAutoPlay(tempIndex);
    }
  };

  const handleDownPlay = (event) => {
    if ('name' in event) {
      const tempIndex = algoData.value.findIndex((item) => item.name === event.name);
      if (myChart.value) continueAutoPlay(tempIndex);
    }
  };

  const handleClickChart = (event) => {
    const { dataIndex } = event;
    if (myChart.value) pauseAutoPlay(dataIndex);
  };

  const handleMouseOver = (event) => {
    const { dataIndex } = event;
    if (myChart.value) pauseAutoPlay(dataIndex);
  };

  const handleMouseOut = (event) => {
    const { dataIndex } = event;
    if (myChart.value) continueAutoPlay(dataIndex);
  };

  const option = computed(() => {
    return {
      title: {
        text: '问题占比', // 设置标题文本
        // left: titleLeft.value, // 标题居中对齐
        left: '32.5%',
        top: '37%',
        textAlign: 'center',
        textStyle: {
          fontSize: 20,
        },
      },
      grid: {
        left: '10px',
        right: '4%',
        bottom: '3%',
      },
      legend: [
        {
          icon: 'circle',
          orient: 'vertical',
          type: 'scroll',
          left: '65%',
          top: 'center',
          itemWidth: 10,
          itemHeight: 10,
          align: 'left',
          textStyle: {
            fontSize: 14,
            color: '#6e69b2',
          },
          data: algoLegendData.value,
          formatter: function (name) {
            let maxNameLength = 0;
            algoData.value.forEach((item) => {
              if (item.name.length > maxNameLength) maxNameLength = item.name.length;
            });
            if (algoData.value && algoData.value.length) {
              for (var i = 0; i < algoData.value.length; i++) {
                if (name === algoData.value[i].name) {
                  return (
                    '' +
                    name +
                    '   '.repeat(maxNameLength - name.length) +
                    '      ' +
                    (algoData.value[i].value * 100).toFixed(2) +
                    '%'
                  );
                }
              }
            }
          },
        },
      ],
      series: [
        {
          type: 'pie',
          radius: ['44%', '55%'],
          center: ['33%', '40%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'outside',
            fontSize: 16,
            color: '#000',
          },
          labelLine: {
            show: false,
          },
          labelLayout() {
            return {
              x: '33%',
              y: '86%',
              verticalAlign: 'bottom',
              align: 'center',
            };
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
              formatter: '{b}:   {d}%',
            },
            itemStyle: {
              borderColor: '#f3f3f3',
              borderWidth: 3,
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          data: algoData.value,
        },
      ],
    };
  });

  const timeTab = ref<TimeTabEnum>(TimeTabEnum.DAY);

  const onCheckTab = (info: { tab: TimeTabEnum; data: string[] }) => {
    timeTab.value = info.tab;
    props.getViolations(info.data);
    index.value = 0;
    startAutoPlay();
  };
</script>

<style scoped>
  .algo-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .chart {
    width: 100%;
    min-width: 550px;
    flex-grow: 1;
    height: 340px;
  }
  .el-divider--horizontal {
    margin: 0px;
  }

  .algo-tit {
    font-size: 16px;
    margin-top: 17px;
    margin-left: 18px;
  }

  .stat-show {
    flex-grow: 0;
    width: 266px;
    flex-shrink: 0;
    font-size: 14px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    padding: 0;
    margin-top: 72px;
    margin-bottom: 82px;
  }

  .stat-data {
    flex-basis: calc(50% - 1px);
    padding-bottom: 35px;
  }

  .stat-divider {
    width: 1px;
    height: 40px;
    background: #e9e9e9;
  }

  .el-divider--vertical {
    margin: 0px;
    height: 339px;
  }

  /* 控制图例的样式 */
  ::v-deep .echarts-legend {
    display: flex;
    flex-wrap: wrap; /* 图例换行 */
  }

  ::v-deep .echarts-legend-item {
    flex: 0 0 50%; /* 每行显示两个图例 */
  }
</style>
