<script lang="ts" setup>
import { useTemplateRef } from 'vue';
import { NSelect } from 'naive-ui';
import dayjs from 'dayjs';
import { client, safeClient } from '@/service/api';
import type { TableBaseColumns, TableFetchData, TableFilterColumns, TableInst } from '@/components/table';
import UserSelect from '@/components/common/user-select.vue';

defineOptions({
  name: 'DepositPage'
});

const props = defineProps<{
  userId?: string;
  productId?: string;
}>();

enum DepositStatus {
  pending = '确认中',
  locked = '认购成功',
  unlocked = '收益已发放',
  cancelled = '已取消'
}

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

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

const columns: TableBaseColumns = [
  {
    key: 'product.name',
    title: '产品名称',
    fixed: 'left'
  },
  {
    key: 'user.name',
    title: '认购用户'
  },
  {
    key: 'user.username',
    title: '认购用户手机号'
  },
  {
    key: 'walletType.name',
    title: '认购钱包'
  },
  {
    key: 'price',
    title: '价格(元)',
    render: (row: any) => {
      return Number(row.price);
    }
  },
  {
    key: 'maturityYield',
    title: '到期收益(元)',
    render: (row: any) => {
      return Number(row.maturityYield);
    }
  },
  {
    key: 'cycleDays',
    title: '周期(天)'
  },
  {
    key: 'status',
    title: '订阅状态',
    render: (row: any) => {
      return DepositStatus[row.status];
    }
  },
  {
    key: 'createdAt',
    title: '创建时间',
    render: (row: any) => {
      return dayjs(row.createdAt).format('YYYY-MM-DD HH:mm');
    }
  }
  // {
  //   key: 'operations',
  //   title: '操作',
  //   width: 150,
  //   fixed: 'right',
  //   operations: (row: any) => []
  // }
];

const filterColumns: TableFilterColumns = [
  {
    key: 'userId',
    title: '用户',
    component: UserSelect
  },
  {
    key: 'productId',
    title: '产品ID'
  },
  {
    key: 'status',
    title: '状态',
    component: NSelect,
    componentProps: {
      clearable: true,
      options: [
        { label: '确认中', value: 'pending' },
        { label: '认购成功', value: 'locked' },
        { label: '收益已发放', value: 'unlocked' },
        { label: '已取消', value: 'cancelled' }
      ]
    }
  }
];
</script>

<template>
  <TableBase
    ref="tableInst"
    :fetch-data="fetchData"
    :columns="columns"
    :filter-columns="filterColumns"
    :scroll-x="1500"
    :show-header-operation="true"
    :header-operations="{
      add: false,
      refresh: true,
      columns: true
    }"
    v-bind="{ ...$attrs }"
  />
</template>

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