<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="笔记标题" prop="title">
        <el-input v-model="form.title" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="选择分类" prop="groupingId">
        <el-cascader
            v-model="form.groupingId"
            :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="私密笔记">
        <el-switch
            v-model="form.isPrivate"
            :active-value="1"
            :inactive-value="0"
            active-text="私密"
            inactive-text="公开"
        />
        <div class="form-item-help">私密笔记只有登录用户才能查看内容</div>
      </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';

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

const emit = defineEmits(['update:visible', 'create-note']);

const formRef = ref(null);
const form = ref({
  title: '',
  groupingId: null,
  isPrivate: 0,
});

const rules = ref({
  title: [{ required: true, message: '请输入笔记标题', trigger: 'blur' }],
  groupingId: [{ required: true, message: '请选择分类', trigger: 'change' }],
});

watch(() => props.visible, (newVal) => {
  if (!newVal && formRef.value) {
    formRef.value.resetFields();
    form.value = { title: '', groupingId: null, isPrivate: 0 };
  }
});

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

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid) => {
    if (valid) {
      const payload = {
        id: null,
        title: form.value.title,
        groupingId: form.value.groupingId,
        fileName: form.value.title + '.md',
        content: '',
        isPrivate: form.value.isPrivate,
      };
      emit('create-note', payload);
      handleClose();
    } else {
      ElMessage.error('请填写必要的字段');
    }
  });
};
</script>

<style scoped>
.form-item-help {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.5;
}
</style>
