<template>
  <Dialog
    title="共享"
    width="400px"
    height="230px"
    submit
    cancel
    @close="onClose"
    @submit="onSubmit">
    <ElForm ref="form" size="small" :model="formModel" :rules="rules">
      <ElFormItem label="名称" prop="name">
        <ElInput v-model="formModel.name"></ElInput>
      </ElFormItem>
      <ElFormItem label="描述" prop="title">
        <ElInput v-model="formModel.title"></ElInput>
      </ElFormItem>
      <ElFormItem label="分类" prop="categoryId">
        <ElSelect v-model="formModel.categoryId">
          <ElOption
            v-for="item in categories"
            :key="item.id"
            :value="item.id"
            :label="item.category">
          </ElOption>
        </ElSelect>
      </ElFormItem>
    </ElForm>
  </Dialog>
</template>
<script lang="ts" setup>
import Dialog from './Dialog.vue';
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage
} from 'element-plus';
import { ref, computed } from 'vue';
import { useCore, IFile, PAGE_NAME, TemplateDescription } from '@vtj/engine';

export interface FormModel {
  name: string;
  title: string;
  categoryId: string;
}

const props = defineProps<{
  file: IFile;
}>();

const emit = defineEmits(['update:modelValue']);

const { engine } = useCore();
const form = ref();
const rules = {
  name: [{ required: true, message: '名称为必填项' }],
  title: [{ required: true, message: '描述为必填项' }],
  categoryId: [{ required: true, message: '分类为必填项' }]
};
const visible = ref(true);
const categories = computed(() => {
  const groupId = props.file.name === PAGE_NAME ? 'page' : 'block';
  const templateGroups = engine.assets.templateGroups || [];
  const item = templateGroups.find((n) => n.id === groupId);
  return item?.categories ?? [];
});

const formModel = ref<FormModel>({
  name: '',
  title: '',
  categoryId: ''
});

const createTemplate = () => {
  return {
    ...formModel.value,
    groupId: props.file.name === PAGE_NAME ? 'page' : 'block',
    schema: props.file.toSchema()
  } as TemplateDescription;
};

const onSubmit = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      const templateMap = engine.assets.templateMap;
      const template = createTemplate();
      if (templateMap[formModel.value.name]) {
        ElMessageBox.confirm('已存在相同名称的模板，是否替换？', '提示', {
          type: 'warning'
        }).then(() => {
          engine.assets.removeTemplate(formModel.value.name);
          engine.assets.addTemplate(template);
        });
      } else {
        engine.assets.addTemplate(template);
      }
      ElMessage.success({
        message: '共享模板成功'
      });
      emit('update:modelValue', false);
    }
  });
};

const onClose = () => {
  emit('update:modelValue', false);
};
</script>
