#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 { ${simpleClassName}Api } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  import type { VxeTableInstance } from 'vxe-table';

  import { DictTag } from '#/components/dict-tag';
  import { DICT_TYPE, getDictOptions } from '#/utils';
  import { VxeColumn, VxeTable } from 'vxe-table';
  import { reactive,ref, h, nextTick,watch,onMounted } from 'vue';
  import { cloneDeep, formatDateTime } from '@vben/utils';
  import { ContentWrap } from "#/components/content-wrap";

#if ($table.templateType == 11) ## erp
    import { useVbenModal } from '@vben/common-ui';
    import ${subSimpleClassName}Form from './${subSimpleClassName_strikeCase}-form.vue'
    import { Tinymce as RichTextarea } from '#/components/tinymce';
    import { ImageUpload, FileUpload } from "#/components/upload";
    import { message,Button, Tabs,Pagination, Form, Input, Textarea, Select, RadioGroup, Radio, CheckboxGroup, Checkbox,RangePicker, DatePicker, TreeSelect } from 'ant-design-vue';
    import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';
    import { Plus } from '@vben/icons';
    import { $t } from '#/locales';
    import { TableToolbar } from '#/components/table-toolbar';
#end

#if ($table.templateType == 11) ## erp
  import { delete${subSimpleClassName}, get${subSimpleClassName}Page } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
  #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
#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({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_process_msg',
    });
    getList();
  } catch {
    hideLoading();
  }
}
#end

  const loading = ref(true) // 列表的加载中
  const list = ref<${simpleClassName}Api.${subSimpleClassName}[]>([]) // 列表的数据
#if ($table.templateType == 11) ## erp
  const total = ref(0) // 列表的总页数
#end
#if ($table.templateType == 11) ## erp
  const queryFormRef = ref() // 搜索的表单
  const queryParams = reactive({
      pageNo: 1,
      pageSize: 10,
      #foreach ($column in $subColumns)
          #if ($column.listOperation)
              #if ($column.listOperationCondition != 'BETWEEN')
                      $column.javaField: undefined,
              #end
              #if ($column.htmlType == "datetime" || $column.listOperationCondition == "BETWEEN")
                      $column.javaField: undefined,
              #end
          #end
      #end
  })

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
#end
  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
      if (!props.${subJoinColumn.javaField}){
        return []
      }
        ## 特殊：树表专属逻辑（树不需要分页接口）
        #if ($table.templateType == 11) ## erp
          const params = cloneDeep(queryParams) as any;
            #foreach ($column in $columns)
                #if ($column.listOperation)
                    #if ($column.htmlType == "datetime" || $column.listOperationCondition == "BETWEEN")
                      if (params.${column.javaField} && Array.isArray(params.${column.javaField})) {
                        params.${column.javaField} = (params.${column.javaField} as string[]).join(',');
                      }
                    #end
                #end
            #end
          params.${subJoinColumn.javaField} = props.${subJoinColumn.javaField};
          const data = await get${subSimpleClassName}Page(params)
          list.value = data.list
          total.value = data.total
        #else
            #if ($subTable.subJoinMany) ## 一对多
             list.value = await get${subSimpleClassName}ListBy${SubJoinColumnName}(props.${subJoinColumn.javaField}!);
            #else
             list.value = [await get${subSimpleClassName}By${SubJoinColumnName}(props.${subJoinColumn.javaField}!)];
            #end
        #end
    } finally {
      loading.value = false
    }
  }

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

#if ($table.templateType == 11) ## erp
/** 隐藏搜索栏 */
const hiddenSearchBar = ref(false);
const tableToolbarRef = ref<InstanceType<typeof TableToolbar>>();
const tableRef = ref<VxeTableInstance>();

/** 初始化 */
onMounted(async () => {
  await getList();
  await nextTick();
  // 挂载 toolbar 工具栏
  const table = tableRef.value;
  const tableToolbar = tableToolbarRef.value;
  if (table && tableToolbar) {
    await table.connect(tableToolbar.getToolbarRef()!);
  }
});
#end
</script>

