<script setup>
import { ElMessage } from 'element-plus'
import { createCategory, updateCategory } from '../api'

const props = defineProps(['data'])

const emit = defineEmits(['update', 'update:modelValue'])

const isUpdate = computed(() => !!props.data?.id)
const title = computed(() => (isUpdate.value ? '编辑类别' : '添加类别'))

const formRef = ref()
const form = reactive({
  name: '',
  status: '1',
})

watchEffect(() => {
  if (props.data) Object.assign(form, props.data)
})

const rules = ref({
  name: [{ required: true, message: '请输入' }],
  status: [{ required: true, message: '请输入' }],
})

// 提交
async function handleSubmit() {
  await formRef.value?.validate()
  isUpdate.value ? handleUpdate() : handleAdd()
}

// 新建
async function handleAdd() {
  await createCategory(form)
  ElMessage({ message: '新增成功', type: 'success' })
  emit('update')
  emit('update:modelValue', false)
}

// 新建
async function handleUpdate() {
  await updateCategory(form)
  ElMessage({ message: '修改成功', type: 'success' })
  emit('update')
  emit('update:modelValue', false)
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" @closed="$emit('update:modelValue', false)">
    <el-row justify="center">
      <el-col :sm="24" :md="16">
        <el-form ref="formRef" :model="form" :rules="rules" label-position="top" @submit.prevent="handleSubmit">
          <el-form-item label="类别名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="form.status"
              active-text="生效"
              active-value="1"
              inactive-text="失效"
              inactive-value="0" />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
