<template>
  <div>
    <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
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :pagination="true"
        :resizeHeightOffset="-4000"
      />
    </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 { dieLog } from '@/api/echarts/dieLog';
  import { defRangeShortcuts, timestampToDate } from '@/utils/dateUtil';
  import { NButton, NIcon, NTooltip } from 'naive-ui';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { useUserStoreWidthOut } from '@/store/modules/user';

  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: 'chapter_id',
      key: 'chapter_id',
    },
    {
      title: '关卡',
      dataIndex: 'chapter',
      key: 'chapter',
    },
    {
      key: 'die_count',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '死亡次数（总/新手）', icon: renderIcon(HelpCircleOutline) }
          ),
          '在关卡死亡时统计一次，同一关卡可能死亡多次'
        );
      },
      render: (rows, _) => {
        return rows.die_count + ' / ' + rows.new_die_count;
      },
    },
    {
      title: '死亡人数（总/新手）',
      dataIndex: 'die_user_count',
      key: 'die_user_count',
      render: (rows, _) => {
        return rows.die_user_count + ' / ' + rows.new_die_user_count;
      },
    },
  ];

  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: '选择日期',
      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: 80,
    schemas,
  });

  //根据id值 从小到大排序
  function sortId(a, b) {
    // // 多字段排序
    // if (a.chapter_id !== b.chapter_id) return a.chapter_id < b.chapter_id ? -1 : 1;
    // else if (a.difficulty !== b.difficulty) return a.difficulty === '简单' ? -1 : 1;
    // return a.chapter_id - b.chapter_id;

    return a.index < b.index ? -1 : 1;
  }

  const loadDataTable = async (res) => {
    let list = await dieLog({ ...formParams, ...params.value, ...res });
    list.list.sort(sortId);
    return list;
  };

  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>
