<template>
  <Dialog :title="title" v-bind="$attrs" cancel submit @submit="handleSubmit">
    <ElForm ref="form" :model="formModel" :rules="rules" label-width="100px">
      <ElFormItem label="文件类型" prop="name">
        <ElRadioGroup v-model="formModel.name">
          <ElRadio label="Page">页面</ElRadio>
          <ElRadio label="Block">区块</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="名称[EN]" prop="fileName">
        <ElInput v-model="formModel.fileName"></ElInput>
      </ElFormItem>
      <ElFormItem label="标题[CN]" prop="title">
        <ElInput v-model="formModel.title"></ElInput>
      </ElFormItem>
      <ElFormItem
        v-if="formModel.name === 'Page'"
        label="路由路径"
        prop="routePath">
        <ElInput v-model="formModel.routePath">
          <template #prepend>{{ routePrefix }}</template>
        </ElInput>
      </ElFormItem>
    </ElForm>
  </Dialog>
</template>
<script lang="ts" setup>
import { Dialog, IFile } from '@vtj/engine';
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRadioGroup,
  ElRadio,
  type FormInstance,
  type FormRules
} from 'element-plus';
import { ref, computed, reactive } from 'vue';
import useCore from '../hooks/useCore';

export interface Props {
  file: IFile | null;
}

const props = defineProps<Props>();
const emit = defineEmits(['submit']);

const { project, engine } = useCore();

const routePrefix = computed(() => {
  return engine.config.routePrefix + project.name.toLowerCase() + '/';
});
const formModel = reactive({
  name: props.file?.name || 'Page',
  fileName: props.file?.fileName || '',
  title: props.file?.title || '',
  routePath: ((props.file as any)?.routePath || '').replace(
    routePrefix.value,
    ''
  )
});

const rules = reactive<FormRules>({
  fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  routePath: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
});

const form = ref<FormInstance>();

const title = computed(() => {
  return props.file ? '编辑文件' : '新增文件';
});

async function handleSubmit() {
  form.value?.validate((valid) => {
    if (valid) {
      if (!project.validateFile(formModel as any, props.file)) {
        ElMessage.warning('已存在相同路径或名称的文档');
        return;
      }
      formModel.routePath = routePrefix.value + formModel.routePath;
      emit('submit', formModel);
    }
  });
}
</script>
