#set ($apiName = "${table.moduleName.substring(0,1).toUpperCase()}${table.moduleName.substring(1)}${simpleClassName}Api")
<script lang="ts" setup>
import type { ${apiName} } from '#/api/${table.moduleName}/${table.businessName}';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage#if ($table.templateType == 11), ElTabs, ElTabPane#end } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { create${simpleClassName}, get${simpleClassName}, update${simpleClassName} } from '#/api/${table.moduleName}/${table.businessName}';
import { $t } from '#/locales';
## 特殊：主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 )
  #foreach ($subSimpleClassName in $subSimpleClassNames)
  #set ($index = $foreach.count - 1)
  #set ($subSimpleClassName_strikeCase = $subSimpleClassName_strikeCases.get($index))
  import ${subSimpleClassName}Form from './${subSimpleClassName_strikeCase}-form.vue'
  #end
#end

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<${apiName}.${simpleClassName}>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['${table.classComment}'])
    : $t('ui.actionTitle.create', ['${table.classComment}']);
});
## 特殊：主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 )
  #if ( $subTables && $subTables.size() > 0 )

  /** 子表的表单 */
  const subTabsName = ref('$subClassNameVars.get(0)')
    #foreach ($subClassNameVar in $subClassNameVars)
      #set ($index = $foreach.count - 1)
      #set ($subSimpleClassName = $subSimpleClassNames.get($index))
      const ${subClassNameVar}FormRef = ref<InstanceType<typeof ${subSimpleClassName}Form>>()
    #end
  #end
#end

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
## 特殊：主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 )
      #if ( $subTables && $subTables.size() > 0 )
        // 校验子表单
        #foreach ($subTable in $subTables)
          #set ($index = $foreach.count - 1)
          #set ($subClassNameVar = $subClassNameVars.get($index))
          #if ($subTable.subJoinMany) ## 一对多
            ## TODO 列表值校验？
          #else
            const ${subClassNameVar}Valid = await ${subClassNameVar}FormRef.value?.validate();
            if (!${subClassNameVar}Valid) {
              subTabsName.value = '${subClassNameVar}';
              return;
            }
          #end
        #end
      #end
#end
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as ${apiName}.${simpleClassName};
## 特殊：主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 )
      #if ( $subTables && $subTables.size() > 0 )
        // 拼接子表的数据
        #foreach ($subTable in $subTables)
          #set ($index = $foreach.count - 1)
          #set ($subClassNameVar = $subClassNameVars.get($index))
          #if ($subTable.subJoinMany)
            data.${subClassNameVar}s = ${subClassNameVar}FormRef.value?.getData();
          #else
            data.${subClassNameVar} = await ${subClassNameVar}FormRef.value?.getValues();
          #end
        #end
      #end
#end
    try {
      await (formData.value?.id ? update${simpleClassName}(data) : create${simpleClassName}(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    const data = modalApi.getData<${apiName}.${simpleClassName}>();
    if (!data || !data.id) {
#if (${table.templateType} == 2)## 树表特有
      // 设置上级
      await formApi.setValues(data);
#end
      return;
    }
    modalApi.lock();
    try {
      formData.value = await get${simpleClassName}(data.id);
      // 设置到 values
      if (formData.value) {
        await formApi.setValues(formData.value);
      }
    } finally {
      modalApi.unlock();
    }
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
## 特殊：主子表专属逻辑
#if ( $table.templateType == 10 || $table.templateType == 12 )
      <!-- 子表的表单 -->
      <ElTabs v-model="subTabsName">
        #foreach ($subTable in $subTables)
          #set ($index = $foreach.count - 1)
          #set ($subClassNameVar = $subClassNameVars.get($index))
          #set ($subSimpleClassName = $subSimpleClassNames.get($index))
          #set ($subJoinColumn_strikeCase = $subJoinColumn_strikeCases.get($index))
          <ElTabPane name="$subClassNameVar" label="${subTable.classComment}">
            <${subSimpleClassName}Form ref="${subClassNameVar}FormRef" :${subJoinColumn_strikeCase}="formData?.id" />
          </ElTabPane>
        #end
      </ElTabs>
#end
  </Modal>
</template>
