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

#if ($table.templateType == 11) ## erp
  import ${subSimpleClassName}Form from './${subSimpleClassName_strikeCase}-form.vue'
#end
  import { useVbenModal } from '@vben/common-ui';
  import { Button, message } from 'ant-design-vue';
  import { Plus } from '@vben/icons';
  import { #if($table.templateType != 11)ref,#end h, nextTick,watch } from 'vue';
  import { $t } from '#/locales';
  import { useVbenVxeGrid } from '#/adapter/vxe-table';


#if ($table.templateType == 11) ## erp
  import { delete${subSimpleClassName}, get${subSimpleClassName}Page } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  import { use${subSimpleClassName}GridFormSchema, use${subSimpleClassName}GridColumns } from '../data';
  #else
  #if ($subTable.subJoinMany) ## 一对多
  import { get${subSimpleClassName}ListBy${SubJoinColumnName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  #else
  import { get${subSimpleClassName}By${SubJoinColumnName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  #end
  import { use${subSimpleClassName}GridColumns } from '../data';
#end

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

#if ($table.templateType == 11) ## erp
  const [FormModal, formModalApi] = useVbenModal({
    connectedComponent: ${subSimpleClassName}Form,
    destroyOnClose: true,
  });

/** 创建${subTable.classComment} */
function onCreate() {
  if (!props.${subJoinColumn.javaField}){
    message.warning("请先选择一个${table.classComment}!")
    return
  }
  formModalApi.setData({${subJoinColumn.javaField}: props.${subJoinColumn.javaField}}).open();
}

/** 编辑${subTable.classComment} */
function onEdit(row: ${simpleClassName}Api.${subSimpleClassName}) {
  formModalApi.setData(row).open();
}

/** 删除${subTable.classComment} */
async function onDelete(row: ${simpleClassName}Api.${subSimpleClassName}) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await delete${subSimpleClassName}(row.id as number);
    message.success( $t('ui.actionMessage.deleteSuccess', [row.id]) );
    onRefresh();
  } catch {
    hideLoading();
  }
}

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

#end
  const [Grid, gridApi] = useVbenVxeGrid({
#if ($table.templateType == 11)
    formOptions: {
      schema: use${subSimpleClassName}GridFormSchema(),
    },
#end
    gridOptions: {
#if ($table.templateType == 11)
    columns: use${subSimpleClassName}GridColumns(onActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
              if (!props.${subJoinColumn.javaField}){
                  return []
              }
            return await get${subSimpleClassName}Page({
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ${subJoinColumn.javaField}: props.${subJoinColumn.javaField},
              ...formValues,
            });
          },
        },
      },
    pagerConfig: {
        enabled: true,
    },
    toolbarConfig: {
        refresh: { code: 'query' },
        search: true,
    },
#else
    columns: use${subSimpleClassName}GridColumns(),
    pagerConfig: {
        enabled: false,
    },
    toolbarConfig: {
        enabled: false,
    },
#end
    height: '600px',
    rowConfig: {
        keyField: 'id',
        isHover: true,
    },
    } as VxeTableGridOptions<${simpleClassName}Api.${subSimpleClassName}>,
  });

/** 刷新表格 */
const onRefresh = async ()=> {
#if ($table.templateType == 11) ## erp
    await gridApi.query();
#else
    #if ($subTable.subJoinMany) ## 一对多
    await gridApi.grid.loadData(await get${subSimpleClassName}ListBy${SubJoinColumnName}(props.${subJoinColumn.javaField}!));
    #else
    await gridApi.grid.loadData([await get${subSimpleClassName}By${SubJoinColumnName}(props.${subJoinColumn.javaField}!)]);
    #end
#end
}

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

<template>
    #if ($table.templateType == 11) ## erp
      <FormModal @success="onRefresh" />
      <Grid table-title="${subTable.classComment}列表">
        <template #toolbar-tools>
          <Button :icon="h(Plus)" type="primary" @click="onCreate" v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:create']">
            {{ $t('ui.actionTitle.create', ['${subTable.classComment}']) }}
          </Button>
        </template>
      </Grid>
    #else
      <Grid table-title="${subTable.classComment}列表" />
    #end
</template>
