<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="首日关卡分布">
          <n-alert :show-icon="false">
            统计规则解释：假设玩家进入章节1（普通）3次，第一和第二次都在18房间进行结算，第三次在28房间进行结算。则第1~28房间途径人数各自增加1人，18、28房间结算人数各自增加1人
          </n-alert>
        </n-card>
      </div>
      <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"
        :resizeHeightOffset="-2000"
        :pagination="false"
      />
    </n-card>
  </div>
</template>

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

  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) });
  }

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

  const columns = [
    {
      title: '房间ID',
      key: 'room_id',
      width: 100,
    },
    {
      key: 'count',
      width: 100,
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '房间途径人数', icon: renderIcon(HelpCircleOutline) }
          ),
          '同一玩家多次途径只统计一次'
        );
      },
    },
    {
      key: 'count',
      width: 100,
      title: '房间留存率',
      render(row) {
        if (row.oldTimes == 0 || row.oldUsers == 0) {
          return '-';
        }
        return ((row.count / indexNum.value) * 100).toFixed(2) + '%';
      },
    },
    {
      key: 'settle_count',
      width: 100,
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '房间结算人数', icon: renderIcon(HelpCircleOutline) }
          ),
          '同一玩家多次结算只统计一次'
        );
      },
    },
  ];

  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;
        },
      },
    },
    {
      field: 'type',
      component: 'NSelect',
      label: '选择章节',
      componentProps: {
        placeholder: '请选择章节',
        options: useUserStore.config.chapter_option,
        consistentMenuWidth: false,
        onUpdateValue: (e: any) => {
          const chapter = getChapterAndDifficulty(e);
          params.value.chapter_id = chapter?.id;
          params.value.difficulty = chapter?.diff;
        },
      },
    },
    {
      field: 'makeDate',
      component: 'NDatePicker',
      label: '选择日期',
      defaultValue: defaultStatisticsTimeOptions(),
      componentProps: {
        type: 'date',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e);
        },
      },
    },
  ];

  const indexNum = ref(0);
  const actionRef = ref();
  const formParams = reactive({
    day: '',
    date: null,
    difficulty: 0,
    chapter_id: 0,
    days: 0,
    channel_id: '',
  });

  const [register, {}] = useForm({
    gridProps: { cols: '6' },
    labelWidth: 80,
    schemas,
  });

  const loadDataTable = async (res) => {
    const data = await chapterFirstDay({ ...formParams, ...params.value, ...res });
    console.log('data:' + JSON.stringify(data));

    if (data.list !== undefined && data.list !== null && data.list.length > 0) {
      indexNum.value = data.list[0].count;
    }

    return data;
  };

  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: 10,
      day: timestampToDate(defaultStatisticsTimeOptions()),
      difficulty: 0,
      chapter_id: 0,
      days: 0,
      channel_id: '',
      server_id: null,
      flag: -1,
    };
    reloadTable();
  }
</script>

<style scoped></style>
