<script setup lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { columns, searchFormSchemas } from './data'
import ProductFormModal from './ProductFormModal.vue'
import { BasicTable, TableAction, useTable } from '@/components/Table'
import { deleteProduct, getProductList } from '@/api/product'
import { useModal } from '@/components/Modal'
import type { Product } from '@/api/product/types'
import { useMessage } from '@/hooks/web/useMessage'
import { usePermission } from '@/hooks/web/usePermission'

defineOptions({ name: 'Product' })

const [registerModal, { openModal }] = useModal<Product>()

const { hasPermission } = usePermission()

const [register, { reload }] = useTable({
  api: getProductList,
  columns,
  formConfig: {
    schemas: searchFormSchemas,
    labelWidth: 80,
  },
  bordered: true,
  canResize: false,
  useSearchForm: true,
  actionColumn: {
    width: 220,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    auth: ['view', 'edit', 'delete'].map(code => `product_${code}`),
  },
})

async function handleDelete(id: string) {
  try {
    await deleteProduct(id)
    useMessage().createMessage.success('删除成功')
    reload()
  }
  catch {}
}
</script>

<template>
  <div>
    <BasicTable :api="async () => ([] as Product[])" @register="register">
      <template v-if="hasPermission('product_add')" #tableTitle>
        <a-button type="primary" @click="openModal">
          <PlusOutlined />
          新建
        </a-button>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'i-ant-design:file-search-outlined',
                label: '详情',
                auth: 'product_view',
                onClick: () => $router.push(`/product/detail/${record.id}`),
              },
              {
                icon: 'i-ant-design:edit-outlined',
                label: '编辑',
                auth: 'product_edit',
                onClick: () => openModal(true, record),
              },
              {
                icon: 'i-ant-design:delete-outlined',
                danger: true,
                label: '删除',
                auth: 'product_delete',
                popConfirm: {
                  title: '是否要删除数据？',
                  placement: 'left',
                  confirm: () => handleDelete(record.id),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

    <ProductFormModal @register="registerModal" @success="reload" />
  </div>
</template>
