<template>
    <PagingTable url="/banners" :query="query" ref="table">
        <template #filter>
            <ElButton :icon="Plus" @click="onEdit()">添加</ElButton>
        </template>
        <ElTableColumn prop="id" label="#" width="80" />
        <ElTableColumn prop="title" label="名称" min-width="120" />
        <ElTableColumn prop="img" label="图片" min-width="120">
            <template #default="{ row }">
                <RImage style="width: 30px; height: 35px; vertical-align: middle" :src="row.img" fit="cover" />
            </template>
        </ElTableColumn>
        <ElTableColumn prop="desc" 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="title" label="名称">
            <ElInput v-model="model.title" placeholder="请输入名称" />
        </ElFormItem>
        <ElFormItem prop="img" label="图片">
            <SingleUpload v-model="model.img" />
        </ElFormItem>
        <ElFormItem prop="desc" label="描述">
            <ElInput v-model="model.desc" placeholder="请输入描述" />
        </ElFormItem>
        <ElFormItem prop="link" label="链接">
            <ElInput v-model="model.link" 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'
import RImage from '@/components/RImage.vue'
import SingleUpload from '@/components/SingleUpload.vue'
const query = ref({})
const timeFormatter = useTimeFormatter()
const table = ref(null)
const model = ref({})
const rules = {
    title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    img: [{ required: true, message: '请上传图片', trigger: 'blur' }],
}
const { showEditDialog } = setupEditDialog(model)
async function onEdit(row) {
    model.value = row ? await http.get(`/banners/${row.id}`) : {}
    showEditDialog.value = true
}
async function submit() {
    model.value.id
        ? await http.put(`/banners/${model.value.id}`, model.value)
        : await http.post('/banners', model.value)
    ElMessage.success('保存成功')
}
</script>
