<template>
  <div>
    <n-card
      title="宝物碎片产出数据"
      :content-style="{ padding: '10px' }"
      :header-style="{ padding: '10px' }"
    >
      <Chart :loading="loading" :options="options3" style="width: 100%; min-height: 600px" />
    </n-card>

    <n-card :bordered="false" class="proCard" title="宝物碎片每日产出 / 人均数据">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1800"
        :resizeHeightOffset="-20000"
      />
    </n-card>
    <PlayerLevel />
    <RoleWear />
    <Level />
    <Star />
  </div>
</template>

<script lang="ts" setup>
  import { Component, h, onMounted, reactive, ref } from 'vue';
  import { NButton, NIcon, NTooltip, useMessage } from 'naive-ui';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { TreasureInfo } from '@/api/echarts/ExpeditionInfo';
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import { defRangeShortcuts, timestampToDate } from '@/utils/dateUtil';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { getAllMaterials } from '@/api/account/list';
  import { isObjectEmpty } from '@/utils/is';
  import PlayerLevel from './playerLevel.vue';
  import RoleWear from './RoleWear.vue';
  import Level from './Level.vue';
  import Star from './Star.vue';

  const allMaterials = ref<any>({});
  const useUserStore = useUserStoreWidthOut();
  const renderTooltip = (trigger, content) => {
    return h(NTooltip, null, {
      trigger: () => trigger,
      default: () => content,
    });
  };

  function renderIcon(icon: Component) {
    return () => h(NIcon, null, { default: () => h(icon) });
  }

  let options3 = ref({});

  const defColumns = [
    {
      title: '日期',
      key: 'date',
      width: 120,
    },
    {
      title: '获得碎片人数',
      key: 'player_count',
      width: 120,
    },
    {
      dataIndex: 'activeCount',
      key: 'activeCount',
      width: 180,
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '总活跃人数 / 占比', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天内登录过游戏的玩家人数，不区分新老玩家'
        );
      },
      render(row) {
        if (!row.active_count || row.active_count < 1 || row.player_count < 1) {
          return '-';
        }
        return (
          row.active_count + ' / ' + ((row.player_count / row.active_count) * 100).toFixed(2) + '%'
        );
      },
    },
  ];

  const columns = ref([]);
  const dataSource = ref([]);
  const params = ref<any>({
    pageSize: 10,
    day: timestampToDate(new Date() - 86400000 * 30),
    endDay: timestampToDate(new Date()),
    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: 'createtime',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'daterange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        defaultValue: [new Date() - 86400000 * 30, new Date()],
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e[0]);
          params.value.endDay = timestampToDate(e[1]);
        },
      },
    },
  ];

  const loading = ref(false);
  const message = useMessage();
  const actionRef = ref();
  const formParams = reactive({
    day: '',
    endDay: '',
    channel_id: '',
  });

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

  interface IData {
    id: number;
    date: string;
    channel_id: string;
    server_id: number;
    player_count: number;
    output: string;
    TreasureOutput: {
      [key: `d:${number}`]: number;
    };
  }

  const loadDataTable = async (res1) => {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      TreasureInfo({ ...formParams, ...params.value, ...res1 })
        .then((res) => {
          let list = [];
          if (res == null) {
            return;
          }
          res.forEach((element: IData) => {
            let obj = {
              ...element,
              ...element.TreasureOutput,
            };
            delete obj.id;
            delete obj.channel_id;
            delete obj.server_id;
            delete obj.output;
            delete obj.TreasureOutput;
            return list.push(obj);
          });

          console.log('list:' + JSON.stringify(list));
          dataSource.value = list;
          draw(list);
          loading.value = false;
        })
        .catch((error) => {
          message.error("TreasureInfo err: "+error.toString());
          loading.value = false;
        });
    });
  };

  onMounted(async () => {
    await loadAllMaterial();
    await loadDataTable({});
  });

  const loadAllMaterial = async () => {
    if (!isObjectEmpty(allMaterials.value)) {
      return;
    }
    loading.value = true;
    const ms = await getAllMaterials({});
    ms[26].forEach((element: { ItemType: number; ItemId: string | number; ItemName: any }) => {
      allMaterials.value[element.ItemId] = element.ItemName.replace('碎片', '');
    });

    columns.value = defColumns;
    for (let key in allMaterials.value) {
      columns.value.push({
        title: allMaterials.value[key] + ' / 人均',
        key: 'd:' + key,
        width: 120,
        render(row) {
          let k1 = 'd:' + key;
          if (!row[k1] || row[k1] < 1 || row.player_count < 1) {
            return '-';
          }
          return row[k1] + ' / ' + (row[k1] / row.player_count).toFixed(1);
        },
      });
    }
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

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

  function draw(list: any[]) {
    if (!list) {
      list = [];
    }

    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: [],
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      toolbox: {
        feature: {
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [],
    };

    // 转换为对象数组
    const objectData = list.map((item) => ({
      date: item.date,
      player_count: item.player_count,
      additionalData: Object.keys(item).filter((key) => key !== 'date' && key !== 'player_count'),
    }));

    // 提取日期和玩家计数
    const reversedDates = objectData.map((item) => item.date).reverse();
    const reversedPlayerCounts = objectData.map((item) => item.player_count).reverse();
    let additionalKeys = [];

    for (let key in allMaterials.value) {
      additionalKeys.push(allMaterials.value[key]);
    }

    // 动态更新折线图配置
    options3.value.xAxis.data = reversedDates;
    options3.value.legend.data = ['获得碎片人数', ...additionalKeys];

    options3.value.series.push({
      name: '获得碎片人数',
      type: 'line',
      data: reversedPlayerCounts,
    });

    for (let key in allMaterials.value) {
      let clos = {
        name: allMaterials.value[key],
        type: 'line',
        data: [],
      };

      list.forEach((item) => {
        let k1 = 'd:' + key;
        if (k1 in item) {
          clos.data.push(item[k1]);
        } else {
          clos.data.push(0);
        }
      });
      clos.data.reverse();

      options3.value.series.push(clos);
    }
  }

  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: null,
    };
    reloadTable();
  }
</script>

<style scoped></style>
