<script setup lang="ts">
import { h } from 'vue';

import { Button, Popconfirm, Table } from 'ant-design-vue';

defineProps<{
  tableInfo: any;
  loading: boolean;
}>();

const emit = defineEmits<{
  'edit-table-comment': [];
  'edit-column-comment': [column: any];
  'edit-column': [column: any];
  'add-column': [];
  'delete-column': [column: any];
}>();

const columns = [
  { title: '字段名', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'column_type', key: 'column_type' },
  {
    title: '允许NULL',
    dataIndex: 'nullable',
    key: 'nullable',
    customRender: ({ text }: any) => (text ? '是' : '否'),
  },
  { title: '默认值', dataIndex: 'default_value', key: 'default_value' },
  { title: '键', dataIndex: 'key_type', key: 'key_type' },
  { title: '注释', dataIndex: 'comment', key: 'comment' },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    customRender: ({ record }: any) =>
      h('div', { class: 'flex gap-2' }, [
        h(Button, {
          type: 'link',
          size: 'small',
          onClick: () => emit('edit-column', record),
        }, () => '编辑'),
        h(Button, {
          type: 'link',
          size: 'small',
          onClick: () => emit('edit-column-comment', record),
        }, () => '注释'),
        h(Popconfirm, {
          title: '确定删除此字段吗？此操作不可恢复！',
          onConfirm: () => emit('delete-column', record),
        }, {
          default: () =>
            h(Button, {
              type: 'link',
              danger: true,
              size: 'small',
            }, () => '删除'),
        }),
      ]),
  },
];
</script>

<template>
  <div v-if="loading" class="flex h-64 items-center justify-center">
    <i class="fa-solid fa-spinner fa-spin text-2xl text-primary"></i>
  </div>
  <div v-else-if="tableInfo">
    <div class="mb-4 flex items-center justify-between">
      <div>
        <div class="text-sm text-gray-600 dark:text-gray-400 mb-2">
          表注释：
          <span class="font-medium text-gray-900 dark:text-gray-100">
            {{ tableInfo.comment || '无' }}
          </span>
          <Button type="link" size="small" @click="emit('edit-table-comment')">
            编辑
          </Button>
        </div>
        <div class="text-xs text-gray-500">
          引擎: {{ tableInfo.engine }} | 字符集: {{ tableInfo.collation }} | 记录数: {{ tableInfo.rows }}
        </div>
      </div>
      <Button type="primary" @click="emit('add-column')">
        <i class="fa-solid fa-plus mr-2"></i>添加字段
      </Button>
    </div>
    <Table
      :columns="columns"
      :data-source="tableInfo.columns"
      :pagination="false"
      size="small"
      :scroll="{ x: 1000 }"
    />
  </div>
</template>
