#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 { DictTag } from '#/components/dict-tag';
  import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';
  import { VxeColumn, VxeTable } from '#/adapter/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 { ElMessage, ElLoading, ElButton, ElTabs, ElTabPane, ElPagination, ElForm, ElFormItem, ElDatePicker, ElSelect, ElOption, ElInput } from 'element-plus';
    import { Plus, Trash2 } from '@vben/icons';
    import { $t } from '#/locales';
    import { TableToolbar } from '#/components/table-toolbar';
    import { useTableToolbar } from '#/hooks';
#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}){
    ElMessage.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 loadingInstance = ElLoading.service({
    text: $t('ui.actionMessage.deleting', [row.id]),
    background: 'rgba(0, 0, 0, 0.7)',
  });
  try {
    await delete${subSimpleClassName}(row.id as number);
    ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.id]));
    await getList();
  } finally {
    loadingInstance.close();
  }
}

#if ($deleteBatchEnable)
/** 批量删除${subTable.classComment} */
async function handleDeleteBatch() {
  const loadingInstance = ElLoading.service({
    text: $t('ui.actionMessage.deleting'),
    background: 'rgba(0, 0, 0, 0.7)',
  });
  try {
    await delete${subSimpleClassName}List(checkedIds.value);
    checkedIds.value = [];
    ElMessage.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    loadingInstance.close();
  }
}

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
  })

/** 搜索按钮操作 */
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, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
#end
</script>

<template>
    #if ($table.templateType == 11) ## erp
      <FormModal @success="getList" />
      <div class="h-[600px]">
        <ContentWrap v-if="!hiddenSearchBar">
          <!-- 搜索工作栏 -->
          <el-form
              :model="queryParams"
              ref="queryFormRef"
              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")
                        <el-form-item label="${comment}">
                          <el-input
                              v-model="queryParams.${javaField}"
                              placeholder="请输入${comment}"
                              clearable
                              @keyup.enter="handleQuery"
                              class="!w-[240px]"
                          />
                        </el-form-item>
                      #elseif ($column.htmlType == "select" || $column.htmlType == "radio" || $column.htmlType == "checkbox")
                        <el-form-item label="${comment}">
                          <el-select
                              v-model="queryParams.${javaField}"
                              placeholder="请选择${comment}"
                              clearable
                              class="!w-[240px]"
                          >
                              #if ("" != $dictType)## 设置了 dictType 数据字典的情况
                                <el-option
                                    v-for="dict in getDictOptions(DICT_TYPE.$dictType.toUpperCase(), '$dictMethod')"
                                    :key="dict.value"
                                    :value="dict.value"
                                    :label="dict.label"
                                />
                              #else## 未设置 dictType 数据字典的情况
                                <el-option label="请选择字典生成" value="" />
                              #end
                          </el-select>
                        </el-form-item>
                      #elseif($column.htmlType == "datetime")
                          #if ($column.listOperationCondition != "BETWEEN")## 非范围
                            <el-form-item label="${comment}">
                              <el-date-picker
                                  v-model="queryParams.${javaField}"
                                  value-format="YYYY-MM-DD"
                                  placeholder="选择${comment}"
                                  clearable
                                  class="!w-[240px]"
                              />
                            </el-form-item>
                          #else## 范围
                            <el-form-item label="${comment}">
                              <el-date-picker
                                  v-model="queryParams.${javaField}"
                                  type="daterange"
                                  value-format="YYYY-MM-DD"
                                  range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期"
                                  class="!w-[240px]"
                              />
                            </el-form-item>
                          #end
                      #end
                  #end
              #end
            <el-form-item>
              <el-button class="ml-2" @click="resetQuery"> 重置 </el-button>
              <el-button class="ml-2" @click="handleQuery" type="primary">
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap title="${table.classComment}">
          <template #extra>
            <TableToolbar
                ref="tableToolbarRef"
                v-model:hidden-search="hiddenSearchBar"
            >
              <el-button
                  class="ml-2"
                  :icon="h(Plus)"
                  type="primary"
                  @click="handleCreate"
                  v-access:code="['${permissionPrefix}:create']"
              >
                {{ $t('ui.actionTitle.create', ['${table.classComment}']) }}
              </el-button>
                #if ($deleteBatchEnable)
                  <el-button
                      :icon="h(Trash2)"
                      type="danger"
                      class="ml-2"
                      :disabled="isEmpty(checkedIds)"
                      @click="handleDeleteBatch"
                      v-access:code="['${table.moduleName}:${simpleClassName_strikeCase}:delete']"
                  >
                    批量删除
                  </el-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}">
                <el-button
                    size="small"
                    type="primary"
                    link
                    @click="handleEdit(row as any)"
                    v-access:code="['${permissionPrefix}:update']"
                >
                  {{ $t('ui.actionTitle.edit') }}
                </el-button>
                <el-button
                    size="small"
                    type="danger"
                    link
                    class="ml-2"
                    @click="handleDelete(row as any)"
                    v-access:code="['${permissionPrefix}:delete']"
                >
                  {{ $t('ui.actionTitle.delete') }}
                </el-button>
              </template>
            </vxe-column>
          </vxe-table>
          <!-- 分页 -->
          <div class="mt-2 flex justify-end">
            <el-pagination
                :total="total"
                v-model:current-page="queryParams.pageNo"
                v-model:page-size="queryParams.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="getList"
                @current-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>
