<template>
  <el-dialog
    v-model="visible"
    title="创建文件分组"
    width="400px"
    @close="handleCancel"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="分组名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入文件分组名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { createFileCate } from "@/api/file";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "success", "close"]);

const visible = ref(false);
const formRef = ref<any>(null);
const loading = ref(false);

const form = ref({
  name: "",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入文件分组名称", trigger: "blur" },
    { min: 1, max: 50, message: "名称长度在 1 到 50 个字符", trigger: "blur" },
  ],
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      // 打开对话框时，清空表单数据
      form.value.name = "";
      // 清除表单验证
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    }
  }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  if (!newVal) {
    emit("update:modelValue", false);
  }
});

// 取消
const handleCancel = () => {
  visible.value = false;
  form.value.name = "";
  if (formRef.value) {
    formRef.value.clearValidate();
  }
  emit("close");
};

// 提交
const handleSubmit = async () => {
  if (!formRef.value) {
    return;
  }

  // 表单验证
  try {
    await formRef.value.validate();
  } catch (error) {
    ElMessage.warning("请检查表单填写是否正确");
    return;
  }

  // 验证名称是否为空
  if (!form.value.name || form.value.name.trim() === "") {
    ElMessage.error("文件分组名称不能为空");
    return;
  }

  loading.value = true;
  try {
    const res = await createFileCate({
      name: form.value.name.trim(),
    });

    if (res.code === 200) {
      ElMessage.success("创建成功");
      visible.value = false;
      form.value.name = "";
      emit("success");
      emit("close");
    } else {
      ElMessage.error(res.msg || "创建失败");
    }
  } catch (error: any) {
    const errorMsg =
      error?.response?.data?.message || error?.message || "创建失败";
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  open: () => {
    form.value.name = "";
    visible.value = true;
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  },
});
</script>

<style scoped>
.create-category-dialog {
  width: 400px;
}
</style>
