<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>
    <BattleWaves />
    <BattleSeconds />
    <Dan />
    <Match/>
  </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 { GrandmasterInfo } 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 BattleWaves from './BattleWaves.vue';
  import BattleSeconds from './BattleSeconds.vue';
  import Dan from './Dan.vue';
  import Match from './Match.vue';

  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 columns = [
    {
      title: '日期',
      key: 'date',
      width: 120,
    },
    {
      title: '满足开放人数',
      key: 'open_player_count',
      width: 120,
    },
    {
      dataIndex: 'part_count',
      key: 'part_count',
      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.player_count || row.open_player_count < 1 || row.player_count < 1) {
          return '-';
        }
        return (
          row.player_count +
          ' / ' +
          ((row.player_count / row.open_player_count) * 100).toFixed(2) +
          '%'
        );
      },
    },
    {
      dataIndex: 'part_count',
      key: 'part_count',
      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.part_count || row.part_count < 1 || row.player_count < 1) {
          return '-';
        }
        return row.part_count + ' / ' + (row.part_count / row.player_count).toFixed(2);
      },
    },
    {
      dataIndex: 'all_match_seconds',
      key: 'all_match_seconds',
      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.part_count || row.part_count < 1 || row.all_match_seconds < 1) {
          return '-';
        }
        return row.all_match_seconds + ' / ' + (row.all_match_seconds / row.part_count).toFixed(2);
      },
    },
    {
      dataIndex: 'leave_users',
      key: 'leave_users',
      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.leave_users || row.leave_users < 1 || row.player_count < 1) {
          return '-';
        }
        return (
          row.leave_users + ' / ' + ((row.leave_users / row.player_count) * 100).toFixed(2) + '%'
        );
      },
    },
    {
      dataIndex: 'battle_waves_count',
      key: 'battle_waves_count',
      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.part_count || row.part_count < 1 || row.battle_waves_count < 1) {
          return '-';
        }
        return (
          row.battle_waves_count + ' / ' + (row.battle_waves_count / row.part_count).toFixed(2)
        );
      },
    },
    {
      dataIndex: 'all_battle_seconds',
      key: 'all_battle_seconds',
      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.part_count || row.part_count < 1 || row.all_battle_seconds < 1) {
          return '-';
        }
        return (
          row.all_battle_seconds + ' / ' + (row.all_battle_seconds / row.part_count).toFixed(2)
        );
      },
    },
  ];

  const dataSource = ref<IData[]>([]);
  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 {
    date: string;
    id: number;
    all_battle_seconds: number;
    all_match_seconds: number;
    battle_waves_count: number;
    leave_users: number;
    open_player_count: number;
    part_count: number;
    player_count: number;
  }

  const loadDataTable = async (res1) => {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      GrandmasterInfo({ ...formParams, ...params.value, ...res1 })
        .then((res) => {
          let list: IData[] = res as IData[];
          console.log('list:' + JSON.stringify(list));
          dataSource.value = list;
          draw(list);
          loading.value = false;
        })
        .catch((error) => {
          message.error(error.toString());
          loading.value = false;
        });
    });
  };

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

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

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

  function draw(list: IData[]) {
    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: IData) => ({
      date: item.date,
      open_player_count: item.open_player_count,
      player_count: item.player_count,
      part_count: item.part_count,
      all_match_seconds: calculateAvgMatchSeconds(item),
      leave_users: item.leave_users,
      battle_waves_count: calculateAvgBattleWavesCount(item),
      all_battle_seconds: calculateAvgBattleSeconds(item),
    }));

    function calculateAvgMatchSeconds(row: IData): number {
      if (!row.part_count || row.part_count < 1 || row.all_match_seconds < 1) {
        return 0;
      }
      return (row.all_match_seconds / row.part_count).toFixed(2);
    }

    function calculateAvgBattleWavesCount(row: IData): number {
      if (!row.part_count || row.part_count < 1 || row.battle_waves_count < 1) {
        return 0;
      }
      return (row.battle_waves_count / row.part_count).toFixed(2);
    }

    function calculateAvgBattleSeconds(row: IData): number {
      if (!row.part_count || row.part_count < 1 || row.all_battle_seconds < 1) {
        return 0;
      }
      return (row.all_battle_seconds / row.part_count).toFixed(2);
    }

    options3.value.xAxis.data = objectData.map((item: IData) => item.date).reverse();

    options3.value.legend.data = [];
    options3.value.legend.data.push('满足开放人数');
    options3.value.series.push({
      name: '满足开放人数',
      type: 'line',
      data: objectData.map((item: IData) => item.open_player_count).reverse(),
    });

    options3.value.legend.data.push('参与人数');
    options3.value.series.push({
      name: '参与人数',
      type: 'line',
      data: objectData.map((item: IData) => item.player_count).reverse(),
    });

    options3.value.legend.data.push('离开人数');
    options3.value.series.push({
      name: '离开人数',
      type: 'line',
      data: objectData.map((item: IData) => item.leave_users).reverse(),
    });

    options3.value.legend.data.push('参与次数');
    options3.value.series.push({
      name: '参与次数',
      type: 'line',
      data: objectData.map((item: IData) => item.part_count).reverse(),
    });

    options3.value.legend.data.push('人均匹配时长(秒)');
    options3.value.series.push({
      name: '人均匹配时长(秒)',
      type: 'line',
      data: objectData.map((item: IData) => item.all_match_seconds).reverse(),
    });

    options3.value.legend.data.push('人均战斗波数');
    options3.value.series.push({
      name: '人均战斗波数',
      type: 'line',
      data: objectData.map((item: IData) => item.battle_waves_count).reverse(),
    });

    options3.value.legend.data.push('人均战斗时长(秒)');
    options3.value.series.push({
      name: '人均战斗时长(秒)',
      type: 'line',
      data: objectData.map((item: IData) => item.all_battle_seconds).reverse(),
    });
  }

  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>
