<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="广告综合统计" />
    </div>
    <n-card :bordered="false" class="proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :canResize="true"
        :resizeHeightOffset="-20000"
      >
        <template #tableTitle>
          <n-button type="primary" @click="exportOrders" :loading="loadingRef"> 导出数据 </n-button>
        </template>
      </BasicTable>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, Component } from 'vue';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { NTooltip, NIcon, NButton } from 'naive-ui';
  import { advSumm } from '@/api/echarts/UserAdv';
  import { defaultStatisticsTimeOptions, timestampToDate } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { delNullProperty, encodeParams } from '@/utils/array';

  const renderTooltip = (trigger, content) => {
    return h(NTooltip, null, {
      trigger: () => trigger,
      default: () => content,
    });
  };

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

  const params = ref<any>({
    pageSize: 10,
    day: timestampToDate(defaultStatisticsTimeOptions()),
    days: 0,
    channel_id: '',
    server_id: null,
    flag: -1,
  });

  const useUserStore = useUserStoreWidthOut();
  const columns = reactive([
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 100,
    },
    {
      dataIndex: 'rewardTimes',
      key: 'rewardTimes',
      width: 120,
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '总曝光次数', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天所有广告点位观看并领取的次数'
        );
      },
    },
    {
      dataIndex: 'rewardUsers',
      key: 'rewardUsers',
      width: 120,
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '总曝光人数', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天所有广告点位观看并领取的人数'
        );
      },
    },
    {
      title: '总平均频次',
      dataIndex: 'active_users',
      key: 'active_users',
      width: 100,
      render(row) {
        if (row.rewardTimes == 0 || row.rewardUsers == 0) {
          return '-';
        }
        return (row.rewardTimes / row.rewardUsers).toFixed(2);
      },
    },
    {
      dataIndex: 'activeCount',
      key: 'activeCount',
      width: 120,
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '总活跃人数', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天内登录过游戏的玩家人数，不区分新老玩家'
        );
      },
    },
    {
      dataIndex: 'active_users',
      key: 'active_users',
      width: 120,
      render(row) {
        if (row.rewardUsers == 0 || row.activeCount == 0) {
          return '-';
        }
        return ((row.rewardUsers / row.activeCount) * 100).toFixed(2) + '%';
      },
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '总覆盖率', icon: renderIcon(HelpCircleOutline) }
          ),
          '总曝光人数 / 总活跃人数 * 100'
        );
      },
    },
    {
      title: '新注册广告次数',
      dataIndex: 'newTimes',
      key: 'newTimes',
      width: 130,
    },
    {
      dataIndex: 'newUsers',
      key: 'newUsers',
      width: 150,
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '新注册广告人数', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天新注册玩家，且观看广告并领取奖励的人数'
        );
      },
    },
    {
      title: '新注册平均频次',
      dataIndex: 'new_count',
      key: 'new_count',
      width: 130,
      render(row) {
        if (row.newTimes == 0 || row.newUsers == 0) {
          return '-';
        }
        return (row.newTimes / row.newUsers).toFixed(2);
      },
    },
    {
      title: '新注册人数',
      dataIndex: 'newCount',
      key: 'newCount',
      width: 100,
    },
    {
      title(column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '新注册覆盖率', icon: renderIcon(HelpCircleOutline) }
          ),
          '新注册覆盖率 = 新注册广告人数 / 新注册人数'
        );
      },
      dataIndex: 'new_count',
      key: 'new_count',
      width: 130,
      render(row) {
        if (row.newUsers == 0 || row.newCount == 0) {
          return '-';
        }
        return ((row.newUsers / row.newCount) * 100).toFixed(2) + '%';
      },
    },
    {
      title: '老玩家广告次数',
      dataIndex: 'oldTimes',
      key: 'oldTimes',
      width: 130,
    },
    {
      dataIndex: 'oldUsers',
      key: 'oldUsers',
      width: 150,
      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.activeCount == 0) {
          return '-';
        }
        return row.activeCount - row.newCount;
      },
    },
    {
      title: '老玩家平均频次',
      dataIndex: 'old_count',
      key: 'old_count',
      width: 130,
      render(row) {
        if (row.oldTimes == 0 || row.oldUsers == 0) {
          return '-';
        }
        return (row.oldTimes / row.oldUsers).toFixed(2);
      },
    },
    {
      dataIndex: 'oldCount',
      key: 'oldCount',
      width: 150,
      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.activeCount == 0) {
          return '-';
        }
        return row.activeCount - row.oldUsers;
      },
    },
    {
      // title: '老玩家覆盖率',
      dataIndex: 'old_count',
      key: 'old_count',
      width: 130,
      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.activeCount == 0 || row.oldUsers == 0) {
          return '-';
        }

        return ((row.oldUsers / row.activeCount) * 100).toFixed(2) + '%';
      },
    },
  ]);
  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: 'flag',
      component: 'NSelect',
      label: '玩家分类',
      componentProps: {
        placeholder: '请选择玩家分类',
        options: useUserStore.config.flag_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.flag = e;
        },
      },
    },
  ];

  const actionRef = ref();

  const formParams = reactive({
    day: '',
    days: 0,
    channel_id: '',
  });

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

  const loadDataTable = (res) => {
    return advSumm({ ...formParams, ...params.value, ...res });
  };

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

  function reloadTable() {
    actionRef.value.reload();
  }

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

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = {
      pageSize: 100,
      day: timestampToDate(defaultStatisticsTimeOptions()),
      days: 0,
      channel_id: '',
      server_id: null,
      flag: -1,
    };
    reloadTable();
  }

  const loadingRef = ref(false);
  function exportOrders() {
    // window.location.href = '/api/dash/advSummExport?' + encodeParams(params.value);

    loadingRef.value = true;
    window.location.href =
      '/api/dash/advSumm?' +
      encodeParams(
        delNullProperty({ ...params.value, is_export: 1, ...{ authorization: useUserStore.token } })
      );
    setTimeout(() => {
      loadingRef.value = false;
    }, 2000);
  }
</script>

<style scoped></style>
