<script lang="ts" setup>
import { useTemplateRef } from 'vue';
import { useDateFormat } from '@vueuse/core';
import { useDialog } from 'naive-ui';
import { client, safeClient } from '@/service/api';
import type { TableBaseColumns, TableFetchData, TableInst } from '@/components/table';

const props = defineProps<{
  id: string;
}>();

const tableInst = useTemplateRef<TableInst>('tableInst');
const dialog = useDialog();

const fetchData: TableFetchData = ({ pagination, filter }) => {
  return safeClient(() =>
    client.api.admin.rwa.subscription.orders.get({
      query: {
        editionId: props.id,
        ...pagination,
        ...filter
      }
    })
  );
};

const columns: TableBaseColumns = [
  {
    title: '分配用户ID',
    key: 'userId',
    width: 150
  },
  {
    title: '分配数量',
    key: 'quantity',
    width: 120,
    render: (row: any) => {
      return Number(row.quantity).toFixed(2);
    }
  },
  {
    title: '单价',
    key: 'unitPrice',
    width: 120,
    render: (row: any) => {
      return Number(row.unitPrice).toFixed(2);
    }
  },
  {
    title: '分配时间',
    key: 'createdAt',
    render: (row: any) => {
      return useDateFormat(row.createdAt, 'YYYY-MM-DD HH:mm').value;
    }
  },
  {
    title: '操作',
    fixed: 'right',
    key: 'operation',
    width: 'auto',
    operations: row => [
      {
        contentText: '执行分配',
        type: 'primary',
        ghost: true,
        size: 'small',
        onClick: () => {
          dialog.create({
            title: '执行分配',
            content: '确认执行该分配操作？',
            positiveText: '确认',
            negativeText: '取消',
            onPositiveClick: async () => {
              await safeClient(() =>
                client.api.admin.rwa.subscription.allocate.post({
                  editionId: props.id
                })
              );
              tableInst.value?.reload();
            }
          });
        }
      }
    ]
  }
];
</script>

<template>
  <TableBase ref="tableInst" title="申购记录" :columns="columns" :fetch-data="fetchData" :scroll-x="undefined" />
</template>

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