#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 '#/adapter/vxe-table';

import { reactive,ref, h, nextTick,watch,onMounted } from 'vue';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';

import { DictTag } from '#/components/dict-tag';
import { getRangePickerDefaultProps } from '#/utils';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import { ContentWrap } from '#/components/content-wrap';

#if ($table.templateType == 11) ## erp
import { useVbenModal } from '@vben/common-ui';
import { useTableToolbar, VbenVxeTableToolbar } from '@vben/plugins/vxe-table';
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 { Plus, Trash2 } from '@vben/icons';
import { $t } from '#/locales';
#end

#if ($table.templateType == 11) ## erp
import { delete${subSimpleClassName},#if ($deleteBatchEnable) delete${subSimpleClassName}List,#end get${subSimpleClassName}Page } from '#/api/${table.moduleName}/${simpleClassName_strikeCase}';
import { isEmpty } from '@vben/utils';
#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 handleCreate() {
  if (!props.${subJoinColumn.javaField}){
    message.warning("请先选择一个${table.classComment}!")
    return
  }
  formModalApi.setData({${subJoinColumn.javaField}: props.${subJoinColumn.javaField}}).open();
}

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

/** 删除${subTable.classComment} */
async function handleDelete(row: ${simpleClassName}Api.${subSimpleClassName}) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await delete${subSimpleClassName}(row.id!);
    message.success($t('ui.actionMessage.deleteSuccess', [row.id]));
    await getList();
  } finally {
    hideLoading();
  }
}

#if ($deleteBatchEnable)
/** 批量删除${subTable.classComment} */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
  });
  try {
    await delete${subSimpleClassName}List(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([])
function handleRowCheckboxChange({
  records,
}: {
  records: ${simpleClassName}Api.${subSimpleClassName}[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}
#end
#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
})

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

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value.resetFields()
  handleQuery()
}
#end
  /** 查询列表 */
async function getList() {
  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, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
#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>
            <VbenVxeTableToolbar
                ref="tableToolbarRef"
                v-model:hidden-search="hiddenSearchBar"
            >
              <Button
                  class="ml-2"
                  :icon="h(Plus)"
                  type="primary"
                  @click="handleCreate"
                  v-access:code="['${permissionPrefix}:create']"
              >
                {{ $t('ui.actionTitle.create', ['${table.classComment}']) }}
              </Button>
                #if ($deleteBatchEnable)
                  <Button
                      :icon="h(Trash2)"
                      type="primary"
                      danger
                      class="ml-2"
                      :disabled="isEmpty(checkedIds)"
                      @click="handleDeleteBatch"
                      v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:delete']"
                  >
                    批量删除
                  </Button>
                #end
            </TableToolbar>
          </template>
          <vxe-table
              ref="tableRef"
              :data="list"
              show-overflow
              :loading="loading"
              #if ($deleteBatchEnable)
              @checkboxAll="handleRowCheckboxChange"
              @checkboxChange="handleRowCheckboxChange"
              #end
          >
              #if ($deleteBatchEnable)
                <vxe-column type="checkbox" width="40"></vxe-column>
              #end
              #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="handleEdit(row as any)"
                    v-access:code="['${permissionPrefix}:update']"
                >
                  {{ $t('ui.actionTitle.edit') }}
                </Button>
                <Button
                    size="small"
                    type="link"
                    danger
                    class="ml-2"
                    @click="handleDelete(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>
