<script lang="ts" setup>
import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';

import { Page, useVbenModal } from '@vben/common-ui';
import { Button, message,Tabs } from 'ant-design-vue';
import { Download, Plus } from '@vben/icons';
import Form from './modules/form.vue';

## 特殊：主子表专属逻辑
#if ( $table.templateType == 11 || $table.templateType == 12 )
    #foreach ($subSimpleClassName in $subSimpleClassNames)
    #set ($index = $foreach.count - 1)
    #set ($subSimpleClassName_strikeCase = $subSimpleClassName_strikeCases.get($index))
    import ${subSimpleClassName}List from './modules/${subSimpleClassName_strikeCase}-list.vue'
    #end
#end

import { ref, h } from 'vue';
import { $t } from '#/locales';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
#if (${table.templateType} == 2)## 树表接口
import { get${simpleClassName}List, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#else## 标准表接口
import { get${simpleClassName}Page, delete${simpleClassName}, export${simpleClassName} } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
#end
import { downloadByData } from '#/utils/download';

import { useGridColumns, useGridFormSchema } from './data';

#if ($table.templateType == 12 || $table.templateType == 11) ## 内嵌和erp情况
/** 子表的列表 */
const subTabsName = ref('$subClassNameVars.get(0)')
#if ($table.templateType == 11)
const select${simpleClassName} = ref<${simpleClassName}Api.${simpleClassName}>();
#end
#end

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

#if (${table.templateType} == 2)## 树表特有：控制表格展开收缩
/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}
#end

/** 刷新表格 */
function onRefresh() {
#if ($table.templateType == 12) ## 内嵌情况
  gridApi.reload();
#else
  gridApi.query();
#end
}

/** 创建${table.classComment} */
function onCreate() {
  formModalApi.setData({}).open();
}

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

#if (${table.templateType} == 2)## 树表特有：新增下级
/** 新增下级${table.classComment} */
function onAppend(row: ${simpleClassName}Api.${simpleClassName}) {
  formModalApi.setData({ ${treeParentColumn.javaField}: row.id }).open();
}
#end

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

/** 导出表格 */
async function onExport() {
  const data = await export${simpleClassName}(await gridApi.formApi.getValues());
  downloadByData(data, '${table.classComment}.xls');
}

/** 表格操作按钮的回调函数 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<${simpleClassName}Api.${simpleClassName}>) {
  switch (code) {
  #if (${table.templateType} == 2)## 树表特有：新增下级
    case 'append': {
      onAppend(row);
      break;
    }
  #end
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
#if (${table.templateType} == 11)
    height: '600px',
#else
    height: 'auto',
#end
#if (${table.templateType} == 2)## 树表设置
  treeConfig: {
    parentField: '${treeParentColumn.javaField}',
    rowField: 'id',
    transform: true,
    expandAll: true,
    reserve: true,
  },
  pagerConfig: {
    enabled: false,
  },
#else## 标准表设置
    pagerConfig: {
      enabled: true,
    },
#end
    proxyConfig: {
      ajax: {
#if (${table.templateType} == 2)## 树表数据加载
        query: async (_, formValues) => {
          return await get${simpleClassName}List(formValues);
        },
#else## 标准表数据加载
        query: async ({ page }, formValues) => {
          return await get${simpleClassName}Page({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
#end
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
#if (${table.templateType} == 11)
      isCurrent: true,
#end
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
    },
  } as VxeTableGridOptions<${simpleClassName}Api.${simpleClassName}>,
#if (${table.templateType} == 11)
  gridEvents:{
    cellClick: ({ row }: { row: ${simpleClassName}Api.${simpleClassName}}) => {
      select${simpleClassName}.value = row;
    },
  }
#end
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />

#if ($table.templateType == 11) ## erp情况
  <div>
#end
    <Grid table-title="${table.classComment}列表">
        #if ($table.templateType == 12) ## 内嵌情况
          <template #expand_content="{ row }">
            <!-- 子表的表单 -->
            <Tabs v-model:active-key="subTabsName" class="mx-8">
                #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))
                  <Tabs.TabPane key="$subClassNameVar" tab="${subTable.classComment}" force-render>
                    <${subSimpleClassName}List :${subJoinColumn_strikeCase}="row?.id" />
                  </Tabs.TabPane>
                #end
            </Tabs>
          </template>
        #end
      <template #toolbar-tools>
#if (${table.templateType} == 2)## 树表特有：展开/收缩按钮
        <Button @click="toggleExpand" class="mr-2">
          {{ isExpanded ? '收缩' : '展开' }}
        </Button>
#end
        <Button :icon="h(Plus)" type="primary" @click="onCreate" v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:create']">
          {{ $t('ui.actionTitle.create', ['${table.classComment}']) }}
        </Button>
        <Button
          :icon="h(Download)"
          type="primary"
          class="ml-2"
          @click="onExport"
          v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:export']"
        >
          {{ $t('ui.actionTitle.export') }}
        </Button>
      </template>
    </Grid>

#if ($table.templateType == 11) ## erp情况
    <!-- 子表的表单 -->
    <Tabs v-model:active-key="subTabsName" class="mt-2">
        #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))
          <Tabs.TabPane key="$subClassNameVar" tab="${subTable.classComment}" force-render>
            <${subSimpleClassName}List :${subJoinColumn_strikeCase}="select${simpleClassName}?.id" />
          </Tabs.TabPane>
        #end
    </Tabs>
    </div>
#end
  </Page>
</template>
