<template>
  <div class="app-container">
    <!-- 使用 TableList 组件 -->
    <TableList
      ref="tableListRef"
      :config="tableListConfig"
      @update:data="list = $event"
      @update:loading="loading = $event"
      @columnChange="handleColumnChange"
      #if ( $table.templateType != 2 )
      #if ($deleteBatchEnable)
      @update:selectedRows="handleSelectionChange"
      #end
      #end
    />
    <!-- 对话框(添加 / 修改) -->
    <${simpleClassName}Form ref="formRef" @success="getList" />
  ## 特殊：主子表专属逻辑
  #if ( $table.templateType == 11 && $subTables && $subTables.size() > 0 )
    <!-- 子表的列表 -->
      <el-tabs v-model="subTabsName">
          #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))
            <el-tab-pane label="${subTable.classComment}" name="$subClassNameVar">
              <${subSimpleClassName}List v-if="currentRow.id" :${subJoinColumn_strikeCase}="currentRow.id" />
            </el-tab-pane>
          #end
      </el-tabs>
  #end
  </div>
</template>

<script>
import * as ${simpleClassName}Api from '@/api/${table.moduleName}/${table.businessName}';
import ${simpleClassName}Form from './${simpleClassName}Form.vue';
import TableList from '@/components/TableList/index.vue';
import type { TableListConfig } from '@/components/TableList/types';
#if ($hasImageUploadColumn)
import ImageUpload from '@/components/ImageUpload';
#end
#if ($hasFileUploadColumn)
import FileUpload from '@/components/FileUpload';
#end
#if ($hasEditorColumn)
import Editor from '@/components/Editor';
#end
## 特殊：主子表专属逻辑
#if ( $table.templateType != 10 )
#if ( $subTables && $subTables.size() > 0 )
    #foreach ($subSimpleClassName in $subSimpleClassNames)
    import ${subSimpleClassName}List from './components/${subSimpleClassName}List.vue';
    #end
