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

import { useVbenModal } from '@vben/common-ui';
import { Tinymce as RichTextarea } from '#/components/tinymce';
import { ImageUpload, FileUpload } from "#/components/upload";
import { ElMessage, ElTabs, ElTabPane, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox, ElDatePicker, ElTreeSelect } from 'element-plus';
import { DICT_TYPE, getDictOptions } from '#/utils';
#if($table.templateType == 2)## 树表需要导入这些
import { get${simpleClassName}List } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
import { handleTree } from '@vben/utils'
#end
## 特殊：主子表专属逻辑
#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, reactive } from 'vue';
import { $t } from '#/locales';
import { get${simpleClassName}, create${simpleClassName}, update${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';

const emit = defineEmits(['success']);

const formRef = ref();
const formData = ref<Partial<${simpleClassName}Api.${simpleClassName}>>({
#foreach ($column in $columns)
  #if ($column.createOperation || $column.updateOperation)
    #if ($column.htmlType == "checkbox")
        $column.javaField: [],
    #else
        $column.javaField: undefined,
    #end
  #end
#end
});
const rules = reactive<FormRules>({
  #foreach ($column in $columns)
    #if (($column.createOperation || $column.updateOperation) && !$column.nullable && !${column.primaryKey})## 创建或者更新操作 && 要求非空 && 非主键
      #set($comment=$column.columnComment)
        $column.javaField: [{ required: true, message: '${comment}不能为空', trigger: #if($column.htmlType == 'select')'change'#else'blur'#end }],
    #end
  #end
});
## 特殊：树表专属逻辑
#if ( $table.templateType == 2 )
const ${classNameVar}Tree = ref<any[]>([]) // 树形结构
#end
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 resetForm = () => {
  formData.value = {
    #foreach ($column in $columns)
      #if ($column.createOperation || $column.updateOperation)
        #if ($column.htmlType == "checkbox")
            $column.javaField: [],
        #else
            $column.javaField: undefined,
        #end
      #end
    #end
  };
  formRef.value?.resetFields();
}

## 特殊：树表专属逻辑
#if ( $table.templateType == 2 )
/** 获得${table.classComment}树 */
const get${simpleClassName}Tree = async () => {
  ${classNameVar}Tree.value = []
  const data = await get${simpleClassName}List({});
  data.unshift({
    id: 0,
    name: '顶级${table.classComment}',
  });
    ${classNameVar}Tree.value = handleTree(data);
}
#end

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    await formRef.value?.validate();
    ## 特殊：主子表专属逻辑
    #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
            try {
              await ${subClassNameVar}FormRef.value?.validate()
            } catch (e) {
              subTabsName.value = '${subClassNameVar}'
              return
            }
          #end
        #end
      #end
    #end
    modalApi.lock();
    // 提交表单
    const data = formData.value 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} = ${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) {
      resetForm()
      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();
      }
    }
    formData.value = data;
#if ( $table.templateType == 2 )
    // 加载树数据
    await get${simpleClassName}Tree()
#end
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      #foreach($column in $columns)
        #if ($column.createOperation || $column.updateOperation)
          #set ($dictType = $column.dictType)
          #set ($javaField = $column.javaField)
          #set ($javaType = $column.javaType)
          #set ($comment = $column.columnComment)
          #if ($javaType == "Integer" || $javaType == "Long" || $javaType == "Byte" || $javaType == "Short")
            #set ($dictMethod = "number")
          #elseif ($javaType == "String")
            #set ($dictMethod = "string")
          #elseif ($javaType == "Boolean")
            #set ($dictMethod = "boolean")
          #end
          #if ( $table.templateType == 2 && $column.id == $treeParentColumn.id )
            <el-form-item label="${comment}" prop="${javaField}">
              <el-tree-select
                      v-model="formData.${javaField}"
                      :data="${classNameVar}Tree"
                #if ($treeNameColumn.javaField == "name")
                      :props="{
            label: 'name',
            value: 'id',
            children: 'children',
          }"
                #else
                      :props="{
                        label: '$treeNameColumn.javaField',
                        value: 'id',
                        children: 'children',
                        }"
                #end
                      check-strictly
                      default-expand-all
                      placeholder="请选择${comment}"
              />
            </el-form-item>
          #elseif ($column.htmlType == "input" && !$column.primaryKey)## 忽略主键，不用在表单里
            <el-form-item label="${comment}" prop="${javaField}">
              <el-input v-model="formData.${javaField}" placeholder="请输入${comment}" />
            </el-form-item>
          #elseif($column.htmlType == "imageUpload")## 图片上传
            <el-form-item label="${comment}" prop="${javaField}">
              <ImageUpload v-model="formData.${javaField}" />
            </el-form-item>
          #elseif($column.htmlType == "fileUpload")## 文件上传
            <el-form-item label="${comment}" prop="${javaField}">
              <FileUpload v-model="formData.${javaField}" />
            </el-form-item>
          #elseif($column.htmlType == "editor")## 文本编辑器
            <el-form-item label="${comment}" prop="${javaField}">
              <RichTextarea v-model="formData.${javaField}" height="500px" />
            </el-form-item>
          #elseif($column.htmlType == "select")## 下拉框
            <el-form-item label="${comment}" prop="${javaField}">
              <el-select v-model="formData.${javaField}" placeholder="请选择${comment}">
                #if ("" != $dictType)## 有数据字典
                  <el-option
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :value="dict.value"
                          :label="dict.label"
                  />
                #else##没数据字典
                  <el-option label="请选择字典生成" value="" />
                #end
              </el-select>
            </el-form-item>
          #elseif($column.htmlType == "checkbox")## 多选框
            <el-form-item label="${comment}" prop="${javaField}">
              <el-checkbox-group v-model="formData.${javaField}">
                #if ("" != $dictType)## 有数据字典
                  <el-checkbox
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :label="dict.value"
                 >
                    {{ dict.label }}
                  </el-checkbox>
                #else##没数据字典
                  <el-checkbox label="请选择字典生成" />
                #end
              </el-checkbox-group>
            </el-form-item>
          #elseif($column.htmlType == "radio")## 单选框
            <el-form-item label="${comment}" prop="${javaField}">
              <el-radio-group v-model="formData.${javaField}">
                #if ("" != $dictType)## 有数据字典
                  <el-radio
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                #else##没数据字典
                  <el-radio :label="1">请选择字典生成</el-radio>
                #end
              </el-radio-group>
            </el-form-item>
          #elseif($column.htmlType == "datetime")## 时间框
            <el-form-item label="${comment}" prop="${javaField}">
              <el-date-picker
                      v-model="formData.${javaField}"
                      value-format="x"
                      placeholder="选择${comment}"
              />
            </el-form-item>
          #elseif($column.htmlType == "textarea")## 文本框
            <el-form-item label="${comment}" prop="${javaField}">
              <el-input v-model="formData.${javaField}" type="textarea" placeholder="请输入${comment}" />
            </el-form-item>
          #end
        #end
      #end
    </el-form>
    ## 特殊：主子表专属逻辑
    #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>
