<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { Category, CategorySearchFilter } from '@/model/category'
import RegularPage from '@/components/RegularPage.vue'
import { searchCategoryRequest, deleteCategoryRequest } from '@/api/category'
import type { BaseTableColumns } from 'tdesign-vue-next'
import { useSearchable } from '@/composables/useSearchable'
import CategoryDialog from '@/pages/category/components/CategoryDialog.vue'
import { MessagePlugin } from 'tdesign-vue-next'

const { data, loading, pagination, onPageChange, fetchData } = useSearchable<
  CategorySearchFilter,
  Category
>(searchCategoryRequest)
const columns: BaseTableColumns = [
  {
    title: '分类名称',
    colKey: 'name',
    width: 100
  },
  {
    title: '分类编号',
    colKey: 'code',
    width: 100
  },
  {
    title: '排序',
    colKey: 'order',
    width: 100
  },
  {
    title: '操作',
    colKey: 'operation',
    width: 100
  }
]
const categoryDialogVisible = ref(false)
const isEdit = ref(false)
const currentTableData = ref<Category | {}>({})
onMounted(fetchData)
const editClick = (category: Category) => {
  isEdit.value = true
  currentTableData.value = category
  categoryDialogVisible.value = true
}
const handleCategoryDialogSuccess = () => {
  fetchData()
  categoryDialogVisible.value = false
}
const handleCategoryDialogClosed = () => {
  isEdit.value = false
  currentTableData.value = {}
}
const deleteCategoryClick = async (id: string) => {
  await deleteCategoryRequest(id)
  fetchData()
  MessagePlugin.success('删除分类成功')
}
</script>

<template>
  <RegularPage title="分类管理">
    <template #right-area>
      <TButton @click="categoryDialogVisible = true">创建分类</TButton>
    </template>
    <TTable
      class="w-full h-full"
      row-key="id"
      height="92%"
      table-layout="auto"
      :data="data"
      :loading="loading"
      :columns="columns"
      cell-empty-content="-"
      :paginationAffixedBottom="true"
      :pagination="{
        total: pagination.total,
        current: pagination.page,
        pageSize: pagination.size,
        onChange: onPageChange
      }"
    >
      <template #operation="{ row }">
        <TSpace :size="1">
          <TButton variant="text" size="small" theme="primary" @click="editClick(row)"
            >编辑</TButton
          >
          <t-popconfirm
            theme="default"
            content="确认删除此项分类吗"
            @confirm="deleteCategoryClick(row.id)"
          >
            <TButton variant="text" size="small" theme="danger">删除</TButton>
          </t-popconfirm>
        </TSpace>
      </template>
    </TTable>
    <CategoryDialog
      headerTitle="分类"
      :isEdit="isEdit"
      :category="currentTableData"
      v-model:visible="categoryDialogVisible"
      @closed="handleCategoryDialogClosed"
      @success="handleCategoryDialogSuccess"
    ></CategoryDialog>
  </RegularPage>
</template>

<style scoped>
:deep(.t-card__body) {
  flex: 1;
  min-height: 0;
}
</style>
