<template>
  <div>
    <n-card :content-style="{ padding: '10px' }" :header-style="{ padding: '10px' }">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="各个角色佩戴宝物分布">
          X轴是角色；Y轴是对应角色佩戴各种宝物的数量
        </n-card>
      </div>
      <Chart :loading="loading" :options="options3" style="width: 100%; min-height: 600px" />
    </n-card>
  </div>
</template>

<script setup lang="ts">
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { TreasureRoleWear } from '@/api/echarts/Duel';
  import { onMounted, ref } from 'vue';
  import { useMessage } from 'naive-ui';

  let options3 = ref({});
  const loading = ref(false);
  const message = useMessage();

  function reloadTable() {
    loadDataTable({});
  }

  function draw(data) {
    // 准备 x 轴数据（角色名称数组）
    const xAxisData = data.map((item) => item.roleName);

    // 准备 y 轴数据（宝物数量数组）
    const yAxisData = [];
    for (const dp of data) {
      const treasureValues = Object.values(dp.treasures);
      yAxisData.push(treasureValues);
    }

    // 准备 legend 数据（宝物名称数组）
    const legendData = [];
    for (const dp of data) {
      const treasureKeys = Object.keys(dp.treasures);
      legendData.push(...treasureKeys);
    }

    const uniqueLegendData = [...new Set(legendData)];

    // 设置图表配置项和数据
    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      toolbox: {
        feature: {
          saveAsImage: {},
        },
      },
      legend: {
        data: uniqueLegendData,
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
      },
      yAxis: {
        type: 'value',
      },
      series: [],
    };

    // 添加每个宝物的折线数据系列
    for (let i = 0; i < uniqueLegendData.length; i++) {
      options3.value.series.push({
        name: uniqueLegendData[i],
        type: 'line',
        data: yAxisData.map((item) => item[i]),
      });
    }
  }

  const loadDataTable = async (res) => {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      TreasureRoleWear({ ...res })
        .then((res) => {
          if (res == null) {
            return;
          }
          draw(res);
          loading.value = false;
        })
        .catch((error) => {
          message.error("TreasureRoleWear err: "+error.toString());
          loading.value = false;
        });
    });
  };

  onMounted(async () => {
    await loadDataTable({});
  });
</script>

<style scoped lang="less"></style>
