#set ($subTable = $subTables.get($subIndex))##当前表
#set ($subColumns = $subColumnsList.get($subIndex))##当前字段数组
#set ($subJoinColumn = $subJoinColumns.get($subIndex))##当前 join 字段
#set ($subSimpleClassName = $subSimpleClassNames.get($subIndex))
<script lang="ts" setup>
  import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  import type { Rule } from 'ant-design-vue/es/form';

  import { useVbenModal } from '@vben/common-ui';
  import { Tinymce as RichTextarea } from '#/components/tinymce';
  import { ImageUpload, FileUpload } from "#/components/upload";
  import { message, Tabs, Form, Input, Textarea, Select, RadioGroup, Radio, CheckboxGroup, Checkbox, DatePicker, TreeSelect } from 'ant-design-vue';
  import { DICT_TYPE, getDictOptions } from '#/utils';

  import { computed, ref } from 'vue';
  import { $t } from '#/locales';

  import { get${subSimpleClassName}, create${subSimpleClassName}, update${subSimpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';

  const emit = defineEmits(['success']);
  const getTitle = computed(() => {
    return formData.value?.id
        ? $t('ui.actionTitle.edit', ['${subTable.classComment}'])
        : $t('ui.actionTitle.create', ['${subTable.classComment}']);
  });

  const formRef = ref();
  const formData = ref<Partial<${simpleClassName}Api.${subSimpleClassName}>>({
    #foreach ($column in $subColumns)
      #if ($column.createOperation || $column.updateOperation)
        #if ($column.htmlType == "checkbox")
            $column.javaField: [],
        #else
            $column.javaField: undefined,
        #end
      #end
    #end
  });
  const rules: Record<string, Rule[]> = {
    #foreach ($column in $subColumns)
      #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
  };

  const [Modal, modalApi] = useVbenModal({
    async onConfirm() {
      await formRef.value?.validate();

      modalApi.lock();
      // 提交表单
      const data = formData.value as ${simpleClassName}Api.${subSimpleClassName};
      try {
        await (formData.value?.id ? update${subSimpleClassName}(data) : create${subSimpleClassName}(data));
        // 关闭并提示
        await modalApi.close();
        emit('success');
        message.success({
          content: $t('ui.actionMessage.operationSuccess'),
          key: 'action_process_msg',
        });
      } finally {
        modalApi.unlock();
      }
    },
    async onOpenChange(isOpen: boolean) {
      if (!isOpen) {
        resetForm()
        return;
      }

      // 加载数据
      let data = modalApi.getData<${simpleClassName}Api.${subSimpleClassName}>();
      if (!data) {
        return;
      }
      if (data.id) {
        modalApi.lock();
        try {
          data = await get${subSimpleClassName}(data.id);
        } finally {
          modalApi.unlock();
        }
      }
      // 设置到 values
      formData.value = data;
    },
  });

  /** 重置表单 */
  const resetForm = () => {
    formData.value = {
      #foreach ($column in $subColumns)
        #if ($column.createOperation || $column.updateOperation)
          #if ($column.htmlType == "checkbox")
              $column.javaField: [],
          #else
              $column.javaField: undefined,
          #end
        #end
      #end
    };
    formRef.value?.resetFields();
  }
</script>

<template>
  <Modal :title="getTitle">
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
    >
      #foreach($column in $subColumns)
        #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 ($column.htmlType == "input" && !$column.primaryKey)## 忽略主键，不用在表单里
            <Form.Item label="${comment}" name="${javaField}">
              <Input v-model:value="formData.${javaField}" placeholder="请输入${comment}" />
            </Form.Item>
          #elseif($column.htmlType == "imageUpload")## 图片上传
            <Form.Item label="${comment}" name="${javaField}">
              <ImageUpload v-model:value="formData.${javaField}" />
            </Form.Item>
          #elseif($column.htmlType == "fileUpload")## 文件上传
            <Form.Item label="${comment}" name="${javaField}">
              <FileUpload v-model:value="formData.${javaField}" />
            </Form.Item>
          #elseif($column.htmlType == "editor")## 文本编辑器
            <Form.Item label="${comment}" name="${javaField}">
              <RichTextarea v-model="formData.${javaField}" height="500px" />
            </Form.Item>
          #elseif($column.htmlType == "select")## 下拉框
            <Form.Item label="${comment}" name="${javaField}">
              <Select v-model:value="formData.${javaField}" placeholder="请选择${comment}">
                #if ("" != $dictType)## 有数据字典
                  <Select.Option
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :value="dict.value"
                  >
                    {{ dict.label }}
                  </Select.Option>
                #else##没数据字典
                  <Select.Option label="请选择字典生成" value="" />
                #end
              </Select>
            </Form.Item>
          #elseif($column.htmlType == "checkbox")## 多选框
            <Form.Item label="${comment}" name="${javaField}">
              <CheckboxGroup v-model:value="formData.${javaField}">
                #if ("" != $dictType)## 有数据字典
                  <Checkbox
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :value="dict.value"
                  >
                    {{ dict.label }}
                  </Checkbox>
                #else##没数据字典
                  <Checkbox label="请选择字典生成" />
                #end
              </CheckboxGroup>
            </Form.Item>
          #elseif($column.htmlType == "radio")## 单选框
            <Form.Item label="${comment}" name="${javaField}">
              <RadioGroup v-model:value="formData.${javaField}">
                #if ("" != $dictType)## 有数据字典
                  <Radio
                          v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                          :key="dict.value"
                          :value="dict.value"
                  >
                    {{ dict.label }}
                  </Radio>
                #else##没数据字典
                  <Radio value="1">请选择字典生成</Radio>
                #end
              </RadioGroup>
            </Form.Item>
          #elseif($column.htmlType == "datetime")## 时间框
            <Form.Item label="${comment}" name="${javaField}">
              <DatePicker
                      v-model:value="formData.${javaField}"
                      valueFormat="x"
                      placeholder="选择${comment}"
              />
            </Form.Item>
          #elseif($column.htmlType == "textarea")## 文本框
            <Form.Item label="${comment}" name="${javaField}">
              <Textarea v-model:value="formData.${javaField}" placeholder="请输入${comment}" />
            </Form.Item>
          #end
        #end
      #end
    </Form>
  </Modal>
</template>
