#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}/${table.businessName}';

  import { computed, ref, h, onMounted,watch,nextTick } from 'vue';
  import { $t } from '#/locales';

#if ($subTable.subJoinMany) ## 一对多
import { Plus } from "@vben/icons";
import { ElButton, ElTabs, ElTabPane, ElCheckbox, ElInput, ElSelect, ElOption, ElRadioGroup, ElCheckboxGroup, ElDatePicker } from 'element-plus';
import { ImageUpload, FileUpload } from "#/components/upload";
import type { OnActionClickParams } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { use${subSimpleClassName}GridEditColumns } from '../data';
import { get${subSimpleClassName}ListBy${SubJoinColumnName} } from '#/api/${table.moduleName}/${table.businessName}';
#else
import { useVbenForm } from '#/adapter/form';
import { use${subSimpleClassName}FormSchema } from '../data';
import { get${subSimpleClassName}By${SubJoinColumnName} } from '#/api/${table.moduleName}/${table.businessName}';
#end

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

#if ($subTable.subJoinMany) ## 一对多
/** 表格操作按钮的回调函数 */
function onActionClick({
 code,
 row,
}: OnActionClickParams<${simpleClassName}Api.${subSimpleClassName}>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
  columns: use${subSimpleClassName}GridEditColumns(onActionClick),
  border: true,
  showOverflow: true,
  autoResize: true,
  keepSource: true,
  rowConfig: {
    keyField: 'id',
  },
  pagerConfig: {
    enabled: false,
  },
  toolbarConfig: {
    enabled: false,
  },
},
});

/** 添加${subTable.classComment} */
const onAdd = async () => {
  await gridApi.grid.insertAt({} as ${simpleClassName}Api.${subSimpleClassName}, -1);
}

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

/** 提供获取表格数据的方法供父组件调用 */
defineExpose({
  getData: (): ${simpleClassName}Api.${subSimpleClassName}[] => {
    const data = gridApi.grid.getData() as ${simpleClassName}Api.${subSimpleClassName}[];
    const removeRecords = gridApi.grid.getRemoveRecords() as ${simpleClassName}Api.${subSimpleClassName}[];
    const insertRecords = gridApi.grid.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;
      }
      await nextTick();
      await gridApi.grid.loadData(await get${subSimpleClassName}ListBy${SubJoinColumnName}(props.${subJoinColumn.javaField}!));
    },
    { immediate: true },
);
#else
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: use${subSimpleClassName}FormSchema(),
  showDefaultActions: false
});

/** 暴露出表单校验方法和表单值获取方法 */
defineExpose({
  validate: async () => {
    const { valid } = await formApi.validate();
    return valid;
  },
  getValues: formApi.getValues,
});

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

<template>
#if ($subTable.subJoinMany) ## 一对多
  <Grid class="mx-4">
      #foreach($column in $subColumns)
          #if ($column.createOperation || $column.updateOperation)
              #set ($javaField = $column.javaField)
              #if ( $column.id == $subJoinColumn.id) ## 特殊：忽略主子表的 join 字段，不用填写
              #elseif ($column.htmlType == "input" && !$column.primaryKey)## 忽略主键，不用在表单里
                <template #${javaField}="{ row }">
                  <el-input v-model="row.${javaField}" />
                </template>
              #elseif($column.htmlType == "imageUpload")## 图片上传
                <template #${javaField}="{ row }">
                  <ImageUpload v-model="row.${javaField}" />
                </template>
              #elseif($column.htmlType == "fileUpload")## 文件上传
                <template #${javaField}="{ row }">
                  <FileUpload v-model="row.${javaField}" />
                </template>
              #elseif($column.htmlType == "select")## 下拉框
                <template #${javaField}="{ row, column }">
                  <el-select v-model="row.${javaField}" class="w-full">
                    <el-option v-for="option in column.params.options" :key="option.value" :value="option.value" :label="option.label" />
                  </el-select>
                </template>
              #elseif($column.htmlType == "checkbox")## 多选框
                <template #${javaField}="{ row, column }">
                  <el-checkbox-group v-model="row.${javaField}">
                    <el-checkbox v-for="option in column.params.options" :key="option.value" :label="option.value">
                      {{ option.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </template>
              #elseif($column.htmlType == "radio")## 单选框
                <template #${javaField}="{ row, column }">
                  <el-radio-group v-model="row.${javaField}">
                    <el-radio v-for="option in column.params.options" :key="option.value" :label="option.value">
                      {{ option.label }}
                    </el-radio>
                  </el-radio-group>
                </template>
              #elseif($column.htmlType == "datetime")## 时间框
                <template #${javaField}="{ row }">
                  <el-date-picker
                      v-model="row.${javaField}"
                      type="datetime"
                      value-format="x"
                      format="YYYY-MM-DD HH:mm:ss"
                  />
                </template>
              #elseif($column.htmlType == "textarea" || $column.htmlType == "editor")## 文本框
                <template #${javaField}="{ row }">
                  <el-input v-model="row.${javaField}" type="textarea" />
                </template>
              #end
          #end
      #end
  </Grid>
  <div class="flex justify-center -mt-4">
    <el-button :icon="Plus" type="primary" plain @click="onAdd" v-access:code="['${subTable.moduleName}:${simpleClassName_strikeCase}:create']">
      {{ $t('ui.actionTitle.create', ['${subTable.classComment}']) }}
    </el-button>
  </div>
#else
  <Form class="mx-4" />
#end
</template>
