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

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

import DataSearch from './DataSearch.vue';

const props = defineProps<{
  tableInfo: any;
  tableData: any[];
  loading: boolean;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}>();

const emit = defineEmits<{
  'add-data': [];
  'edit-data': [record: any];
  'delete-data': [record: any];
  'batch-delete': [records: any[]];
  'page-change': [page: number, pageSize: number];
  'search': [conditions: any[]];
}>();

const selectedRowKeys = ref<any[]>([]);
const searchConditions = ref<any[]>([]);

const tableColumns = computed(() => {
  if (!props.tableInfo?.columns) return [];
  return [
    {
      title: '',
      key: 'selection',
      width: 50,
      fixed: 'left',
      customRender: ({ record }: any) => {
        const key = getRowKey(record);
        return h('input', {
          type: 'checkbox',
          checked: selectedRowKeys.value.includes(key),
          onChange: (e: any) => {
            if (e.target.checked) {
              selectedRowKeys.value.push(key);
            } else {
              const index = selectedRowKeys.value.indexOf(key);
              if (index > -1) {
                selectedRowKeys.value.splice(index, 1);
              }
            }
          },
        });
      },
    },
    ...props.tableInfo.columns.map((col: any) => ({
      title: col.comment || col.name,
      dataIndex: col.name,
      key: col.name,
    })),
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      customRender: ({ record }: any) =>
        h('div', { class: 'flex gap-2' }, [
          h(Button, {
            type: 'link',
            size: 'small',
            onClick: () => emit('edit-data', record),
          }, () => '编辑'),
          h(Popconfirm, {
            title: '确定删除这条数据吗？',
            onConfirm: () => emit('delete-data', record),
          }, {
            default: () =>
              h(Button, {
                type: 'link',
                danger: true,
                size: 'small',
              }, () => '删除'),
          }),
        ]),
    },
  ];
});

// 获取行的唯一标识
const getRowKey = (record: any) => {
  // 尝试使用id字段，如果没有则使用第一个字段
  if (record.id !== undefined) {
    return record.id;
  }
  const firstKey = Object.keys(record)[0];
  return record[firstKey];
};

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedRowKeys.value = props.tableData.map((record) => getRowKey(record));
  } else {
    selectedRowKeys.value = [];
  }
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    return;
  }
  const selectedRecords = props.tableData.filter((record) =>
    selectedRowKeys.value.includes(getRowKey(record)),
  );
  emit('batch-delete', selectedRecords);
};

// 搜索
const handleSearch = () => {
  emit('search', searchConditions.value);
};

// 重置搜索
const handleResetSearch = () => {
  searchConditions.value = [];
  emit('search', []);
};
</script>

<template>
  <div>
    <!-- 高级搜索 -->
    <DataSearch
      :columns="tableInfo?.columns || []"
      v-model="searchConditions"
      @search="handleSearch"
      @reset="handleResetSearch"
    />

    <!-- 操作栏 -->
    <div class="mb-4 flex items-center justify-between">
      <div class="flex items-center gap-2">
        <Button type="primary" @click="emit('add-data')">
          <i class="fa-solid fa-plus mr-2"></i>添加数据
        </Button>
        <Popconfirm
          v-if="selectedRowKeys.length > 0"
          :title="`确定删除选中的 ${selectedRowKeys.length} 条数据吗？`"
          @confirm="handleBatchDelete"
        >
          <Button type="primary" danger>
            <i class="fa-solid fa-trash mr-2"></i>批量删除 ({{ selectedRowKeys.length }})
          </Button>
        </Popconfirm>
      </div>
      <div v-if="selectedRowKeys.length > 0" class="text-sm text-gray-500">
        已选择 {{ selectedRowKeys.length }} 条
      </div>
    </div>

    <!-- 数据表格 -->
    <Table
      :columns="tableColumns"
      :data-source="tableData"
      :loading="loading"
      :row-key="getRowKey"
      :pagination="{
        current: pagination.current,
        pageSize: pagination.pageSize,
        total: pagination.total,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条`,
      }"
      @change="(p: any) => emit('page-change', p.current, p.pageSize)"
    />
  </div>
</template>
