<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="闯关数据">
        活动关卡如果在未开放日则不会有闯关数据，但由于中途退出下次登录可以重新进入关卡，所以可能存在少量通关和结算数据
      </n-card>
    </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"
        :pagination="false"
        :resizeHeightOffset="-3000"
      />
    </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 { chapterPass } from '@/api/echarts/chapterPass';
  import { defRangeShortcuts, timestampToDate } from '@/utils/dateUtil';
  import { NButton, NIcon, NTag, NTooltip } from 'naive-ui';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import {getDifficultName} from "@/utils/index";

  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 columns = [
    {
      title: '章节id',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '难度',
      dataIndex: 'diff',
      key: 'diff',
      render(row) {
        return h(
          NTag,
          {
            style: {
              marginRight: '6px',
            },
            type: row.diff == 1 ? 'error' : 'info',
            bordered: false,
          },
          {
            default: () =>  getDifficultName(row.diff),
          }
        );
      },
      width: 100,
    },
    {
      key: 'nums',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '闯关次数（总/新手）', icon: renderIcon(HelpCircleOutline) }
          ),
          '进入关卡即算闯关一次'
        );
      },
      width: 220,
      render: (rows, _) => {
        return rows.nums + ' / ' + rows.numsNew;
      },
    },
    {
      title: '闯关人数（总/新手）',
      dataIndex: 'users',
      key: 'users',
      scopedSlots: {
        customRender: 'users',
      },
      width: 220,
      render: (rows, _) => {
        return rows.users + ' / ' + rows.usersNew;
      },
    },
    {
      key: 'passNums',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '通关次数（总/新手）', icon: renderIcon(HelpCircleOutline) }
          ),
          '在章节最后一个房间结算即算通关一次'
        );
      },
      width: 220,
      render: (rows, _) => {
        return rows.passNums + ' / ' + rows.passNumsNew;
      },
    },
    {
      title: '通关人数（总/新手）',
      dataIndex: 'passUsers',
      key: 'passUsers',
      scopedSlots: {
        customRender: 'passUsers',
      },
      width: 220,
      render: (rows, _) => {
        return rows.passUsers + ' / ' + rows.passUsersNew;
      },
    },
    {
      key: 'settleNums',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '结算次数（总/新手）', icon: renderIcon(HelpCircleOutline) }
          ),
          '在章节任意房间结算即算结算一次'
        );
      },
      width: 220,
      render: (rows, _) => {
        return rows.settleNums + ' / ' + rows.settleNumsNew;
      },
    },
    {
      title: '结算人数（总/新手）',
      dataIndex: 'settleUsers',
      key: 'settleUsers',
      width: 220,
      render: (rows, _) => {
        return rows.settleUsers + ' / ' + rows.settleUsersNew;
      },
    },
  ];

  const params = ref<any>({
    pageSize: 10,
    day: timestampToDate(new Date() - 86400000),
    endDay: timestampToDate(new Date() - 86400000),
    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;
        },
      },
    },
    {
      field: 'createtime',
      component: 'NDatePicker',
      label: '选择日期',
      labelMessage: '如果查询1天以上的闯关数据，展示的数据结果为范围日期内的总和',
      componentProps: {
        type: 'daterange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        defaultValue: [new Date() - 86400000, new Date() - 86400000],
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e[0]);
          params.value.endDay = timestampToDate(e[1]);
        },
      },
    },
  ];

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

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

  const loadDataTable = async (res) => {
    return await chapterPass({ ...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: 10,
      day: timestampToDate(new Date() - 86400000),
      endDay: timestampToDate(new Date() - 86400000),
      channel_id: '',
      server_id: null,
      flag: -1,
    };
    reloadTable();
  }
</script>

<style scoped></style>
