<template>
  <div>
    <n-card :bordered="false" class="proCard" title="今日基础数据">
      <n-table :bordered="false" :single-line="false">
        <thead>
          <tr>
            <th>
              <n-space :inline="true" :size="12">
                <n-tag checkable> 名称 </n-tag>
                <n-tag checkable>
                  <n-select
                    v-model:value="serverId"
                    style="width: 200px"
                    size="small"
                    :options="useUserStore.config.server_simple_option"
                    @update:value="handleUpdateValue"
                  />
                </n-tag> </n-space
            ></th>
            <th> {{ loading ? '正在获取..' : '人数' }}</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="(item, i) in basicData" :key="i">
            <tr>
              <td>{{ item.name }}</td>
              <td>{{ item.count }}</td>
            </tr>
          </template>
        </tbody>
      </n-table>

      <n-space vertical v-show="skeletonLoading">
        <span v-for="count in 5" :key="count">
          <n-grid :x-gap="12" :cols="2">
            <n-gi :span="1">
              <n-skeleton height="45px" width="100%" />
            </n-gi>
            <n-gi :span="1">
              <n-skeleton height="45px" width="100%" />
            </n-gi>
          </n-grid>
        </span>
      </n-space>
    </n-card>

    <Retention />
    <n-card :bordered="false" class="proCard" title="日统计">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="formRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :after-request="afterLoadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :pagination="{ pageSize: 15 }"
        :resizeHeightOffset="-20000"
      >
        <template #tableTitle>
          <n-button type="primary" @click="exportOrders" :loading="loadingRef"> 导出数据 </n-button>
        </template>
      </BasicTable>
    </n-card>
    <AddRetention />
  </div>
</template>

<script lang="ts" setup>
  import { ref, h, Component } from 'vue';
  import { useMessage, NTooltip, NIcon, NButton } from 'naive-ui';
  import { BasicTable } from '@/components/Table';
  import { basicInfo, basicReport } from '@/api/echarts/chapterDailyStatistics';
  import AddRetention from './components/AddRetention.vue';
  import Retention from './components/Retention.vue';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { FormSchema, useForm } from '@/components/Form';
  import {delNullProperty, encodeParams} from "@/utils/array";

  const useUserStore = useUserStoreWidthOut();
  const serverId = ref<any>(1);
  const params = ref<any>({
    channel_id: '',
    server_id: null,
    flag: -1,
  });

  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 [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function afterLoadDataTable(info) {
    info.forEach((item) => {
      item.new_duration = (item.new_duration / 60).toFixed(2);
      item.new_avg_duration =
        item.new_count > 0 ? (item.new_duration / item.new_count).toFixed(2) : 0;

      item.valid_duration = (item.valid_duration / 60).toFixed(2);
      item.valid_avg_duration =
        item.valid_count > 0 ? (item.valid_duration / item.valid_count).toFixed(2) : 0;

      item.active_duration = (item.active_duration / 60).toFixed(2);
      item.active_avg_duration =
        item.active_count > 0 ? (item.active_duration / item.active_count).toFixed(2) : 0;
      item.old_avg_duration =
        item.active_count > 0
          ? (
              (item.active_duration - item.new_duration) /
              (item.active_count - item.new_count)
            ).toFixed(2)
          : 0;
    });
  }

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

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

  function handleReset(_values: Recordable) {
    params.value = {
      channel_id: '',
      server_id: null,
      flag: -1,
    };

    reloadTable();
  }

  const skeletonLoading = ref(true);

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

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

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 150,
    },
    {
      dataIndex: 'new_count',
      key: 'new_count',
      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: 'valid_count',
      key: 'valid_count',
      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_count',
      key: 'active_count',
      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: 'new_duration',
      key: 'new_duration',
      width: 180,
      render(row) {
        return row.new_duration + ' / ' + row.new_avg_duration;
      },
    },
    {
      title: '有效新增时长(分钟) / 人均',
      dataIndex: 'valid_duration',
      key: 'valid_duration',
      width: 200,
      render(row) {
        return row.valid_duration + ' / ' + row.valid_avg_duration;
      },
    },
    {
      title: '老玩家时长(分钟) / 人均',
      dataIndex: 'active_duration',
      key: 'active_duration',
      width: 200,
      render(row) {
        return (row.active_duration - row.new_duration).toFixed(2) + ' / ' + row.old_avg_duration;
      },
    },
    {
      title: '总时长(分钟) / 人均',
      dataIndex: 'active_duration',
      key: 'active_duration',
      width: 200,
      render(row) {
        return row.active_duration + ' / ' + row.active_avg_duration;
      },
    },
    {
      title: '次留率',
      dataIndex: 'day_1_active',
      key: 'day_1_active',
      render(row) {
        if (row.day_1_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_1_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '2日留',
      dataIndex: 'day_2_active',
      key: 'day_2_active',
      render(row) {
        if (row.day_2_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_2_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '3日留',
      dataIndex: 'day_3_active',
      key: 'day_3_active',
      render(row) {
        if (row.day_3_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_3_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '4日留',
      dataIndex: 'day_4_active',
      key: 'day_4_active',
      render(row) {
        if (row.day_4_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_4_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '5日留',
      dataIndex: 'day_5_active',
      key: 'day_5_active',
      render(row) {
        if (row.day_5_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_5_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '6日留',
      dataIndex: 'day_6_active',
      key: 'day_6_active',
      render(row) {
        if (row.day_6_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_6_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '7日留',
      dataIndex: 'day_7_active',
      key: 'day_7_active',
      render(row) {
        if (row.day_7_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_7_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '14日留',
      dataIndex: 'day_14_active',
      key: 'day_14_active',
      render(row) {
        if (row.day_14_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_14_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
    {
      title: '30日留',
      dataIndex: 'day_30_active',
      key: 'day_30_active',
      render(row) {
        if (row.day_30_active == 0 || row.new_count == 0) {
          return '-';
        }
        return ((row.day_30_active / row.new_count) * 100).toFixed(1) + '%';
      },
      width: 100,
    },
  ];

  const message = useMessage();
  const actionRef = ref();
  const basicData = ref([]);
  const loading = ref(false);

  const loadDataTable = (res) => {
    loadBasicInfo();
    return basicReport({
      ...params.value,
      ...res,
    });
  };

  function loadBasicInfo() {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      basicInfo({ server_id: serverId.value })
        .then((res) => {
          basicData.value = res;
          skeletonLoading.value = false;
          loading.value = false;
        })
        .catch((e: Error) => {
          message.error(e.message ?? '操作失败');
        });
    });
  }

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

  function handleUpdateValue(value, _option) {
    serverId.value = value;
    loadBasicInfo();
  }

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

<style scoped></style>
