<script lang="ts" setup>
import { h, 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';
import Edit from './components/edit.vue';

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

const fetchData: TableFetchData = ({ pagination, filter }) => {
  return safeClient(() =>
    client.api.admin.spot_robot_trader.configs.get({
      query: {
        ...pagination,
        ...filter
      }
    })
  );
};

const columns: TableBaseColumns = [
  {
    key: 'selection',
    title: '序号',
    type: 'selection',
    width: 60
  },
  {
    key: 'id',
    title: 'ID',
    width: 100
  },
  {
    key: 'baseAsset',
    title: '基础资产',
    width: 120
  },
  {
    key: 'quoteAsset',
    title: '计价资产',
    width: 120
  },
  {
    key: 'robotUserId',
    title: '机器人用户ID',
    width: 150
  },
  {
    key: 'symbol',
    title: '交易对',
    width: 100
  },
  {
    key: 'baseTopUpAmount',
    title: '基础资产单次充值金额',
    width: 160
  },
  {
    key: 'buyPriceMax',
    title: '买入价格上限',
    width: 140
  },
  {
    key: 'buyPriceMin',
    title: '买入价格下限',
    width: 140
  },
  {
    key: 'buyPriceStep',
    title: '买入价格步长',
    width: 140
  },
  {
    key: 'createdAt',
    title: '创建时间',
    width: 180,
    render: (row: any) => {
      return useDateFormat(row.createdAt, 'YYYY-MM-DD HH:mm:ss').value;
    }
  },
  {
    key: 'enabled',
    title: '是否启用',
    width: 100,
    render: (row: any) => (row.enabled ? '是' : '否')
  },
  {
    key: 'operations',
    title: '操作',
    fixed: 'right',
    width: 150,
    operations: (row: any) => [
      {
        contentText: row.enabled ? '禁用' : '启用',
        type: 'primary',
        ghost: true,
        size: 'small',
        onClick: async () => {
          await safeClient(
            client.api.admin.spot_robot_trader.config.enable.post({
              id: row.id
            })
          );
          tableInst.value?.reload();
        }
      },
      {
        contentText: '编辑',
        type: 'primary',
        ghost: true,
        size: 'small',
        onClick: () => {
          handleEdit(row);
        }
      }
    ]
  }
];

function handleEdit(row: any) {
  const dialogInstance = dialog.create({
    title: '编辑现货机器人配置',
    content: () =>
      h(Edit, {
        data: row,
        onClose: () => {
          dialogInstance.destroy();
          tableInst.value?.reload();
        }
      }),
    style: { width: '600px' },
    showIcon: false
  });
}
</script>

<template>
  <TableBase ref="tableInst" show-header-operation :columns="columns" :fetch-data="fetchData" :scroll-x="1000" />
</template>

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