<template>
  <el-dialog
      :model-value="visible"
      title="新建分类"
      width="450px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
      <el-form-item label="父级分类">
        <el-cascader
            v-model="form.parentId"
            :options="categoryOptions"
            :props="cascaderProps"
            clearable
            filterable
            placeholder="不选则创建为一级分类"
            style="width: 100%;"
        >
          <template #default="{ node, data }">
            <span class="category-option">
              <el-icon class="category-icon">
                <Folder v-if="data.children && data.children.length > 0" />
                <Folder-Opened v-else-if="node.isLeaf" />
                <Folder v-else />
              </el-icon>
              <span class="category-name">{{ data.grouping }}</span>
              <span v-if="data.children && data.children.length > 0" class="category-count">
                ({{ data.children.length }})
              </span>
            </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input 
            v-model="form.name" 
            autocomplete="off"
            placeholder="请输入新分类名称"
            maxlength="50"
            show-word-limit
        ></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 { Folder, FolderOpened } from '@element-plus/icons-vue';
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' }],
});

// 级联选择器配置
const cascaderProps = {
  checkStrictly: true,
  emitPath: false,
  value: 'id',
  label: 'grouping',
  children: 'children'
};

// 当对话框关闭时，重置表单
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) {
        // 错误已在 axios 拦截器中显示，这里不再重复显示
        console.error('创建分类失败:', error);
      }
    }
  });
};
</script>

<style scoped>
.category-option {
  display: flex;
  align-items: center;
  gap: 6px;
}

.category-icon {
  color: #409eff;
  font-size: 16px;
}

.category-name {
  flex: 1;
}

.category-count {
  color: #909399;
  font-size: 12px;
}
</style>