<template>
    #if ($table.templateType == 11) ## erp
      <FormModal @success="getList" />
      <div class="h-[600px]">
        <ContentWrap v-if="!hiddenSearchBar">
          <!-- 搜索工作栏 -->
          <Form
              :model="queryParams"
              ref="queryFormRef"
              layout="inline"
          >
              #foreach($column in $subColumns)
                  #if ($column.listOperation)
                      #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")
                        <Form.Item label="${comment}" name="${javaField}">
                          <Input
                              v-model:value="queryParams.${javaField}"
                              placeholder="请输入${comment}"
                              allowClear
                              @pressEnter="handleQuery"
                              class="w-full"
                          />
                        </Form.Item>
                      #elseif ($column.htmlType == "select" || $column.htmlType == "radio" || $column.htmlType == "checkbox")
                        <Form.Item label="${comment}" name="${javaField}">
                          <Select
                              v-model:value="queryParams.${javaField}"
                              placeholder="请选择${comment}"
                              allowClear
                              class="w-full"
                          >
                              #if ("" != $dictType)## 设置了 dictType 数据字典的情况
                                <Select.Option
                                    v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                                    :key="dict.value"
                                    :value="dict.value"
                                >
                                  {{ dict.label }}
                                </Select.Option>
                              #else## 未设置 dictType 数据字典的情况
                                <Select.Option label="请选择字典生成" value="" />
                              #end
                          </Select>
                        </Form.Item>
                      #elseif($column.htmlType == "datetime")
                          #if ($column.listOperationCondition != "BETWEEN")## 非范围
                            <Form.Item label="${comment}" name="${javaField}">
                              <DatePicker
                                  v-model:value="queryParams.${javaField}"
                                  valueFormat="YYYY-MM-DD"
                                  placeholder="选择${comment}"
                                  allowClear
                                  class="w-full"
                              />
                            </Form.Item>
                          #else## 范围
                            <Form.Item label="${comment}" name="${javaField}">
                              <RangePicker
                                  v-model:value="queryParams.${javaField}"
                                  v-bind="getRangePickerDefaultProps()"
                                  class="w-full"
                              />
                            </Form.Item>
                          #end
                      #end
                  #end
              #end
            <Form.Item>
              <Button class="ml-2" @click="resetQuery"> 重置 </Button>
              <Button class="ml-2" @click="handleQuery" type="primary">
                搜索
              </Button>
            </Form.Item>
          </Form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap title="${table.classComment}">
          <template #extra>
            <TableToolbar
                ref="tableToolbarRef"
                v-model:hidden-search="hiddenSearchBar"
            >
              <Button
                  class="ml-2"
                  :icon="h(Plus)"
                  type="primary"
                  @click="onCreate"
                  v-access:code="['${permissionPrefix}:create']"
              >
                {{ $t('ui.actionTitle.create', ['${table.classComment}']) }}
              </Button>
            </TableToolbar>
          </template>
          <vxe-table
              ref="tableRef"
              :data="list"
              show-overflow
              :loading="loading"
          >
              #foreach($column in $subColumns)
                  #if ($column.listOperationResult)
                      #set ($dictType=$column.dictType)
                      #set ($javaField = $column.javaField)
                      #set ($comment=$column.columnComment)
                      #if ($column.javaType == "LocalDateTime")## 时间类型
                        <vxe-column field="${javaField}" title="${comment}" align="center">
                          <template #default="{row}">
                            {{formatDateTime(row.${javaField})}}
                          </template>
                        </vxe-column>
                      #elseif($column.dictType && "" != $column.dictType)## 数据字典
                        <vxe-column field="${javaField}" title="${comment}" align="center">
                          <template #default="{row}">
                            <dict-tag :type="DICT_TYPE.$dictType.toUpperCase()" :value="row.${javaField}" />
                          </template>
                        </vxe-column>
                      #elseif ($table.templateType == 2 && $javaField == $treeNameColumn.javaField)
                        <vxe-column field="${javaField}" title="${comment}" align="center"  tree-node/>
                      #else
                        <vxe-column field="${javaField}" title="${comment}" align="center" />
                      #end
                  #end
              #end
            <vxe-column field="operation" title="操作" align="center">
              <template #default="{row}">
                <Button
                    size="small"
                    type="link"
                    @click="onEdit(row as any)"
                    v-access:code="['${permissionPrefix}:update']"
                >
                  {{ $t('ui.actionTitle.edit') }}
                </Button>
                <Button
                    size="small"
                    type="link"
                    danger
                    class="ml-2"
                    @click="onDelete(row as any)"
                    v-access:code="['${permissionPrefix}:delete']"
                >
                  {{ $t('ui.actionTitle.delete') }}
                </Button>
              </template>
            </vxe-column>
          </vxe-table>
          <!-- 分页 -->
          <div class="mt-2 flex justify-end">
            <Pagination
                :total="total"
                v-model:current="queryParams.pageNo"
                v-model:page-size="queryParams.pageSize"
                show-size-changer
                @change="getList"
            />
          </div>
        </ContentWrap>
      </div>
    #else
    <ContentWrap title="${subTable.classComment}列表">
      <vxe-table
          :data="list"
          show-overflow
          :loading="loading"
      >
          #foreach($column in $subColumns)
              #if ($column.listOperationResult)
                  #set ($dictType=$column.dictType)
                  #set ($javaField = $column.javaField)
                  #set ($comment=$column.columnComment)
                  #if ($column.javaType == "LocalDateTime")## 时间类型
                    <vxe-column field="${javaField}" title="${comment}" align="center">
                      <template #default="{row}">
                        {{formatDateTime(row.${javaField})}}
                      </template>
                    </vxe-column>
                  #elseif($column.dictType && "" != $column.dictType)## 数据字典
                    <vxe-column field="${javaField}" title="${comment}" align="center">
                      <template #default="{row}">
                        <dict-tag :type="DICT_TYPE.$dictType.toUpperCase()" :value="row.${javaField}" />
                      </template>
                    </vxe-column>
                  #else
                    <vxe-column field="${javaField}" title="${comment}" align="center" />
                  #end
              #end
          #end
      </vxe-table>
    </ContentWrap>
    #end
</template>
