<template>
  <el-dialog
      :model-value="visible"
      title="新建分类"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="父级分类">
        <el-cascader
            v-model="form.parentId"
            :options="categoryOptions"
            :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'grouping' }"
            clearable
            placeholder="不选则为一级分类"
            style="width: 100%;"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { addGroupings } from '@/api/CommonApi.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  categoryOptions: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['update:visible', 'group-created']);

const formRef = ref(null);
const form = ref({
  name: '',
  parentId: null,
});

const rules = ref({
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
});

// 当对话框关闭时，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal && formRef.value) {
    formRef.value.resetFields();
    form.value = { name: '', parentId: null };
  }
});

const handleClose = () => {
  emit('update:visible', false);
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const payload = {
          grouping: form.value.name,
          parentId: form.value.parentId || 0,
        };
        await addGroupings(payload);
        ElMessage.success('分类创建成功');
        emit('group-created'); // 通知父组件刷新
        handleClose();
      } catch (error) {
        ElMessage.error('创建分类失败: ' + error.message);
      }
    }
  });
};
</script>