#end
#end
export default {
  name: "${simpleClassName}",
  components: {
          ${simpleClassName}Form,
          TableList,
## 特殊：主子表专属逻辑
#if ( $table.templateType != 10 )
#if ( $subTables && $subTables.size() > 0 )
      #foreach ($subSimpleClassName in $subSimpleClassNames)
          ${subSimpleClassName}List,
      #end
#end
#end
#if ($hasImageUploadColumn)
    ImageUpload,
#end
#if ($hasFileUploadColumn)
    FileUpload,
#end
#if ($hasEditorColumn)
    Editor,
#end
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      ## 特殊：树表专属逻辑（树不需要分页接口）
      #if ( $table.templateType != 2 )
        // 总条数
        total: 0,
      #end
      // ${table.classComment}列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        ## 特殊：树表专属逻辑（树不需要分页接口）
        #if ( $table.templateType != 2 )
            pageNo: 1,
            pageSize: 10,
        #end
        #foreach ($column in $columns)
        #if ($column.listOperation)
        #if ($column.listOperationCondition != 'BETWEEN')
        $column.javaField: null,
        #end
        #if ($column.htmlType == "datetime" && $column.listOperationCondition == "BETWEEN")
        $column.javaField: [],
        #end
        #end
        #end
      },
        ## 特殊：主子表专属逻辑-erp
        #if ( $table.templateType == 11)
            #if ( $subTables && $subTables.size() > 0 )
              /** 子表的列表 */
              subTabsName: '$subClassNameVars.get(0)'
            #end
        #end
    };
  },
  computed: {
    // TableList 组件配置
    tableListConfig() {
      return {
        // 搜索表单配置
        searchForm: {
          items: [
            #foreach($column in $columns)
            #if ($column.listOperation)
            #set ($dictType=$column.dictType)
            #set ($javaField=$column.javaField)
            #set ($comment=$column.columnComment)
            #if ($column.htmlType == "input")
            {
              field: '${javaField}',
              label: '${comment}',
              type: 'input' as const,
              placeholder: '请输入${comment}'
            },
            #elseif ($column.htmlType == "select" || $column.htmlType == "radio")
            {
              field: '${javaField}',
              label: '${comment}',
              type: 'select' as const,
              placeholder: '请选择${comment}',
              #if ("" != $dictType)
              options: this.getDictDatas(DICT_TYPE.$dictType.toUpperCase()).map(dict => ({
                label: dict.label,
                value: dict.value
              }))
              #else
              options: [{ label: '请选择字典生成', value: '' }]
              #end
            },
            #elseif ($column.htmlType == "datetime")
            #if ($column.listOperationCondition != "BETWEEN")
            {
              field: '${javaField}',
              label: '${comment}',
              type: 'date-range' as const
            },
            #else
            {
              field: '${javaField}',
              label: '${comment}',
              type: 'date-range' as const
            },
            #end
            #end
            #end
            #end
          ],
          maxItemsPerRow: 3,
          collapsed: true
        },

        // 表格顶部操作按钮配置
        actions: [
          {
            label: '新增',
            type: 'primary' as const,
            icon: 'ep:plus',
            permission: '${permissionPrefix}:create',
            handler: () => this.openForm(undefined)
          },
          #if ( $table.templateType == 2 )
          {
            label: '展开/折叠',
            type: 'danger' as const,
            plain: true,
            icon: 'ep:sort',
            handler: () => this.toggleExpandAll()
          },
          #end
          #if ( $table.templateType != 2 && $deleteBatchEnable )
          ,{
            label: '批量删除',
            type: 'danger' as const,
            plain: true,
            icon: 'ep:delete',
            disabled: !this.checkedIds || this.checkedIds.length === 0,
            permission: '${permissionPrefix}:delete',
            handler: () => this.handleDeleteBatch()
          }
          #end
        ],

        // 表格配置
        table: {
          selection: #if ( $table.templateType != 2 && $deleteBatchEnable ) true #else false #end,
          index: true,
          columns: [
            #foreach($column in $columns)
            #if ($column.listOperationResult)
            #set ($dictType=$column.dictType)
            #set ($javaField=$column.javaField)
            #set ($comment=$column.columnComment)
            #if ($column.javaType == "LocalDateTime")
            {
              prop: '${javaField}',
              label: '${comment}',
              width: 180,
              align: 'center' as const,
              formatter: (row) => this.parseTime(row.${javaField})
            },
            #elseif ("" != $column.dictType)
            {
              prop: '${javaField}',
              label: '${comment}',
              align: 'center' as const,
              dictType: DICT_TYPE.$dictType.toUpperCase()
            },
            #else
            {
              prop: '${javaField}',
              label: '${comment}',
              align: 'center' as const
            },
            #end
            #end
            #end
          ],
          actions: [
            {
              label: '修改',
              type: 'primary' as const,
              link: true,
              icon: 'ep:edit',
              permission: '${permissionPrefix}:update',
              handler: (row) => this.openForm(row.${primaryColumn.javaField})
            },
            {
              label: '删除',
              type: 'danger' as const,
              link: true,
              icon: 'ep:delete',
              permission: '${permissionPrefix}:delete',
              handler: (row) => this.handleDelete(row)
            }
          ]
        },

        // 分页配置
        #if ( $table.templateType != 2 )
        pagination: {
          show: true,
          pageSize: 10,
          layout: 'total, sizes, prev, pager, next, jumper'
        },
        #else
        pagination: {
          show: false
        },
        #end

        // 设置区域配置
        settings: {
          refresh: true,
          download: this.handleExport,
          #if ($table.templateType != 2)
          print: true,
          size: true,
          columns: true,
          fullscreen: true
          #else
          print: false,
          size: false,
          columns: false,
          fullscreen: false
          #end
        },

        // API配置
        api: {
          getList: async (params) => {
            try {
              this.loading = true;
              #if ( $table.templateType == 2 )
              const res = await ${simpleClassName}Api.get${simpleClassName}List(params);
              const list = this.handleTree(res.data, 'id', '${treeParentColumn.javaField}');
              #else
              const res = await ${simpleClassName}Api.get${simpleClassName}Page(params);
              const { list, total } = res.data;
              this.total = total;
              #end
              return {
                list,
                #if ( $table.templateType != 2 )
                total
                #else
                total: list.length
                #end
              };
            } finally {
              this.loading = false;
            }
          }
        },

        // 查询参数
        queryParams: this.queryParams,

        // 自定义事件处理
        onSearch: (params) => {
          this.queryParams = { ...params };
          this.queryParams.pageNo = 1;
        },

        onReset: () => {
          this.resetQuery();
        },

        #if ( $table.templateType != 2 && $deleteBatchEnable )
        onSelectionChange: (selection) => {
          this.checkedIds = selection.map(item => item.${primaryColumn.javaField});
        },
        #end

        // 列变化回调
        columnChange: (columns) => {
          console.log('列配置变化:', columns);
        }
      } as TableListConfig;
    }
  },
  created() {
    // 组件初始化后会自动调用 getList
  },
  methods: {
    /** 添加/修改操作 */
    openForm(id) {
      this.#[[$]]#refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const ${primaryColumn.javaField} = row.${primaryColumn.javaField};
      await this.#[[$modal]]#.confirm('是否确认删除${table.classComment}编号为"' + ${primaryColumn.javaField} + '"的数据项?')
      try {
       await ${simpleClassName}Api.delete${simpleClassName}(${primaryColumn.javaField});
       await this.#[[$]]#refs["tableListRef"].getList();
       this.#[[$modal]]#.msgSuccess("删除成功");
      } catch {}
    },
    #if ($table.templateType != 2 && $deleteBatchEnable)
    /** 批量删除${table.classComment} */
    async handleDeleteBatch() {
      await this.#[[$modal]]#.confirm('是否确认删除?')
      try {
        await ${simpleClassName}Api.delete${simpleClassName}List(this.checkedIds);
        await this.#[[$]]#refs["tableListRef"].getList();
        this.#[[$modal]]#.msgSuccess("删除成功");
      } catch {}
    },
    #end
    /** 导出按钮操作 */
    async handleExport() {
      await this.#[[$modal]]#.confirm('是否确认导出所有${table.classComment}数据项?');
      try {
        this.exportLoading = true;
        const data = await ${simpleClassName}Api.export${simpleClassName}Excel(this.queryParams);
        this.#[[$]]#download.excel(data, '${table.classComment}.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置查询参数
      Object.keys(this.queryParams).forEach((key) => {
        if (key !== 'pageNo' && key !== 'pageSize') {
          this.queryParams[key] = null;
        }
      });
      this.queryParams.pageNo = 1;
      this.queryParams.pageSize = 10;
    },
      ## 特殊：主子表专属逻辑
      #if ( $table.templateType == 11 )
        /** 选中行操作 */
        handleCurrentChange(row) {
         this.currentRow = row;
        #if ( $subTables && $subTables.size() > 0 )
          /** 子表的列表 */
          this.subTabsName = '$subClassNameVars.get(0)';
        #end
        },
      #end
      ## 特殊：树表专属逻辑
      #if ( $table.templateType == 2 )
        /** 展开/折叠操作 */
        toggleExpandAll() {
          this.refreshTable = false
          this.isExpandAll = !this.isExpandAll
          this.$nextTick(function () {
            this.refreshTable = true
          })
        }
      #end
      /** 选择变化处理 */
      handleSelectionChange(selection) {
        this.checkedIds = selection.map(item => item.${primaryColumn.javaField});
      }
  }
};
</script>
