<script lang="ts" setup>
import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${table.businessName}';

import { useVbenModal } from '@vben/common-ui';
import { ElMessage, ElTabs, ElTabPane, ElCheckbox, ElInput, ElSelect, ElRadioGroup, ElCheckboxGroup, ElDatePicker } from 'element-plus';
## 特殊：主子表专属逻辑
#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 { computed, ref } from 'vue';
import { $t } from '#/locales';
import { useVbenForm } from '#/adapter/form';
import { get${simpleClassName}, create${simpleClassName}, update${simpleClassName} } from '#/api/${table.moduleName}/${table.businessName}';

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

const emit = defineEmits(['success']);
const formData = ref<${simpleClassName}Api.${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 ${simpleClassName}Api.${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;
    }
    // 加载数据
    let data = modalApi.getData<${simpleClassName}Api.${simpleClassName}>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await get${simpleClassName}(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values
    formData.value = data;
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
    ## 特殊：主子表专属逻辑
    #if ( $table.templateType == 10 || $table.templateType == 12 )
      <!-- 子表的表单 -->
      <el-tabs 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))
          <el-tab-pane name="$subClassNameVar" label="${subTable.classComment}">
            <${subSimpleClassName}Form ref="${subClassNameVar}FormRef" :${subJoinColumn_strikeCase}="formData?.id" />
          </el-tab-pane>
        #end
      </el-tabs>
    #end
  </Modal>
</template>
