<script setup lang="ts">
import type { ColumnDef } from '@tanstack/vue-table'

import { computed } from 'vue'

import type { DataTableProps } from '@/components/data-table/types'
import type { AgentApp } from '@/pages/admin/agent-apps/data/schema'

import BulkActions from '@/components/data-table/bulk-actions.vue'
import DataTable from '@/components/data-table/data-table.vue'
import { SelectColumn } from '@/components/data-table/table-columns'
import { generateVueTable } from '@/components/data-table/use-generate-vue-table'
import DataTableViewOptions from '@/components/data-table/view-options.vue'
import { getColumns } from '@/pages/admin/agent-apps/components/columns'

const props = defineProps<Omit<DataTableProps<AgentApp>, 'columns'> & {
  onView: (row: AgentApp) => void
  onEdit: (row: AgentApp) => void
  onDelete: (row: AgentApp) => void
}>()

const emit = defineEmits<{
  refresh: []
  batchDelete: [ids: (string | number)[]]
}>()

const columns = computed(() => [
  SelectColumn as ColumnDef<AgentApp>,
  ...getColumns({
    onView: props.onView,
    onEdit: props.onEdit,
    onDelete: props.onDelete,
  }),
])

const table = generateVueTable<AgentApp>({
  get data() { return props.data },
  get loading() { return props.loading },
  columns: columns.value,
})

const columnLabels: Record<string, string> = {
  'select': '选择',
  'agent_name': '代理',
  'app_name': '应用',
  'card_types': '卡密权限',
  'balance': '余额',
  'status': '状态',
  'created_at': '授权时间',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table @refresh="emit('refresh')">
    <template #toolbar>
      <div class="space-y-3">
        <div class="flex items-center justify-end">
          <slot name="actions" />
        </div>
        <BulkActions :table="table" entity-name="agent-apps">
          <UiButton variant="destructive" size="sm" @click="emit('batchDelete', table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])">
            批量移除
          </UiButton>
        </BulkActions>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div class="flex flex-wrap items-center gap-2">
            <slot name="filters" />
          </div>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
