<template>
    <PagingTable url="/categories" :query="query" ref="table">
        <template #filter>
            <ElButton :icon="Plus" @click="onEdit()">添加</ElButton>
        </template>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="name" label="名称" min-width="120" />
        <ElTableColumn prop="createdAt" label="创建时间" :formatter="timeFormatter" width="150" />
        <ElTableColumn label="操作" align="center" width="120">
            <template #default="{ row }">
                <ElButton @click="onEdit(row)">编辑</ElButton>
            </template>
        </ElTableColumn>
    </PagingTable>
    <EditDialog v-model="showEditDialog" :model="model" :rules="rules" :on-submit="submit" @success="table.refresh()">
        <ElFormItem prop="name" label="名称">
            <ElInput v-model="model.name" placeholder="请输入名称" />
        </ElFormItem>
    </EditDialog>
</template>
<script setup>
import { ref } from 'vue'
import PagingTable from '@/components/PagingTable.vue'
import { useTimeFormatter } from '@/utils/formatter'
import { Plus } from '@vicons/tabler'
import EditDialog from '@/components/EditDialog.vue'
import { setupEditDialog } from '@/utils/editDialog'
import { http } from '@/plugins/http'
import { ElMessage } from 'element-plus'
const query = ref({})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({})
const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}
const { showEditDialog } = setupEditDialog(model)
async function onEdit(row) {
    model.value = row ? await http.get(`/categories/${row.id}`) : {}
    showEditDialog.value = true
}
async function submit() {
    model.value.id
        ? await http.put(`/categories/${model.value.id}`, model.value)
        : await http.post('/categories', model.value)
    ElMessage.success('保存成功')
}
</script>
