<template>
  <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"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :flex-height="false"
      :resizeHeightOffset="-500"
    >
      <template #tableTitle>
        <n-button type="primary" @click="exportOrders"> 导出数据 </n-button>
      </template>
    </BasicTable>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      title="格式化"
      style="width: 95%"
    >
      <n-card
        :bordered="false"
        class="proCard mt-4"
        size="small"
        :segmented="{ content: true }"
        title="数据参数"
      >
        <JsonViewer
          :value="preview"
          :expand-depth="10"
          sort
          style="width: 100%; min-width: 3.125rem"
        />
      </n-card>
      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">关闭</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { JsonViewer } from 'vue3-json-viewer';
  import 'vue3-json-viewer/dist/index.css';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getFightingList, getFightingExtra } from '@/api/echarts/rechargeList';
  import { columns } from './columns';
  import { encodeParams } from '@/utils/array';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import {getChapterAndDifficulty} from '@/convert/chapter/map';
  import {defRangeShortcuts} from "@/utils/dateUtil";

  const useUserStore = useUserStoreWidthOut();

  interface Props {
    userId?: number | string;
    userInfo?: any;
  }
  const props = withDefaults(defineProps<Props>(), { userId: 0, userInfo: userInfoObj });

  const schemas: FormSchema[] = [
    {
      field: 'id',
      component: 'NInput',
      label: '记录ID',
      componentProps: {
        placeholder: '请输入记录ID',
        onInput: (e: any) => {
          console.log(e);
          params.value.id = e;
        },
      },
    },
    {
      field: 'type',
      component: 'NSelect',
      label: '选择章节',
      componentProps: {
        placeholder: '请选择章节',
        options: useUserStore.config.chapter_option,
        consistentMenuWidth: false,
        onUpdateValue: (e: any) => {
          console.log(e);
          const chapter = getChapterAndDifficulty(e);
          params.value.chapter_id = chapter?.id;
          params.value.difficulty = chapter?.diff;
        },
      },
    },
    {
      field: 'event_at',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.event_at = e;
        },
      },
    },
  ];

  const preview = ref('');
  const showModal = ref(false);
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '格式化',
            onClick: handleEdit.bind(null, record),
          },
        ],
      });
    },
  });

  async function handleEdit(record: Recordable) {
    showModal.value = true;
    preview.value = record.extra;
    if (!preview.value.includes('{')) {
      let par = { extra_path: preview.value };
      preview.value = await getFightingExtra({ ...par });
    }
  }

  const actionRef = ref();
  const formParams = reactive({
    playerId: props.userId,
  });

  const params = ref<any>({
    id: 0,
    difficulty: -1,
    chapter_id: 0,
    playerId: props.userId,
    event_at: null,
  });

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

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

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

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

  function handleSubmit(_values: Recordable) {
    reloadTable();
  }

  function exportOrders() {
    window.location.href =
      '/api/dash/fightingExport?' +
      encodeParams({ ...params.value, ...{ authorization: useUserStore.token } });
  }

  function handleReset(values: Recordable) {
    params.value = {
      difficulty: -1,
      chapter_id: 0,
      playerId: props.userId,
      event_at: null,
    };
    console.log(values);
    reloadTable();
  }
</script>

<style lang="less" scoped></style>
