<script setup lang="ts">
import { ref, reactive, toRaw, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import _ from "lodash";
import type { TreeData } from "./Tree";

const props = defineProps<{ contextData: TreeData; appendLoading: boolean }>();
const show = defineModel<boolean>("show");
const emit = defineEmits(["ok", "cancel"]);

const form$ = ref<FormInstance>();
const formData = reactive({
  isDir: false,
  filename: "",
});
const rules = reactive<FormRules<typeof formData>>({
  filename: [
    {
      validator: (rule, value, callback, source, options) => {
        if (
          _.includes(
            props.contextData.children?.map((c) => c.key),
            `${props.contextData.key ? `${props.contextData.key}/` : ""}${value}`
          )
        ) {
          callback("文件重名");
        }
        callback();
      },
      trigger: "change",
    },
    {
      pattern: /[^\\/:"*?<>|]/,
      message: '有非法字符: \\/:"*?<>|',
      trigger: "change",
    },
  ],
});

const onOk = async () => {
  try {
    const result = await form$.value?.validate();
    if (result) {
      const data = _.cloneDeep(toRaw(formData))
      if (!formData.isDir) {
        data.filename = `${data.filename}.md`
      }
      emit("ok", data);
    }
  } catch (e) {
    console.warn(e);
  }
};
const onCancel = () => {
  emit("cancel");
  show.value = false;
};
watch(
  () => show.value,
  () => {
    if (!show.value) {
      form$.value?.resetFields();
    }
  }
);
</script>
<template>
  <el-dialog width="400px" v-model="show">
    <el-form ref="form$" :model="formData" :rules="rules">
      <el-form-item label="是否文件夹" prop="isDir">
        <el-switch v-model="formData.isDir" inline-prompt></el-switch>
      </el-form-item>
      <el-form-item :label="formData.isDir ? '文件夹名' : '文件名'" prop="filename">
        <el-input v-model="formData.filename">
          <template v-if="!formData.isDir" #append>.md</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="!formData.filename"
          :loading="appendLoading"
          @click="onOk"
          type="primary"
          >ok</el-button
        >
        <el-button @click="onCancel">cancel</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
