#set ($subTable = $subTables.get($subIndex))##当前表
#set ($subColumns = $subColumnsList.get($subIndex))##当前字段数组
#set ($subJoinColumn = $subJoinColumns.get($subIndex))##当前 join 字段
#set ($subSimpleClassName = $subSimpleClassNames.get($subIndex))
#set ($subClassNameVar = $subClassNameVars.get($subIndex))
#set ($SubJoinColumnName = $subJoinColumn.javaField.substring(0,1).toUpperCase() + ${subJoinColumn.javaField.substring(1)})##首字母大写
<script lang="ts" setup>
  import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';

  import { ElMessage, ElTabs, ElTabPane, ElForm, ElFormItem, ElInput, ElButton, ElSelect, ElOption, ElRadioGroup, ElRadio, ElCheckboxGroup, ElCheckbox, ElDatePicker } from 'element-plus';
  import { computed, ref, reactive, h, onMounted,watch,nextTick } from 'vue';
  import { $t } from '#/locales';
  import { DICT_TYPE, getDictOptions } from '#/utils';

#if ($subTable.subJoinMany) ## 一对多
import type { VxeTableInstance } from '#/adapter/vxe-table';
import { Plus } from "@vben/icons";
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import { get${subSimpleClassName}ListBy${SubJoinColumnName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#else
import type { FormRules } from 'element-plus';
import { Tinymce as RichTextarea } from '#/components/tinymce';
import { get${subSimpleClassName}By${SubJoinColumnName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#end

const props = defineProps<{
   ${subJoinColumn.javaField}?: number // ${subJoinColumn.columnComment}（主表的关联字段）
}>()

#if ($subTable.subJoinMany) ## 一对多
const list = ref<${simpleClassName}Api.${subSimpleClassName}[]>([]) // 列表的数据
const tableRef = ref<VxeTableInstance>();
/** 添加${subTable.classComment} */
const onAdd = async () => {
  await tableRef.value?.insertAt({} as ${simpleClassName}Api.${subSimpleClassName}, -1);
}

/** 删除${subTable.classComment} */
const onDelete =  async (row: ${simpleClassName}Api.${subSimpleClassName}) => {
  await tableRef.value?.remove(row);
}

/** 提供获取表格数据的方法供父组件调用 */
defineExpose({
  getData: (): ${simpleClassName}Api.${subSimpleClassName}[] => {
    const data = list.value as ${simpleClassName}Api.${subSimpleClassName}[];
    const removeRecords = tableRef.value?.getRemoveRecords() as ${simpleClassName}Api.${subSimpleClassName}[];
    const insertRecords = tableRef.value?.getInsertRecords() as ${simpleClassName}Api.${subSimpleClassName}[];
    return data
        .filter((row) => !removeRecords.some((removed) => removed.id === row.id))
        ?.concat(insertRecords.map((row: any) => ({ ...row, id: undefined })));
  },
});

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
    () => props.${subJoinColumn.javaField},
    async (val) => {
      if (!val) {
        return;
      }
      list.value = await get${subSimpleClassName}ListBy${SubJoinColumnName}(props.${subJoinColumn.javaField}!);
    },
    { immediate: true },
);
#else
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 = reactive<FormRules>({
    #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
});
/** 暴露出表单校验方法和表单值获取方法 */
defineExpose({
  validate: async () => await formRef.value?.validate(),
  getValues: ()=> formData.value,
});

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
    () => props.${subJoinColumn.javaField},
    async (val) => {
      if (!val) {
        return;
      }
      await nextTick();
      formData.value = await get${subSimpleClassName}By${SubJoinColumnName}(props.${subJoinColumn.javaField}!);
    },
    { immediate: true },
);
#end
</script>

<template>
#if ($subTable.subJoinMany) ## 一对多
  <vxe-table ref="tableRef" :data="list" show-overflow class="mx-4">
      #foreach($column in $subColumns)
          #if ($column.createOperation || $column.updateOperation)
              #set ($comment = $column.columnComment)
              #set ($javaField = $column.javaField)
              #set ($javaType = $column.javaType)
              #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.id == $subJoinColumn.id) ## 特殊：忽略主子表的 join 字段，不用填写
              #elseif ($column.htmlType == "input" && !$column.primaryKey)## 忽略主键，不用在表单里
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-input v-model="row.${javaField}" />
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "imageUpload")## 图片上传
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <ImageUpload v-model="row.${javaField}" />
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "fileUpload")## 文件上传
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <FileUpload v-model="row.${javaField}" />
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "select")## 下拉框
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-select v-model="row.${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>
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "checkbox")## 多选框
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-checkbox-group v-model="row.${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>
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "radio")## 单选框
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-radio-group v-model="row.${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>
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "datetime")## 时间框
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-date-picker
                        v-model="row.${javaField}"
                        type="datetime"
                        value-format="x"
                        format="YYYY-MM-DD HH:mm:ss"
                    />
                  </template>
                </vxe-column>
              #elseif($column.htmlType == "textarea" || $column.htmlType == "editor")## 文本框
                <vxe-column field="${javaField}" title="${comment}" align="center">
                  <template #default="{row}">
                    <el-input v-model="row.${javaField}" type="textarea" />
                  </template>
                </vxe-column>
              #end
          #end
      #end
    <vxe-column field="operation" title="操作" align="center">
      <template #default="{row}">
        <el-button
            size="small"
            type="danger"
            link
            @click="onDelete(row as any)"
            v-access:code="['${permissionPrefix}:delete']"
        >
          {{ $t('ui.actionTitle.delete') }}
        </el-button>
      </template>
    </vxe-column>
  </vxe-table>
  <div class="flex justify-center mt-4">
    <el-button :icon="h(Plus)" type="primary" plain @click="onAdd" v-access:code="['${permissionPrefix}:create']">
      {{ $t('ui.actionTitle.create', ['${subTable.classComment}']) }}
    </el-button>
  </div>
#else
  <el-form
      ref="formRef"
      class="mx-4"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
  >
      #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)## 忽略主键，不用在表单里
                <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>
#end
</template>
