<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>

      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <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 { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { timestampToDate } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { TreasureStar } from '@/api/echarts/Duel';
  import { onMounted, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { saveAs } from 'file-saver';

  const options3 = ref({});
  const legendData = ref<string[]>();
  const xAxisData = ref<string[]>();
  const yAxisData = ref<number[][]>();

  const useUserStore = useUserStoreWidthOut();
  const loading = ref(false);
  const message = useMessage();
  const params = ref<any>({
    pageSize: 10,
    // startLevel: 1,
    // endLevel: 50,
    channel_id: '',
    server_id: null,
  });
  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.server_id = e;
        },
      },
    },
    // {
    //   field: 'channel_id',
    //   component: 'NTreeSelect',
    //   label: '推广渠道',
    //   componentProps: {
    //     placeholder: '请选择推广渠道',
    //     clearFilterAfterSelect: true,
    //     clearable: true,
    //     filterable: true,
    //     defaultExpandAll: true,
    //     options: useUserStore.config.channel_tree_option,
    //     onUpdateValue: (e: any) => {
    //       console.log(e);
    //       params.value.channel_id = e;
    //     },
    //   },
    // },
    // {
    //   field: 'level',
    //   component: 'NInput',
    //   label: '宝物星级',
    //   componentProps: {
    //     pair: true,
    //     separator: '~',
    //     clearable: true,
    //     placeholder: ['从', '到'],
    //     defaultValue: [params.value.startLevel, params.value.endLevel],
    //     onInput: (e: any) => {
    //       console.log(e);
    //       params.value.startLevel = parseInt(e[0]);
    //       params.value.endLevel = parseInt(e[1]);
    //     },
    //   },
    // },
  ];

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = {
      pageSize: 10,
      day: timestampToDate(new Date() - 86400000 * 30),
      endDay: timestampToDate(new Date()),
      channel_id: '',
      server_id: 1,
    };
    reloadTable();
  }

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

  function exportDataToExcel() {
    // legendData: string[], xAxisData: string[], yAxisData: number[][]
    import('xlsx').then((xlsx) => {
      const workbook = xlsx.utils.book_new();
      const worksheet = xlsx.utils.aoa_to_sheet([]);

      // 设置表头
      let header: any[] = ['宝物星级'].concat(legendData.value);
      xlsx.utils.sheet_add_aoa(worksheet, [header], { origin: -1 });

      // 设置数据行
      for (let i = 0; i < xAxisData.value.length; i++) {
        let rowData: any[] = [xAxisData.value[i]].concat(yAxisData.value[i]);
        xlsx.utils.sheet_add_aoa(worksheet, [rowData], { origin: -1 });
      }

      // 将工作表添加到工作簿
      xlsx.utils.book_append_sheet(workbook, worksheet, 'Data');

      // 导出 Excel 文件
      const buffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });
      const blob = new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      saveAs(blob, '宝物星级分布数据.xlsx');
    });
  }

  function optionToContent(opt: any) {
    let axisData = opt.xAxis[0].data;
    let series = opt.series;
    let table = '<table style="width:100%;text-align:center"><tbody>';
    table += '<tr><th>宝物星级</th>';

    for (let i = 0; i < series.length; i++) {
      table += `<th>${series[i].name}</th>`;
    }

    table += '</tr>';

    for (let i = 0; i < axisData.length; i++) {
      table += '<tr>';
      table += `<td>${axisData[i]}</td>`;

      for (let j = 0; j < series.length; j++) {
        table += `<td>${series[j].data[i]}</td>`;
      }

      table += '</tr>';
    }

    table += '</tbody></table>';

    return table;
  }

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

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

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

    // 去除重复的宝物名称
    legendData.value = [...new Set(legendData.value)];

    // 设置图表配置项和数据
    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      toolbox: {
        itemSize: 14, //工具栏 icon 的大小
        feature: {
          myExport: {
            show: true,
            title: '导出Excel',
            icon: 'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAACcklEQVR4nGNgGAWjYBSMgmEJDOsNpfRqDX11aw0bdGsNN+vWGj5jGIzAvt6eRb9GX1uvxiBOt8Zwol6t0W69WsM3erVG/9HxQLuVQb3Uilev2thGt9YoDeRY3RrDI3o1ht+xOXbAPaBboSsIdmyNUb5ujdEi3Rqjq3o1Rn+JdeyAe0CPAofiwj7rA8jC3uv9jwxpD/isDyA99kY9UDsaA/8HXRJCBjCH4QOjHtBDCr3Obd0ooVO+qgpF3q7d6f+XH1/g8j07+gZXDBjWm/6/9eI23PC7r+7+N6gzgcsvPb4cLnfn5Z3/Rg1mg68YTZmfjhJCuUsKwOIevT7/f/7+CRb79+/f/+R5aYO3Hth7bT/cA5ceXwaLbbmwFS62+cKWwZ2Jvfp8//+AhjYIlKws///3318w+9P3T/8dO10Gtwf0ao3+zzowB27Jx28f4ez2LZ1Doxg1b7b+//LjSxTLrj+78d+gHpGpB20e0Ks1+m/VaofhgWfvn/03a7IaGh5YfXot3OGvP7+Bs2funz34k1Di3BRwUQkC3399/5+3tBBuIago9Z0QOHg9YNJo8f/uq3twC+YcnAcWP3r7GFzs2J0Tg9cDMw/MRil9bNscwOKhUyPgRSkIlK6sGHx5IGhy6P9ff37hbOvsvLwLJV+AMvqg8YBBncn/8w8vwB0IKoFMmyxRHTch4P+fv3/gahYfWzr4kpAehXjUAwMdA4OmItMb9UDAaAwMqSTkvd7/MMOIG9zFNbyuW2tkDJsLGNTD6+RMcOjVGnWAZmMG7QQHCYBRq95QRbfOOFS31rBNr8Zom16N4XNSDBgFo2AUjAKGIQEAkqNB3aFhJ4wAAAAASUVORK5CYII=',
            onclick: function () {
              exportDataToExcel(); // uniqueLegendData, xAxisData, yAxisData
            },
          },
          saveAsImage: {},
          dataView: {
            show: true,
            title: '数据视图',
            readOnly: true,
            optionToContent: optionToContent,
            lang: ['数据视图', '关闭'],
          },
          magicType: {
            show: true,
            type: ['line', 'bar'], // 支持的图表类型
            title: {
              line: '切换为折线图',
              bar: '切换为柱状图',
            },
          },
        },
      },
      legend: {
        data: legendData.value,
      },
      xAxis: {
        type: 'category',
        data: xAxisData.value,
      },
      yAxis: {
        type: 'value',
      },
      series: [],
    };

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

  const loadDataTable = async (res) => {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      TreasureStar({ ...params.value, ...res })
        .then((res) => {
          console.log(JSON.stringify(res));
          draw(res);
          loading.value = false;
        })
        .catch((error) => {
          message.error("TreasureStar err: "+error.toString());
          loading.value = false;
        });
    });
  };

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

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