<template>
  <ContentWrap v-loading="pageInitLoading" :class="{ 'noCard': props.isPopup }">
    <div class="table-list" :class="{ 'full-height': !props.isPopup }" ref="tableListRef">
      <div :style="props.isPopup ? 'padding: 0 10px 10px 10px' : 'padding: 10px'">
        <!-- 搜索工作栏 -->
        <template
          v-if="searchFormConfig && searchFormConfig.items && searchFormConfig.items.length > 0"
        >
          <el-form ref="queryFormRef" :model="queryParams" class="-mb-10px" label-width="100px" label-position="right">
            <el-row>
              <el-col :span="18">
                <!-- 使用 el-row 和 el-col 实现响应式布局 -->
                <el-row :gutter="16">
                  <el-col
                    v-for="(item, index) in displayItems"
                    :key="index"
                    :span="item.span || 24 / maxItemsPerRow"
                    class="search-form-item"
                  >
                    <el-form-item
                      :label="item.label"
                      :label-width="item.labelWidth || '100px'"
                      label-position="right"
                      :prop="item.field"
                      :show-message="false"
                      :rules="
                        item.required
                          ? [
                              {
                                required: true,
                                message: item.requiredMessage || `${item.label}不能为空`,
                                trigger: 'change'
                              }
                            ]
                          : []
                      "
                      class="w-full"
                      :title="item.label"
                    >
                      <!-- 输入框 -->
                      <el-input
                        v-if="item.type === 'input'"
                        v-model="queryParams[item.field]"
                        :placeholder="item.placeholder"
                        :style="`width: ${item.width || '100%'}`"
                        clearable
                        @keyup.enter="handleSearch"
                      />
                      <!-- 选择器 -->
                      <el-select
                        v-else-if="item.type === 'select'"
                        v-model="queryParams[item.field]"
                        :placeholder="item.placeholder"
                        clearable
                        :style="`width: ${item.width || '100%'}`"
                        @change="handleSearch"
                      >
                        <el-option
                          v-for="option in item.options"
                          :key="option.value"
                          :label="option.label"
                          :value="option.value"
                        />
                      </el-select>
                      <!-- 日期范围 -->
                      <el-date-picker
                        v-else-if="item.type === 'date-range'"
                        v-model="queryParams[item.field]"
                        :style="`width: ${item.width || '100%'}`"
                        end-placeholder="结束日期"
                        start-placeholder="开始日期"
                        type="daterange"
                        :value-format="item.valueFormat || 'YYYY-MM-DD'"
                        :default-time="item.defaultTime || null"
                        :shortcuts="item.shortcuts"
                      />
                      <!-- 单个日期 -->
                      <el-date-picker
                        v-else-if="item.type === 'date'"
                        v-model="queryParams[item.field]"
                        :style="`width: ${item.width || '100%'}`"
                        :placeholder="item.placeholder || '选择日期'"
                        type="date"
                        :value-format="item.valueFormat || 'YYYY-MM-DD'"
                        :shortcuts="item.shortcuts"
                      />
                      <!-- 月份选择 -->
                      <el-date-picker
                        v-else-if="item.type === 'month'"
                        v-model="queryParams[item.field]"
                        :style="`width: ${item.width || '100%'}`"
                        :placeholder="item.placeholder || '选择月份'"
                        type="month"
                        :value-format="item.valueFormat || 'YYYY-MM'"
                      />
                      <!-- 年份选择 -->
                      <el-date-picker
                        v-else-if="item.type === 'year'"
                        v-model="queryParams[item.field]"
                        :style="`width: ${item.width || '100%'}`"
                        :placeholder="item.placeholder || '选择年份'"
                        type="year"
                        :value-format="item.valueFormat || 'YYYY'"
                      />
                      <!-- 自定义组件 -->
                      <component
                        v-else-if="item.type === 'custom' && item.component"
                        :is="item.component"
                        v-model="queryParams[item.field]"
                        v-bind="item.props"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="6">
                <!-- 搜索按钮 -->
                <el-row class="search-buttons-row" style="margin: 0">
                  <el-col :span="24">
                    <el-form-item class="search-buttons" :label-width="'20px'">
                      <el-button @click="handleSearch" type="primary"> 搜索 </el-button>
                      <el-button @click="handleReset"> 重置 </el-button>
                      <!-- 展开/收起按钮 -->
                      <el-button v-if="needToggleCollapse" type="text" @click="toggleCollapse">
                        <Icon
                          :icon="isCollapsed ? 'ep:arrow-down' : 'ep:arrow-up'"
                          class="mr-5px"
                        />
                        {{ isCollapsed ? '展开' : '收起' }}
                      </el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </template>

        <!-- 操作按钮区域 -->
        <div
          class="actions-box"
          v-if="hasAnySettings || (config.actions && config.actions.length > 0)"
        >
          <div class="table-actions" v-if="leftActions && leftActions.length > 0">
            <el-button
              v-for="action in leftActions"
              :key="action.label"
              :type="action.type || 'primary'"
              :plain="action.plain || false"
              :loading="
                action.loading && typeof action.loading === 'object'
                  ? action.loading.value
                  : action.loading
              "
              :disabled="
                typeof action.disabled === 'function'
                  ? action.disabled()
                  : action.disabled && typeof action.disabled === 'object'
                    ? action.disabled.value
                    : action.disabled
              "
              @click="action.handler?.()"
            >
              <Icon v-if="action.icon" :icon="action.icon" class="mr-5px" />
              {{ action.label }}
            </el-button>
          </div>
          <!--额外显示耳朵插槽内容-->
          <div class="table-actions">
            <slot name="actions-right"></slot>
          </div>
          <!--设置按钮区域-->
          <div v-if="hasAnySettings || (config.actions && config.actions.length > 0)" class="setting-btns">
            <!-- 右侧操作按钮 -->
            <el-button
              v-for="action in rightActions"
              :key="action.label + '_right'"
              :type="action.type || 'primary'"
              :plain="action.plain || false"
              :loading="
                action.loading && typeof action.loading === 'object'
                  ? action.loading.value
                  : action.loading
              "
              :disabled="
                typeof action.disabled === 'function'
                  ? action.disabled()
                  : action.disabled && typeof action.disabled === 'object'
                    ? action.disabled.value
                    : action.disabled
              "
              @click="action.handler?.()"
              class="ml-10px"
            >
              <Icon v-if="action.icon" :icon="action.icon" class="mr-5px" />
              {{ action.label }}
            </el-button>
            <!-- 刷新按钮 -->
            <Icon
              v-if="config.settings?.refresh !== false"
              :size="18"
              color="#000"
              icon="ep:refresh-right"
              class="ml-10px cursor-pointer hover:text-primary"
              @click="handleRefresh"
              :title="'刷新表格'"
            />
            <!-- 下载按钮 -->
            <Icon
              v-if="config.settings?.download !== false"
              :size="18"
              color="#000"
              icon="ep:download"
              class="ml-10px cursor-pointer hover:text-primary"
              @click="handleDownload"
              :title="'数据下载'"
            />
            <!-- 打印按钮 -->
            <Icon
              v-if="config.settings?.print"
              :size="18"
              color="#000"
              icon="ep:printer"
              class="ml-10px cursor-pointer hover:text-primary"
              @click="handlePrint"
              :title="'数据打印'"
            />
            <!-- 大小设置按钮 -->
            <el-dropdown v-if="config.settings?.size" placement="bottom-start">
              <Icon
                :size="18"
                color="#000"
                icon="fa:table"
                class="ml-10px cursor-pointer hover:text-primary"
                :title="'表格大小设置'"
              />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="size in ['large', 'default', 'small']"
                    :key="size"
                    @click="handleSizeChange(size)"
                    >{{
                      size === 'large' ? '宽松型' : size === 'default' ? '默认' : '紧凑型'
                    }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <el-popover
              v-if="config.settings?.size"
              placement="bottom"
              :width="120"
              trigger="click"
            >
              <template #reference>
                <Icon
                  :size="18"
                  icon="fa:table"
                  class="ml-10px cursor-pointer hover:text-primary"
                />
              </template>
              <div class="size-options">
                <div
                  v-for="size in ['large', 'default', 'small']"
                  :key="size"
                  class="size-option"
                  :class="{ active: tableSize === size }"
                  @click="handleSizeChange(size)"
                >
                  {{ size === 'large' ? '宽松型' : size === 'default' ? '默认' : '紧凑型' }}
                </div>
              </div>
            </el-popover> -->
            <!-- 列设置按钮 -->
            <Icon
              v-if="config.settings?.columns"
              :size="18"
              color="#000"
              icon="ep:setting"
              class="ml-10px cursor-pointer hover:text-primary"
              @click="handleColumnSettings"
              :title="'表格列设置'"
            />
            <!-- 全屏按钮 -->
            <Icon
              v-if="config.settings?.fullscreen"
              :size="18"
              color="#000"
              :icon="isFullscreen ? 'ep:close' : 'ep:full-screen'"
              class="ml-10px cursor-pointer hover:text-primary"
              @click="toggleFullscreen"
              :title="isFullscreen ? '退出全屏' : '全屏'"
            />
            <!-- 重置并刷新按钮 -->
            <el-button v-if="config.settings?.resetRefresh" class="ml-10px" @click="handleResetRefresh">
              重置并刷新
            </el-button>
          </div>
        </div>
        <!-- 列表 -->
        <el-table
          v-loading="loading"
          :data="list"
          :size="tableSize"
          :height="props.tableHeight ? props.tableHeight : !props.isPopup ? tHeight : 'auto'"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @row-dblclick="handleRowDblClick"
          @expand-change="handleExpandChange"
          :row-class-name="getRowClassName"
          :row-key="config.table.rowKey || 'id'"
          :tree-props="
            config.table.treeProps || { children: 'children', hasChildren: 'hasChildren' }
          "
          :default-expand-all="config.table.defaultExpandAll"
          :expand-row-keys="internalExpandRowKeys"
          border
        >
          <!-- 选择列 -->
          <el-table-column
            v-if="config.table.selection === true"
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />

          <!-- 序号列 -->
          <el-table-column
            v-if="config.table.index"
            label="序号"
            width="70"
            align="center"
            fixed="left"
          >
            <template #default="scope">
              {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <!-- 数据列 -->
          <template v-for="column in filteredColumns" :key="column.prop || column.label">
            <el-table-column
              v-if="column.children"
              :label="column.label"
              :align="column.align || 'center'"
              :fixed="column.fixed"
            >
              <el-table-column
                v-for="childColumn in column.children"
                :key="childColumn.prop"
                :prop="childColumn.prop"
                :width="childColumn.width"
                :min-width="childColumn.minWidth"
                :align="childColumn.align || 'center'"
                :fixed="childColumn.fixed"
                :show-overflow-tooltip="childColumn.showOverflowTooltip"
                :formatter="childColumn.formatter"
                :sortable="false"
              >
                <template #header>
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                      width: 100%;
                      gap: 4px;
                    "
                  >
                    <span style="flex: 1; text-align: center">{{ childColumn.label }}</span>
                    <div style="display: flex; align-items: center; gap: 4px; flex-shrink: 0">
                      <el-popover
                        v-if="childColumn.filterable"
                        :ref="(el: any) => setFilterPopoverRef(childColumn.prop, el)"
                        :width="childColumn.filterType === 'number' ? 340 : 280"
                        placement="bottom"
                        trigger="click"
                        :popper-class="`column-filter-popover column-filter-${childColumn.prop}`"
                        @click.stop
                      >
                        <template #reference>
                          <el-icon class="cursor-pointer hover:text-primary">
                            <Filter />
                          </el-icon>
                        </template>
                        <!-- 字典类型筛选 -->
                        <div v-if="childColumn.filterType === 'dict' || childColumn.dictType">
                          <el-select
                            :model-value="tempColumnFilters[childColumn.prop]?.value"
                            @update:model-value="
                              (val) => handleTempFilterChange(childColumn.prop, 'value', val, 'dict')
                            "
                            placeholder="选择筛选值"
                            :size="tableSize"
                            clearable
                            style="width: 100%; margin-bottom: 12px"
                            popper-class="filter-select-popper"
                            :teleported="false"
                            @click.stop
                          >
                            <el-option
                              v-for="option in getDictOptions(childColumn.dictType)"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                              @click.stop
                            />
                          </el-select>
                        </div>
                        <!-- 数字范围筛选 -->
                        <div v-else-if="childColumn.filterType === 'number'">
                          <el-row :gutter="8" @click.stop>
                            <el-col :span="8">
                              <el-select
                                :model-value="tempColumnFilters[childColumn.prop]?.range?.operator"
                                @update:model-value="
                                  (val) =>
                                    handleTempFilterChange(childColumn.prop, 'operator', val, 'number')
                                "
                                placeholder="选择范围"
                                :size="tableSize"
                                popper-class="filter-select-popper"
                                :teleported="false"
                                style="width: 100%; margin-bottom: 12px"
                                @click.stop
                              >
                                <el-option label="大于" value="gt" @click.stop />
                                <el-option label="小于" value="lt" @click.stop />
                                <el-option label="介于" value="between" @click.stop />
                              </el-select>
                            </el-col>
                            <el-col :span="8">
                              <el-input-number
                                :model-value="tempColumnFilters[childColumn.prop]?.range?.min"
                                @update:model-value="
                                  (val) => handleTempFilterChange(childColumn.prop, 'min', val, 'number')
                                "
                                placeholder="值"
                                :controls="false"
                                :size="tableSize"
                                :disabled="!tempColumnFilters[childColumn.prop]?.range?.operator"
                                style="width: 100%; margin-bottom: 12px"
                                @click.stop
                              />
                            </el-col>
                            <el-col :span="8">
                              <el-input-number
                                v-if="tempColumnFilters[childColumn.prop]?.range?.operator === 'between'"
                                :model-value="tempColumnFilters[childColumn.prop]?.range?.max"
                                @update:model-value="
                                  (val) => handleTempFilterChange(childColumn.prop, 'max', val, 'number')
                                "
                                placeholder="值"
                                :controls="false"
                                :size="tableSize"
                                style="width: 100%; margin-bottom: 12px"
                                @click.stop
                              />
                            </el-col>
                          </el-row>
                        </div>
                        <!-- 文本筛选（默认） -->
                        <div v-else>
                          <el-input
                            :model-value="tempColumnFilters[childColumn.prop]?.value"
                            @update:model-value="
                              (val) => handleTempFilterChange(childColumn.prop, 'value', val, 'text')
                            "
                            placeholder="输入筛选条件"
                            :size="tableSize"
                            clearable
                            style="margin-bottom: 12px"
                            @click.stop
                          />
                        </div>
                        <!-- 操作按钮 -->
                        <div style="display: flex; justify-content: flex-end">
                          <el-button size="small" @click="handleColumnFilterReset(childColumn.prop)">
                            重置
                          </el-button>
                          <el-button
                            type="primary"
                            size="small"
                            @click="handleColumnFilterConfirm(childColumn.prop)"
                          >
                            确定
                          </el-button>
                        </div>
                      </el-popover>
                      <el-icon
                        v-if="childColumn.sortable"
                        class="cursor-pointer hover:text-primary"
                        :class="{ 'text-primary': columnSort[childColumn.prop] }"
                        @click="handleColumnSort(childColumn.prop)"
                      >
                        <component :is="getSortIcon(childColumn.prop)" />
                      </el-icon>
                    </div>
                  </div>
                </template>
                <template #default="scope" v-if="childColumn.render || childColumn.dictType">
                  <!-- 自定义渲染 -->
                  <template v-if="childColumn.render">
                    <component
                      :is="{
                        render: () => childColumn.render(h, { row: scope.row, column: childColumn, $index: scope.$index })
                      }"
                    />
                  </template>
                  <!-- 字典标签 -->
                  <dict-tag
                    v-else-if="childColumn.dictType"
                    :type="childColumn.dictType"
                    :value="scope.row[childColumn.prop]"
                  />
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column
              v-else
              :prop="column.prop"
              :width="column.width"
              :min-width="column.minWidth"
              :align="column.align || 'center'"
              :fixed="column.fixed"
              :show-overflow-tooltip="column.showOverflowTooltip"
              :formatter="column.formatter"
              :sortable="false"
            >
              <template #header>
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    width: 100%;
                    gap: 4px;
                  "
                >
                  <span style="flex: 1; text-align: center">{{ column.label }}</span>
                  <div style="display: flex; align-items: center; gap: 4px; flex-shrink: 0">
                    <el-popover
                      v-if="column.filterable"
                      :ref="(el: any) => setFilterPopoverRef(column.prop, el)"
                      :width="column.filterType === 'number' ? 340 : 280"
                      placement="bottom"
                      trigger="click"
                      :popper-class="`column-filter-popover column-filter-${column.prop}`"
                      @click.stop
                    >
                      <template #reference>
                        <el-icon class="cursor-pointer hover:text-primary">
                          <Filter />
                        </el-icon>
                      </template>
                      <!-- 字典类型筛选 -->
                      <div v-if="column.filterType === 'dict' || column.dictType">
                        <el-select
                          :model-value="tempColumnFilters[column.prop]?.value"
                          @update:model-value="
                            (val) => handleTempFilterChange(column.prop, 'value', val, 'dict')
                          "
                          placeholder="选择筛选值"
                          :size="tableSize"
                          clearable
                          style="width: 100%; margin-bottom: 12px"
                          popper-class="filter-select-popper"
                          :teleported="false"
                          @click.stop
                        >
                          <el-option
                            v-for="option in getDictOptions(column.dictType)"
                            :key="option.value"
                            :label="option.label"
                            :value="option.value"
                            @click.stop
                          />
                        </el-select>
                      </div>
                      <!-- 数字范围筛选 -->
                      <div v-else-if="column.filterType === 'number'">
                        <el-row :gutter="8" @click.stop>
                          <el-col :span="8">
                            <el-select
                              :model-value="tempColumnFilters[column.prop]?.range?.operator"
                              @update:model-value="
                                (val) =>
                                  handleTempFilterChange(column.prop, 'operator', val, 'number')
                              "
                              placeholder="选择范围"
                              :size="tableSize"
                              popper-class="filter-select-popper"
                              :teleported="false"
                              style="width: 100%; margin-bottom: 12px"
                              @click.stop
                            >
                              <el-option label="大于" value="gt" @click.stop />
                              <el-option label="小于" value="lt" @click.stop />
                              <el-option label="介于" value="between" @click.stop />
                            </el-select>
                          </el-col>
                          <el-col :span="8">
                            <el-input-number
                              :model-value="tempColumnFilters[column.prop]?.range?.min"
                              @update:model-value="
                                (val) => handleTempFilterChange(column.prop, 'min', val, 'number')
                              "
                              placeholder="值"
                              :controls="false"
                              :size="tableSize"
                              :disabled="!tempColumnFilters[column.prop]?.range?.operator"
                              style="width: 100%; margin-bottom: 12px"
                              @click.stop
                            />
                          </el-col>
                          <el-col :span="8">
                            <el-input-number
                              v-if="tempColumnFilters[column.prop]?.range?.operator === 'between'"
                              :model-value="tempColumnFilters[column.prop]?.range?.max"
                              @update:model-value="
                                (val) => handleTempFilterChange(column.prop, 'max', val, 'number')
                              "
                              placeholder="值"
                              :controls="false"
                              :size="tableSize"
                              style="width: 100%; margin-bottom: 12px"
                              @click.stop
                            />
                          </el-col>
                        </el-row>
                      </div>
                      <!-- 文本筛选（默认） -->
                      <div v-else>
                        <el-input
                          :model-value="tempColumnFilters[column.prop]?.value"
                          @update:model-value="
                            (val) => handleTempFilterChange(column.prop, 'value', val, 'text')
                          "
                          placeholder="输入筛选条件"
                          :size="tableSize"
                          clearable
                          style="margin-bottom: 12px"
                          @click.stop
                        />
                      </div>
                      <!-- 操作按钮 -->
                      <div style="display: flex; justify-content: flex-end">
                        <el-button size="small" @click="handleColumnFilterReset(column.prop)">
                          重置
                        </el-button>
                        <el-button
                          type="primary"
                          size="small"
                          @click="handleColumnFilterConfirm(column.prop)"
                        >
                          确定
                        </el-button>
                      </div>
                    </el-popover>
                    <el-icon
                      v-if="column.sortable"
                      class="cursor-pointer hover:text-primary"
                      :class="{ 'text-primary': columnSort[column.prop] }"
                      @click="handleColumnSort(column.prop)"
                    >
                      <component :is="getSortIcon(column.prop)" />
                    </el-icon>
                  </div>
                </div>
              </template>
              <template #default="scope" v-if="column.render || column.dictType">
                <!-- 自定义渲染 -->
                <template v-if="column.render">
                  <component
                    :is="{
                      render: () => column.render(h, { row: scope.row, column, $index: scope.$index })
                    }"
                  />
                </template>
                <!-- 字典标签 -->
                <dict-tag
                  v-else-if="column.dictType"
                  :type="column.dictType"
                  :value="scope.row[column.prop]"
                />
              </template>
            </el-table-column>
          </template>

          <!-- 操作列 -->
          <el-table-column
            v-if="config.table.actions && config.table.actions.length > 0"
            label="操作"
            fixed="right"
            :width="config.table.actionsWidth || 160"
            align="center"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center; justify-content: left">
                <!-- 显示前2个按钮，如果超过3个则显示更多下拉菜单 -->
                <template v-for="action in displayedActions(scope.row)" :key="action.label">
                  <el-button
                    :type="action.type || 'primary'"
                    :link="action.link !== false"
                    :icon="action.icon"
                    @click="action.handler?.(scope.row)"
                  >
                    {{ action.label }}
                  </el-button>
                </template>

                <!-- 更多操作下拉菜单 -->
                <el-dropdown v-if="hasMoreActions(scope.row)" trigger="click">
                  <el-button type="primary" :link="true" style="margin-left: 12px">
                    更多 <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-for="action in moreActions(scope.row)"
                        :key="action.label"
                        @click="action.handler?.(scope.row)"
                      >
                        <el-icon v-if="action.icon" class="mr-1">
                          <component :is="action.icon" />
                        </el-icon>
                        {{ action.label }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination
          v-if="config.pagination?.show !== false"
          :page="queryParams.pageNo"
          :page-sizes="config.pagination?.pageSizes || [10, 20, 50, 100]"
          :limit="queryParams.pageSize"
          :total="total"
          :layout="config.pagination?.layout || 'total, sizes, prev, pager, next, jumper'"
          @pagination="handlePaginationChange"
        />
      </div>
    </div>
  </ContentWrap>
  <!-- 列设置弹窗 -->
  <el-dialog v-model="columnSettingsVisible" title="列设置" width="500px" append-to-body>
    <div class="column-settings-content">
      <template
        v-if="
          columnsForSettings.filter((item) => {
            return item.fixed == 'left'
          }).length > 0
        "
      >
        <div class="settings-tip">
          <span>固定左侧</span>
          <el-checkbox
            :model-value="isAllLeftColumnsSelected"
            :indeterminate="isLeftColumnsIndeterminate"
            @change="handleLeftColumnsSelectAll"
            size="small"
          >
            全选
          </el-checkbox>
        </div>
        <div class="column-list" @dragover.prevent @drop="handleDrop($event, 'left')">
          <div
            v-for="column in columnsForSettings.filter((item) => {
              return item.fixed == 'left'
            })"
            :key="column.prop"
            class="column-item"
            :class="{ 'column-hidden': !column.show }"
            :data-original-index="columnsForSettings.findIndex((c) => c.prop === column.prop)"
            :data-list-type="'left'"
            draggable="true"
            @dragstart="handleDragStart($event, column, 'left')"
            @dragover.prevent="handleDragOver"
            @dragend="handleDragEnd"
          >
            <Icon icon="ep:rank" class="drag-handle" :size="14" />
            <el-checkbox
              v-model="column.show"
              :disabled="column.required"
              @change="
                handleColumnVisibilityChange(
                  columnsForSettings.findIndex((c) => c.prop === column.prop)
                )
              "
            />
            <span class="column-label">{{ column.label }}</span>
            <el-dropdown placement="bottom-start">
              <Icon icon="ep:more-filled" class="drag-handle" :size="14" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="fixedColumn(column, 'left')">固定左侧</el-dropdown-item>
                  <el-dropdown-item @click="fixedColumn(column, 'right')"
                    >固定右侧</el-dropdown-item
                  >
                  <el-dropdown-item @click="fixedColumn(column, null)">不固定</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      <template
        v-if="
          columnsForSettings.filter((item) => {
            return !item.fixed
          }).length > 0
        "
      >
        <div class="settings-tip">
          <span>不固定</span>
          <el-checkbox
            :model-value="isAllCenterColumnsSelected"
            :indeterminate="isCenterColumnsIndeterminate"
            @change="handleCenterColumnsSelectAll"
            size="small"
          >
            全选
          </el-checkbox>
        </div>
        <div
          class="column-list"
          ref="columnListRef"
          @dragover.prevent
          @drop="handleDrop($event, 'center')"
        >
          <div
            v-for="column in columnsForSettings.filter((item) => {
              return !item.fixed
            })"
            :key="column.prop"
            class="column-item"
            :class="{ 'column-hidden': !column.show }"
            :data-original-index="columnsForSettings.findIndex((c) => c.prop === column.prop)"
            :data-list-type="'center'"
            draggable="true"
            @dragstart="handleDragStart($event, column, 'center')"
            @dragover.prevent="handleDragOver"
            @dragend="handleDragEnd"
          >
            <Icon icon="ep:rank" class="drag-handle" :size="14" />
            <el-checkbox
              v-model="column.show"
              :disabled="column.required"
              @change="
                handleColumnVisibilityChange(
                  columnsForSettings.findIndex((c) => c.prop === column.prop)
                )
              "
            />
            <span class="column-label">{{ column.label }}</span>
            <el-dropdown placement="bottom-start">
              <Icon icon="ep:more-filled" class="drag-handle" :size="14" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="fixedColumn(column, 'left')">固定左侧</el-dropdown-item>
                  <el-dropdown-item @click="fixedColumn(column, 'right')"
                    >固定右侧</el-dropdown-item
                  >
                  <el-dropdown-item @click="fixedColumn(column, null)">不固定</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      <template
        v-if="
          columnsForSettings.filter((item) => {
            return item.fixed == 'right'
          }).length > 0
        "
      >
        <div class="settings-tip">
          <span>固定右侧</span>
          <el-checkbox
            :model-value="isAllRightColumnsSelected"
            :indeterminate="isRightColumnsIndeterminate"
            @change="handleRightColumnsSelectAll"
            size="small"
          >
            全选
          </el-checkbox>
        </div>
        <div class="column-list" @dragover.prevent @drop="handleDrop($event, 'right')">
          <div
            v-for="column in columnsForSettings.filter((item) => {
              return item.fixed == 'right'
            })"
            :key="column.prop"
            class="column-item"
            :class="{ 'column-hidden': !column.show }"
            :data-original-index="columnsForSettings.findIndex((c) => c.prop === column.prop)"
            :data-list-type="'right'"
            draggable="true"
            @dragstart="handleDragStart($event, column, 'right')"
            @dragover.prevent="handleDragOver"
            @dragend="handleDragEnd"
          >
            <Icon icon="ep:rank" class="drag-handle" :size="14" />
            <el-checkbox
              v-model="column.show"
              :disabled="column.required"
              @change="
                handleColumnVisibilityChange(
                  columnsForSettings.findIndex((c) => c.prop === column.prop)
                )
              "
            />
            <span class="column-label">{{ column.label }}</span>
            <el-dropdown placement="bottom-start">
              <Icon icon="ep:more-filled" class="drag-handle" :size="14" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="fixedColumn(column, 'left')">固定左侧</el-dropdown-item>
                  <el-dropdown-item @click="fixedColumn(column, 'right')"
                    >固定右侧</el-dropdown-item
                  >
                  <el-dropdown-item @click="fixedColumn(column, null)">不固定</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="columnSettingsVisible = false">取消</el-button>
        <el-button type="primary" @click="handleColumnSettingsConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 下载列选择弹窗 -->
  <el-dialog v-model="downloadColumnsVisible" title="选择下载列" width="500px" append-to-body>
    <div class="download-columns-content">
      <div class="download-columns-header">
        <el-checkbox
          :model-value="isAllDownloadColumnsSelected"
          :indeterminate="isDownloadColumnsIndeterminate"
          @change="handleDownloadColumnsSelectAll"
        >
          全选
        </el-checkbox>
      </div>
      <div class="download-columns-list">
        <div
          v-for="column in columnsForDownload"
          :key="column.prop"
          class="column-item"
          :class="{ 'column-hidden': !column.selected && !column.required }"
        >
          <el-checkbox v-model="column.selected" :disabled="column.required" />
          <span class="column-label">{{ column.label }}</span>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="downloadColumnsVisible = false">取消</el-button>
      <el-button type="primary" @click="executeDownload">确定下载</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, h, nextTick } from 'vue'
// import type { FormInstance } from 'element-plus'
import type { TableListConfig } from './types'
import { checkPermi } from '@/utils/permission'
import { useFullscreen } from '@vueuse/core'
import { ArrowDown, Filter, Sort, SortDown, SortUp } from '@element-plus/icons-vue'
import { TableApi } from '@/api/system/grid/table'
import { FieldApi } from '@/api/system/grid/field'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import request from '@/config/axios'
import { useUserStore } from '@/store/modules/user'
import dayjs from 'dayjs'
import { resolveFormatter } from '@/utils/formatTime'
import { useTableHeightCalculator } from '@/utils/tableHeightUtils'
const userStore = useUserStore()
interface Props {
  isPopup?: boolean // 是否在弹窗中使用，为 true 时移除 full-height 样式类
  config: TableListConfig,
  noPadding?: boolean,
  tableHeight?: string,
  autoLoad?: boolean // 是否在初始化时自动加载数据，默认为 true
}
const pageInitLoading = ref(true)
const props = defineProps<Props>()
const tHeight = ref(600) // 初始化默认高度
// 使用表格高度计算器
const { calculate } = useTableHeightCalculator()
// 计算表格高度
const calculateTableContainerHeight = () => {
  tHeight.value = calculate() // 根据实际需要调整底部预留空间
}
// 默认 autoLoad 为 true
const autoLoad = computed(() => {
  return props.autoLoad !== undefined ? props.autoLoad : true
})
// 定义 emit
const emit = defineEmits<{
  'update:data': [data: any[]]
  'update:loading': [loading: boolean]
  columnChange: [columns: any[]]
  selectionChange: [selection: any[]]
  rowDblClick: [row: any]
}>()

const getStorageKey = () => {
  const gridCode = props.config.gridCode
  if (gridCode) {
    return `tableList_queryParams_${gridCode}`
  }
  const fullPath = window.location.fullPath || window.location.pathname + window.location.search
  return `tableList_queryParams_${fullPath}`
}

const saveQueryParamsToStorage = (params: any) => {
  try {
    const storageKey = getStorageKey()
    const paramsToSave = { ...params }
    delete paramsToSave.pageNo
    delete paramsToSave.pageSize
    localStorage.setItem(storageKey, JSON.stringify(paramsToSave))
  } catch (error) {
    console.error('保存查询参数失败:', error)
  }
}

const loadQueryParamsFromStorage = () => {
  try {
    const storageKey = getStorageKey()
    const stored = localStorage.getItem(storageKey)
    if (stored) {
      return JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载查询参数失败:', error)
  }
  return null
}

const clearQueryParamsFromStorage = () => {
  try {
    const storageKey = getStorageKey()
    localStorage.removeItem(storageKey)
  } catch (error) {
    console.error('清除查询参数失败:', error)
  }
}

const getExpandStateStorageKey = () => {
  const gridCode = props.config.gridCode
  if (gridCode) {
    return `tableList_expandState_${gridCode}`
  }
  const fullPath = window.location.fullPath || window.location.pathname + window.location.search
  return `tableList_expandState_${fullPath}`
}

const saveExpandStateToStorage = (isCollapsed: boolean) => {
  try {
    const storageKey = getExpandStateStorageKey()
    localStorage.setItem(storageKey, JSON.stringify({ isCollapsed }))
  } catch (error) {
    console.error('保存展开状态失败:', error)
  }
}

const loadExpandStateFromStorage = () => {
  try {
    const storageKey = getExpandStateStorageKey()
    const stored = localStorage.getItem(storageKey)
    if (stored) {
      const parsed = JSON.parse(stored)
      return parsed.isCollapsed
    }
  } catch (error) {
    console.error('加载展开状态失败:', error)
  }
  return undefined
}

const clearExpandStateFromStorage = () => {
  try {
    const storageKey = getExpandStateStorageKey()
    localStorage.removeItem(storageKey)
  } catch (error) {
    console.error('清除展开状态失败:', error)
  }
}

// 表单引用
// const queryFormRef = ref<FormInstance>()
// 高级筛选显示状态
const showAdvancedPopover = ref(false)
// 数据总数
const total = ref(0)
// 选中的数据
const selectedRows = ref<any[]>([])
// 加载状态
const loading = ref(false)
// 列表数据
const list = ref<any[]>([])
// 原始数据（用于列筛选）
const originalList = ref<any[]>([])
// 展开的行键（用于树形表格）
const internalExpandRowKeys = ref<any[]>([])
// 列筛选状态
interface FilterValue {
  type: 'text' | 'number' | 'dict'
  value?: string | string[]
  range?: {
    operator: 'gt' | 'lt' | 'between'
    min?: number
    max?: number
  }
}
const columnFilters = ref<Record<string, FilterValue>>({})
// 临时筛选状态（用于 popover 中暂存筛选条件）
const tempColumnFilters = ref<Record<string, FilterValue>>({})
// 筛选 popover 引用
const filterPopoverRefs = ref<Record<string, any>>({})
// 设置 popover 引用
const setFilterPopoverRef = (columnProp: string, el: any) => {
  if (el) {
    filterPopoverRefs.value[columnProp] = el
  }
}
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: props.config.pagination?.pageSize || 10,
  ...props.config.queryParams
})

// 展开/收起相关状态
const isCollapsed = ref(true)
const maxItemsPerRow = computed(() => searchFormConfig.value?.maxItemsPerRow || 3)

// 初始化展开/收起状态
const initCollapseState = () => {
  const storedState = loadExpandStateFromStorage()
  if (storedState !== undefined) {
    isCollapsed.value = storedState
  }
}

// 需要显示的items（受展开/收起影响）
const displayItems = computed(() => {
  const items = searchFormConfig.value?.items || []

  // 如果是动态字段配置
  if (props.config.gridCode) {
    // 计算所有字段的fieldWidth总和
    const totalWidth = items.reduce((sum, item) => {
      return sum + (item.span || 6) // 使用span值，默认为6
    }, 0)

    // 折叠状态下只显示一行的字段（总和<=24）
    if (isCollapsed.value) {
      return items.filter((item, index) => {
        const currentWidth = items.slice(0, index + 1).reduce((sum, currentItem) => {
          return sum + (currentItem.span || 6)
        }, 0)
        return currentWidth <= 24
      })
    }
    return items
  }

  // 原有逻辑：基于 maxItemsPerRow 的折叠
  if (isCollapsed.value && items.length > maxItemsPerRow.value) {
    return items.slice(0, maxItemsPerRow.value)
  }
  return items
})

// 是否需要展开/收起按钮
const needToggleCollapse = computed(() => {
  const items = searchFormConfig.value?.items || []

  // 如果是动态字段配置，根据fieldWidth总和判断
  if (props.config.gridCode) {
    // 计算所有字段的fieldWidth总和（使用span值）
    const totalWidth = items.reduce((sum, item) => {
      console.log('动态查询项', item)
      if (item.span == null || item.span == undefined) {
        item.span = 24 / maxItemsPerRow.value // 没有span设置默认值
      }
      return sum + item.span // 使用span值
    }, 0)
    // 总宽度大于24则需要展开/收起按钮
    return totalWidth > 24
  }

  // 原有逻辑：基于 items 数量判断
  return items.length > maxItemsPerRow.value
})

// 切换展开/收起状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
  // 保存展开/收起状态到 localStorage
  saveExpandStateToStorage(isCollapsed.value)
}

// 表格大小状态
const tableSize = ref<'large' | 'default' | 'small'>('default')

// 全屏相关状态
const tableListRef = ref<HTMLElement>()
const { toggle: toggleFullscreen, isFullscreen } = useFullscreen(tableListRef)

// 列设置相关状态
const showColumnSettings = ref(false)
const columnSettingsVisible = ref(false)
const columnsForSettings = ref<any[]>([])
const draggedIndex = ref<number | null>(null)
const draggedItem = ref<any>(null)
const sourceList = ref<string>('')

// 下载相关状态
const downloadColumnsVisible = ref(false)
const columnsForDownload = ref<any[]>([])

// 下载列选择相关计算属性
const isAllDownloadColumnsSelected = computed(() => {
  if (columnsForDownload.value.length === 0) return false
  return columnsForDownload.value.every((col) => col.selected || col.required)
})

const isDownloadColumnsIndeterminate = computed(() => {
  if (columnsForDownload.value.length === 0) return false
  const selectedCount = columnsForDownload.value.filter(
    (col) => col.selected || col.required
  ).length
  return selectedCount > 0 && selectedCount < columnsForDownload.value.length
})

// 列设置全选相关计算属性
const isAllLeftColumnsSelected = computed(() => {
  const leftColumns = columnsForSettings.value.filter((col) => col.fixed === 'left')
  return leftColumns.length > 0 && leftColumns.every((col) => col.show || col.required)
})

const isLeftColumnsIndeterminate = computed(() => {
  const leftColumns = columnsForSettings.value.filter((col) => col.fixed === 'left')
  const selectedCount = leftColumns.filter((col) => col.show || col.required).length
  return selectedCount > 0 && selectedCount < leftColumns.length
})

const isAllCenterColumnsSelected = computed(() => {
  const centerColumns = columnsForSettings.value.filter((col) => !col.fixed)
  return centerColumns.length > 0 && centerColumns.every((col) => col.show || col.required)
})

const isCenterColumnsIndeterminate = computed(() => {
  const centerColumns = columnsForSettings.value.filter((col) => !col.fixed)
  const selectedCount = centerColumns.filter((col) => col.show || col.required).length
  return selectedCount > 0 && selectedCount < centerColumns.length
})

const isAllRightColumnsSelected = computed(() => {
  const rightColumns = columnsForSettings.value.filter((col) => col.fixed === 'right')
  return rightColumns.length > 0 && rightColumns.every((col) => col.show || col.required)
})

const isRightColumnsIndeterminate = computed(() => {
  const rightColumns = columnsForSettings.value.filter((col) => col.fixed === 'right')
  const selectedCount = rightColumns.filter((col) => col.show || col.required).length
  return selectedCount > 0 && selectedCount < rightColumns.length
})

// 内部维护的列配置（支持动态更新）
const internalColumns = ref<any[]>([])
// 过滤后的列配置（用于渲染表格）
const filteredColumns = computed(() => {
  return internalColumns.value.filter((column) => !column.hidden)
})

// 内部维护的搜索表单配置（支持动态更新）
const internalSearchForm = ref<any>(null)
// 实际使用的搜索表单配置
const searchFormConfig = computed(() => {
  return internalSearchForm.value || props.config.searchForm
})

// 检查是否有任何设置按钮
const hasAnySettings = computed(() => {
  const settings = props.config.settings
  if (!settings) return false
  return (
    settings.refresh !== false ||
    settings.download !== false ||
    settings.print ||
    settings.size ||
    settings.columns ||
    settings.fullscreen ||
    settings.resetRefresh
  )
})

// 刷新列表
const handleRefresh = () => {
  // 重新加载当前页数据
  getList()
}
// 获取排序图标
const getSortIcon = (columnProp: string) => {
  const sortState = columnSort.value[columnProp]
  if (!sortState) return Sort
  return sortState === 'ascending' ? SortUp : SortDown
}

// 处理列排序
const handleColumnSort = (columnProp: string) => {
  const currentSort = columnSort.value[columnProp]

  // 切换排序状态：无 -> 升序 -> 降序 -> 无
  if (!currentSort) {
    columnSort.value[columnProp] = 'ascending'
  } else if (currentSort === 'ascending') {
    columnSort.value[columnProp] = 'descending'
  } else {
    columnSort.value[columnProp] = null
  }

  // 对列表数据进行排序
  applyColumnSort()
}
// 应用列筛选
const applyColumnFilters = (dataList: any[]) => {
  if (!dataList || dataList.length === 0) {
    return dataList
  }

  // 获取所有设置了筛选的列
  const filterKeys = Object.keys(columnFilters.value).filter(
    (key) =>
      columnFilters.value[key] &&
      (columnFilters.value[key].value && columnFilters.value[key].value !== '')
  )

  if (filterKeys.length === 0) {
    return dataList
  }

  // 对每条数据应用所有筛选条件
  return dataList.filter((row) => {
    return filterKeys.every((key) => {
      const filterConfig = columnFilters.value[key]
      if (!filterConfig) return true

      const cellValue = row[key]

      // 文本类型筛选（默认）
      if (!filterConfig.value || filterConfig.value === '') return true
      if (cellValue === null || cellValue === undefined) return false

      // 模糊匹配（不区分大小写）
      return String(cellValue).toLowerCase().includes(String(filterConfig.value).toLowerCase())
    })
  })
}
// 处理临时筛选变化
const handleTempFilterChange = (
  columnProp: string,
  field: string,
  value: any,
  filterType?: 'text'
) => {
  if (!tempColumnFilters.value[columnProp]) {
    // 默认使用 text 类型
    tempColumnFilters.value[columnProp] = { type: 'text' }
  }

  if (field === 'value') {
    tempColumnFilters.value[columnProp].value = value
  }
}

// 确认筛选
const handleColumnFilterConfirm = (columnProp: string) => {
  const tempFilter = tempColumnFilters.value[columnProp]
  if (!tempFilter) {
    // 如果没有临时筛选，清除该列的筛选
    delete columnFilters.value[columnProp]
  } else {
    // 应用临时筛选
    columnFilters.value[columnProp] = { ...tempFilter }
  }

  // 关闭 popover
  closeFilterPopover(columnProp)

  // 重新应用筛选，必须从原始数据开始
  if (originalList.value && originalList.value.length > 0) {
    list.value = applyColumnFilters(originalList.value)
  } else {
    // 如果没有原始数据，直接使用当前列表数据
    list.value = applyColumnFilters(list.value)
  }
  // 序号会自动重新排列，因为表格是基于list.value渲染的
}

// 重置筛选
const handleColumnFilterReset = (columnProp: string) => {
  // 清除临时筛选
  delete tempColumnFilters.value[columnProp]
  // 清除已应用的筛选
  delete columnFilters.value[columnProp]
  // 重置回最初的数据，然后应用其他列的筛选条件
  if (originalList.value && originalList.value.length > 0) {
    list.value = applyColumnFilters(originalList.value)
  } else {
    // 如果没有原始数据，直接使用当前列表数据
    list.value = applyColumnFilters(list.value)
  }
  // 关闭 popover
  // closeFilterPopover(columnProp)
}

// 关闭筛选 popover
const closeFilterPopover = (columnProp: string) => {
  const popover = filterPopoverRefs.value[columnProp]
  if (popover && popover.hide) {
    popover.hide()
  }
}

// 处理列筛选输入
const handleColumnFilterInput = (columnProp: string, value: any) => {
  if (!columnFilters.value[columnProp]) {
    columnFilters.value[columnProp] = { type: 'text' }
  }
  columnFilters.value[columnProp].value = value
  // 重新应用筛选（使用原始数据）
  if (originalList.value && originalList.value.length > 0) {
    list.value = applyColumnFilters(originalList.value)
  }
}
// 下载表格数据
const handleDownload = async () => {
  // 检查下载配置
  const downloadConfig = props.config.settings?.download

  // 如果下载配置是对象且showColumnSelector为false，则直接下载
  if (typeof downloadConfig === 'object' && downloadConfig.showColumnSelector === false) {
    await executeDownload()
    return
  }

  // 默认行为或showColumnSelector为true时，显示列选择弹窗
  initDownloadColumns()
  downloadColumnsVisible.value = true
}

// 执行下载
const executeDownload = async () => {
  try {
    const downloadConfig = props.config.settings?.download

    // 如果外部提供了下载方法（函数形式），则调用外部方法
    if (typeof downloadConfig === 'function') {
      const selectedColumns = columnsForDownload.value.filter((col) => col.selected)
      const filteredList = list.value.map((row) => {
        const filteredRow: any = {}
        selectedColumns.forEach((col) => {
          if (col.prop) {
            filteredRow[col.prop] = row[col.prop]
          }
        })
        return filteredRow
      })
      downloadConfig(filteredList)
      downloadColumnsVisible.value = false
      return
    }

    // 如果外部提供了下载方法（对象形式），则调用对象的handler方法
    if (
      typeof downloadConfig === 'object' &&
      downloadConfig.handler &&
      typeof downloadConfig.handler === 'function'
    ) {
      // 检查是否需要传递筛选后的数据
      if (downloadConfig.passFilteredData === true) {
        const selectedColumns = columnsForDownload.value.filter((col) => col.selected)
        const filteredList = list.value.map((row) => {
          const filteredRow: any = {}
          selectedColumns.forEach((col) => {
            if (col.prop) {
              filteredRow[col.prop] = row[col.prop]
            }
          })
          return filteredRow
        })
        downloadConfig.handler(filteredList)
      } else {
        // 不传递筛选数据，直接调用handler
        downloadConfig.handler()
      }
      downloadColumnsVisible.value = false
      return
    }

    // 否则使用内置的纯前端下载方法
    // 如果没有选择列，则下载所有显示的列
    if (columnsForDownload.value.length === 0) {
      initDownloadColumns()
    }
    await downloadTableData()
    downloadColumnsVisible.value = false
  } catch (error) {
    console.error('下载失败:', error)
    // 这里可以添加错误提示
  }
}

// 初始化下载列数据
const initDownloadColumns = () => {
  const currentColumns =
    internalColumns.value.length > 0 ? internalColumns.value : props.config.table.columns
  columnsForDownload.value = currentColumns
    .filter((col) => col.prop) // 过滤掉没有prop的列（如操作列）
    .map((col) => ({
      ...col,
      selected: !col.hidden && col.show !== false, // 默认选中显示的列
      required: col.required || false // 标记为必需的列
    }))
}

// 下载列全选/取消全选
const handleDownloadColumnsSelectAll = (checked: boolean) => {
  columnsForDownload.value.forEach((col) => {
    if (!col.required) {
      col.selected = checked
    }
  })
}

// 列设置全选相关方法
const handleLeftColumnsSelectAll = (checked: boolean) => {
  columnsForSettings.value.forEach((col) => {
    if (col.fixed === 'left' && !col.required) {
      col.show = checked
    }
  })
}

const handleCenterColumnsSelectAll = (checked: boolean) => {
  columnsForSettings.value.forEach((col) => {
    if (!col.fixed && !col.required) {
      col.show = checked
    }
  })
}

const handleRightColumnsSelectAll = (checked: boolean) => {
  columnsForSettings.value.forEach((col) => {
    if (col.fixed === 'right' && !col.required) {
      col.show = checked
    }
  })
}

// 内置的纯前端下载方法
const downloadTableData = async () => {
  if (!list.value || list.value.length === 0) {
    console.warn('暂无数据可下载')
    return
  }

  // 准备下载数据
  const headers = props.config.table.columns
    .filter((col) => col.prop) // 过滤掉没有prop的列（如操作列）
    .map((col) => ({
      header: col.label,
      key: col.prop,
      width: col.width || 120
    }))

  // 转换数据格式
  const data = list.value.map((row) => {
    const dataRow: any = {}
    headers.forEach((header) => {
      // 处理formatter或字典类型
      const column = props.config.table.columns.find((col) => col.prop === header.key)
      if (column) {
        if (column.formatter) {
          dataRow[header.key] = column.formatter(row, column, row[header.key])
        } else if (column.dictType) {
          // 这里可以调用字典转换，暂时返回原值
          dataRow[header.key] = row[header.key]
        } else {
          dataRow[header.key] = row[header.key]
        }
      }
    })
    return dataRow
  })

  // 生成CSV格式内容
  const csvContent = generateCSV(headers, data)

  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)

  link.setAttribute('href', url)
  link.setAttribute('download', `table_data_${new Date().getTime()}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  console.log('表格数据下载成功')
}

// 生成CSV内容
const generateCSV = (headers: any[], data: any[]) => {
  const csvHeaders = headers.map((h) => h.header).join(',')
  const csvRows = data.map((row) =>
    headers
      .map((h) => {
        const value = row[h.key] || ''
        // 处理包含逗号、换行符、引号的情况
        if (
          typeof value === 'string' &&
          (value.includes(',') || value.includes('\n') || value.includes('"'))
        ) {
          return `"${value.replace(/"/g, '""')}"`
        }
        return value
      })
      .join(',')
  )

  // 添加BOM以支持中文显示
  return '\ufeff' + csvHeaders + '\n' + csvRows.join('\n')
}

// 打印表格数据
const handlePrint = async () => {
  try {
    if (!list.value || list.value.length === 0) {
      console.warn('暂无数据可打印')
      // 这里可以添加空数据提示
      return
    }

    // 生成打印内容
    const printContent = generatePrintContent()

    // 写入打印内容
    const printHtml = `
      <!DOCTYPE html>
      <html>
        <head>
          <title>表格打印</title>
          <style>
            ${getPrintStyles()}
          </style>
        </head>
        <body>
          ${printContent}
          <script>
            // 打印完成后关闭窗口
            window.onload = function() {
              setTimeout(function() {
                window.print();
                window.onafterprint = function() {
                  window.close();
                };
              }, 500);
            };
          <\/script>
        </body>
      </html>
    `

    // 打开新窗口进行打印
    const printWindow = window.open('', '_blank')
    if (printWindow) {
      printWindow.document.write(printHtml)
      printWindow.document.close()
    } else {
      console.warn('无法打开打印窗口，请检查浏览器弹窗设置')
    }

    console.log('打印功能已调用')
  } catch (error) {
    console.error('打印失败:', error)
    // 降级方案：使用浏览器默认打印
    window.print()
  }
}

// 处理表格尺寸改变
const handleSizeChange = (size: 'large' | 'default' | 'small') => {
  tableSize.value = size
}

// 打开列设置弹窗
const handleColumnSettings = () => {
  // 使用内部列配置或初始列配置
  const currentColumns =
    internalColumns.value.length > 0 ? internalColumns.value : props.config.table.columns
  columnsForSettings.value = currentColumns.map((col: any) => ({
    ...col,
    show: !col.hidden && col.show !== false, // 默认显示，除非被隐藏或明确设置为false
    required: col.required || false // 标记为必需的列，不允许隐藏
  }))
  columnSettingsVisible.value = true
}

// 拖拽开始
const handleDragStart = (event: DragEvent, column: any, listType: string) => {
  const target = event.target as HTMLElement
  const listItem = target.closest('.column-item')
  if (listItem) {
    draggedIndex.value = parseInt(listItem.dataset.originalIndex || '0')
    draggedItem.value = { ...column }
    sourceList.value = listType
    listItem.classList.add('dragging')

    // 设置拖拽数据
    event.dataTransfer?.setData(
      'text/plain',
      JSON.stringify({
        columnIndex: draggedIndex.value,
        listType: listType
      })
    )
  }
}

// 拖拽经过
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

// 拖拽结束
const handleDragEnd = (event: DragEvent) => {
  const target = event.target as HTMLElement
  const listItem = target.closest('.column-item')
  if (listItem) {
    listItem.classList.remove('dragging')
  }
  draggedIndex.value = null
  draggedItem.value = null
  sourceList.value = ''
}

// 拖拽放置
const handleDrop = (event: DragEvent, targetListType: string) => {
  event.preventDefault()

  if (draggedItem.value && draggedIndex.value !== null) {
    const target = event.target as HTMLElement
    const targetItem = target.closest('.column-item')

    // 获取目标项的原始索引
    let targetIndex = -1
    if (targetItem) {
      targetIndex = parseInt(targetItem.dataset.originalIndex || '-1')
    }

    // 创建新的列数组副本
    const newColumns = [...columnsForSettings.value]

    // 移除拖拽的项
    const [draggedColumn] = newColumns.splice(draggedIndex.value, 1)

    // 如果改变了固定状态，更新fixed属性
    if (sourceList.value !== targetListType) {
      if (targetListType === 'left') {
        draggedColumn.fixed = 'left'
      } else if (targetListType === 'right') {
        draggedColumn.fixed = 'right'
      } else {
        delete draggedColumn.fixed
      }
    }

    // 确定插入位置
    if (targetIndex === -1) {
      // 如果没有目标项，根据列表类型插入到合适位置
      if (targetListType === 'left') {
        // 插入到所有左侧固定列的最后
        const leftFixedCount = newColumns.filter((col) => col.fixed === 'left').length
        newColumns.splice(leftFixedCount, 0, draggedColumn)
      } else if (targetListType === 'right') {
        // 插入到所有右侧固定列的最后
        newColumns.push(draggedColumn)
      } else {
        // 插入到不固定列的最后
        const leftFixedCount = newColumns.filter((col) => col.fixed === 'left').length
        const centerCount = newColumns.filter((col) => !col.fixed).length
        newColumns.splice(leftFixedCount + centerCount, 0, draggedColumn)
      }
    } else {
      // 找到在目标列表中的正确插入位置
      let insertIndex = targetIndex
      if (sourceList.value === targetListType) {
        // 同一列表内，如果目标索引大于拖拽索引，需要调整
        if (targetIndex > draggedIndex.value) {
          insertIndex = targetIndex - 1
        }
      }
      newColumns.splice(insertIndex, 0, draggedColumn)
    }

    // 更新列数组
    columnsForSettings.value = newColumns
  }
}

// 处理列显示状态变化
const handleColumnVisibilityChange = (index: number) => {
  const visibleColumns = columnsForSettings.value.filter((col) => col.show)
  if (visibleColumns.length === 0) {
    // 如果所有列都隐藏了，强制显示当前列
    columnsForSettings.value[index].show = true
    console.warn('至少需要显示一列数据')
  }
}
// 列固定属性设置
const fixedColumn = (column: any, type: 'left' | 'right' | null) => {
  if (type) {
    column.fixed = type
  } else {
    delete column.fixed
  }
}
// 确认列设置
const handleColumnSettingsConfirm = () => {
  // 更新表格列配置
  const newColumns = columnsForSettings.value.map((col) => {
    return {
      ...col,
      // 如果列被隐藏，设置 hidden 属性
      hidden: !col.show
    }
  })

  // 更新内部列配置
  internalColumns.value = [...newColumns]

  columnSettingsVisible.value = false
}

// 生成打印内容
const generatePrintContent = () => {
  const headers = props.config.table.columns
    .filter((col) => col.prop) // 过滤掉没有prop的列（如操作列）
    .map((col) => `<th>${col.label}</th>`)
    .join('')

  const rows = list.value
    .map((row) => {
      const cells = props.config.table.columns
        .filter((col) => col.prop)
        .map((col) => {
          const value = getDisplayValue(row, col)
          return `<td>${value}</td>`
        })
        .join('')
      return `<tr>${cells}</tr>`
    })
    .join('')

  return `
    <div class="print-table-container">
      <h2>表格数据打印</h2>
      <div class="print-info">
        <span>打印时间: ${new Date().toLocaleString()}</span>
        <span>数据条数: ${list.value.length}</span>
      </div>
      <table class="print-table">
        <thead>
          <tr>${headers}</tr>
        </thead>
        <tbody>
          ${rows}
        </tbody>
      </table>
    </div>
  `
}

// 获取显示值（处理formatter）
const getDisplayValue = (row: any, column: any) => {
  if (column.formatter) {
    return column.formatter(row, column, row[column.prop])
  } else if (column.dictType) {
    // 这里可以调用字典转换，暂时返回原值
    return row[column.prop]
  } else {
    return row[column.prop]
  }
}

// 获取打印样式
const getPrintStyles = () => {
  return `
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
      line-height: 1.6;
    }
    
    .print-table-container {
      width: 100%;
    }
    
    h2 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
    }
    
    .print-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      padding: 10px;
      background: #f5f5f5;
      border-radius: 4px;
    }
    
    .print-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
    }
    
    .print-table th,
    .print-table td {
      border: 1px solid #ddd;
      padding: 12px 8px;
      text-align: left;
    }
    
    .print-table th {
      background-color: #f2f2f2;
      font-weight: bold;
      text-align: center;
    }
    
    .print-table tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    
    .print-table tr:hover {
      background-color: #f5f5f5;
    }
    
    @media print {
      body {
        margin: 0;
      }
      
      .print-info {
        background: none;
        border: 1px solid #ddd;
      }
      
      .print-table {
        page-break-inside: avoid;
      }
      
      .print-table th,
      .print-table td {
        border: 1px solid #000;
      }
    }
    
    @page {
      margin: 20mm;
    }
  `
}

// 设置初始默认值
const initializeDefaultValues = () => {
  const currentSearchForm = searchFormConfig.value
  if (currentSearchForm && currentSearchForm.items) {
    currentSearchForm.items.forEach((item: any) => {
      if (item.defaultValue !== undefined && queryParams[item.field] === undefined) {
        queryParams[item.field] = item.defaultValue
      }
    })

    if (currentSearchForm.advancedItems) {
      currentSearchForm.advancedItems.forEach((item: any) => {
        if (item.defaultValue !== undefined && queryParams[item.field] === undefined) {
          queryParams[item.field] = item.defaultValue
        }
      })
    }
  }
}

// 过滤操作按钮
const filteredActions = computed(() => {
  return (row: any) => {
    if (!props.config.table?.actions) return []
    return props.config.table.actions.filter((action: any) => !action.show || action.show(row))
  }
})

// 显示的操作按钮（当actions ≤ showActionsMoreNum时显示全部，> showActionsMoreNum时显示前showActionsMoreNum-1个）
const displayedActions = computed(() => {
  return (row: any) => {
    const actions = filteredActions.value(row)
    const showActionsMoreNum = props.config.table.showActionsMoreNum || 3
    return actions.length > showActionsMoreNum ? actions.slice(0, showActionsMoreNum - 1) : actions
  }
})

// 是否有更多操作按钮（当actions > showActionsMoreNum时显示更多下拉菜单）
const hasMoreActions = computed(() => {
  return (row: any) => {
    const actions = filteredActions.value(row)
    const showActionsMoreNum = props.config.table.showActionsMoreNum || 3
    return actions.length > showActionsMoreNum
  }
})

// 更多操作按钮（从第showActionsMoreNum个开始，仅当actions > showActionsMoreNum时才有）
const moreActions = computed(() => {
  return (row: any) => {
    const actions = filteredActions.value(row)
    const showActionsMoreNum = props.config.table.showActionsMoreNum || 3
    return actions.slice(showActionsMoreNum - 1)
  }
})

// 过滤表格操作按钮
const filteredTableActions = computed(() => {
  if (!props.config.actions) return []
  return props.config.actions.filter((action: any) => !action.show || action.show())
})

// 过滤带权限的表格操作按钮
const filteredActionsWithPermission = computed(() => {
  return filteredTableActions.value.filter(
    (action: any) => !action.permission || checkPermi([action.permission])
  )
})

// 左侧操作按钮
const leftActions = computed(() => {
  return filteredActionsWithPermission.value.filter(
    (action: any) => !action.position || action.position === 'left'
  )
})

// 右侧操作按钮
const rightActions = computed(() => {
  return filteredActionsWithPermission.value.filter(
    (action: any) => action.position && action.position === 'right'
  )
})

// 封装的接口数据获取方法
const fetchSelectOptions = async (apiUrl: string, apiParams?: string, apiMethod?: string) => {
  try {
    let params = {}
    if (apiParams) {
      try {
        const parsedParams = JSON.parse(apiParams)
        // 处理变量模板替换
        params = processApiParams(parsedParams)
        console.log('接口参数:', params)
      } catch (error) {
        console.warn('接口参数解析失败:', error)
      }
    }

    // 根据请求方法调用不同的接口
    let response
    const method = apiMethod?.toLowerCase() || 'get'

    if (method === 'get') {
      response = await request.get({ url: apiUrl, params })
    } else if (method === 'post') {
      response = await request.post({ url: apiUrl, data: params })
    } else {
      // 默认使用GET
      response = await request.get({ url: apiUrl, params })
    }

    return Array.isArray(response) ? response : response?.data || response?.list || []
  } catch (error) {
    console.error('获取接口数据失败:', error)
    return []
  }
}

// 处理接口参数中的变量模板替换
const processApiParams = (parsedParams: any) => {
  const processedParams: any = {}

  const paramsSource = searchFormConfig.value?.params || {}

  Object.keys(parsedParams).forEach((key) => {
    const value = parsedParams[key]

    // 检查是否是变量模板（如 "${deptId}"）
    if (typeof value === 'string' && value.includes('${') && value.includes('}')) {
      // 提取变量名
      const variableMatch = value.match(/\$\{([^}]+)\}/)
      if (variableMatch) {
        const variableName = variableMatch[1]
        // 从 searchFormConfig.params 中获取值，如果找不到则使用空字符串
        processedParams[key] = paramsSource[variableName] || ''
      } else {
        processedParams[key] = value
      }
    } else {
      // 不是变量模板，直接使用原值
      processedParams[key] = value
    }
  })

  return processedParams
}

// 加载字段配置
const loadFieldConfig = async () => {
  console.log('------userStore-------', userStore.getRoles)
  if (props.config.gridCode) {
    pageInitLoading.value = true
    try {
      const res = await TableApi.getEnabledTheme({
        gridCode: props.config.gridCode,
        roleCodeList: userStore.getRoles
      })
      console.log('----动态查询条件----', res)
      if (res && res.showFlag) {
        const conditionData = assembleFieldConditionData(res.fieldDTO)
        const tableFieldData = assembleTableFieldData(res.tableFieldVO)
        console.log('----动态查询条件组装数据----', conditionData)
        console.log('----动态列组装数据----', tableFieldData)
        // 将字段配置转换为搜索表单配置
        if (tableFieldData.length > 0) {
          // 需要将表格列字段换成动态获取的列字段
          internalColumns.value = tableFieldData
        }
        if (conditionData.list && conditionData.list.length > 0) {
          transformFieldConfigToSearchForm(conditionData.list)
        } else {
          getList()
        }
      } else {
        getList()
      }
    } catch (error) {
      console.error('加载字段配置失败:', error)
      getList()
    } finally {
      pageInitLoading.value = false
    }
  } else {
    getList()
  }
}
// 组装动态的表格列字段
const assembleTableFieldData = (res: any) => {
  if (res && res.tableFieldAttrSaveReqVOList && res.tableFieldSaveReqVOList) {
    const arr1 = res.tableFieldSaveReqVOList.filter((item) => {
      return item.showFlag === 0
    })
    const arr2 = res.tableFieldAttrSaveReqVOList
    // 修改数据处理方式，确保正确更新数组中的对象
    return arr1.map((item) => {
      // 在arr2中查找匹配的项
      const matchedItem = arr2.find((item2) => item.fieldKey == item2.fieldKey)

      // 如果找到匹配项，则合并两个对象
      if (matchedItem) {
        item = {
          ...matchedItem,
          ...item
        }
      }

      // 映射关系处理
      item.prop = item.fieldKey
      item.label = item.fieldShowName
      item.dictType = item.dictCode
      // 存在格式化属性，需要格式化日期---开始
      const dateFormats = ['YYYY-MM-DD', 'YYYY-MM-DD HH:mm', 'YYYY-MM-DD HH:mm:ss']
      // 只有当 formatter 是字符串且在支持的格式中时才处理
      if (typeof item.formatter === 'string' && dateFormats.includes(item.formatter)) {
        const format = item.formatter
        item.formatter = (row: any) => {
          const fieldValue = row[item.fieldKey]
          if (!fieldValue) {
            return ''
          }
          return dayjs(fieldValue).format(format)
        }
      }
      // 存在格式化属性，需要格式化日期---结束
      // item.formatter = resolveFormatter(item.formatter)
      // 处理alignment到fixed的映射
      if (item.alignment && item.alignment !== 'none') {
        item.fixed = item.alignment
      } else {
        // 如果alignment为none或不存在，删除fixed属性
        delete item.fixed
      }

      return item
    })
  } else {
    return []
  }
}
// 组装字段条件数据（复用 FieldForm.vue 中的逻辑）
const assembleFieldConditionData = (res: any) => {
  const processFieldTypeData = (list: any[], fieldType: string) => {
    return list.map((item) => ({
      ...item,
      selectJson: JSON.parse(item.selectJson || '[]'),
      fieldType
    }))
  }

  const fieldSaveList = processFieldTypeData(res.fieldSaveList || [], '1')
  const fieldSelectAttrSaveList = processFieldTypeData(res.fieldSelectAttrSaveList || [], '2')
  const fieldDateAttrSaveList = processFieldTypeData(res.fieldDateAttrSaveList || [], '3')

  const list = [...fieldSaveList, ...fieldSelectAttrSaveList, ...fieldDateAttrSaveList]

  // 按 sortOrder 字段排序
  list.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))

  return { list }
}

// 将字段配置转换为搜索表单配置
const transformFieldConfigToSearchForm = async (fieldList: any[]) => {
  // 只显示启用的字段 (showFlag=0)
  const enabledFields = fieldList.filter((field) => field.showFlag === 0)

  const searchItems = await Promise.all(
    enabledFields.map(async (field) => {
      // 基础配置
      const baseItem: any = {
        label: field.fieldShowName,
        field: field.fieldKey,
        // 根据字段类型设置不同的 placeholder
        placeholder: field.promptValue || getDefaultPlaceholder(field.fieldType),
        // 栅格span：有fieldWidth则用fieldWidth作为span，否则使用默认布局
        span: calculateFieldWidth(field.fieldWidth)
      }

      // 根据字段类型设置不同的组件类型
      switch (field.fieldType) {
        case '1': // 文本输入
          return {
            ...baseItem,
            type: 'input',
            // 设置默认值
            defaultValue: field.defaultValue
          }

        case '2': // 下拉选择
          const selectOptions = await getSelectOptions(field)
          return {
            ...baseItem,
            type: 'select',
            options: selectOptions
          }

        case '3': // 日期选择
          const datePickerType = getDatePickerType(field.dateType)
          // 根据字段的dateFormat设置value-format，如果没有则使用默认格式
          const getValueFormat = () => {
            if (field.dateFormat) {
              return field.dateFormat
            }
            switch (datePickerType) {
              case 'date-range':
                return 'YYYY-MM-DD HH:mm:ss'
              case 'date':
                return 'YYYY-MM-DD'
              case 'month':
                return 'YYYY-MM'
              case 'year':
                return 'YYYY'
              default:
                return 'YYYY-MM-DD'
            }
          }

          return {
            ...baseItem,
            type: datePickerType,
            // 日期格式设置 - 优先使用字段的dateFormat
            ...(datePickerType === 'date-range' && {
              valueFormat: getValueFormat(),
              format: field.dateFormat,
              startPlaceholder: '开始日期',
              endPlaceholder: '结束日期',
              shortcuts: getDateShortcuts(field.quickOptions)
            }),
            ...(datePickerType === 'date' && {
              valueFormat: getValueFormat(),
              format: field.dateFormat,
              placeholder: field.promptValue || '请选择日期',
              shortcuts: getSingleDateShortcuts(field.quickOptions)
            }),
            ...(datePickerType === 'month' && {
              valueFormat: getValueFormat(),
              format: field.dateFormat,
              placeholder: field.promptValue || '请选择月份'
            }),
            ...(datePickerType === 'year' && {
              valueFormat: getValueFormat(),
              format: field.dateFormat,
              placeholder: field.promptValue || '请选择年份'
            })
          }

        default:
          return {
            ...baseItem,
            type: 'input',
            defaultValue: field.defaultValue
          }
      }
    })
  )

  // 更新内部搜索表单配置
  internalSearchForm.value = {
    items: searchItems,
    maxItemsPerRow: props.config.searchForm?.maxItemsPerRow || 3,
    collapsed: undefined // 由 computed 计算是否需要折叠
  }

  // 初始化默认值到 queryParams
  searchItems.forEach((item) => {
    if (item.defaultValue !== undefined) {
      queryParams[item.field] = item.defaultValue
    }
  })

  // 从 localStorage 恢复上次的查询条件
  const storedParams = loadQueryParamsFromStorage()
  if (storedParams) {
    Object.assign(queryParams, storedParams)
  }

  // 初始化展开/收起状态
  initCollapseState()

  getList()
  console.log('---searchItems----', searchItems)
  console.log('---搜索字段----', queryParams)
}

// 获取默认占位符
const getDefaultPlaceholder = (fieldType: string) => {
  switch (fieldType) {
    case '1': // 输入框
      return '请输入'
    case '2': // 选择框
      return '请选择'
    case '3': // 日期框
      return '请选择日期'
    default:
      return '请输入'
  }
}

// 计算字段宽度（返回栅格span值，而不是百分比）
const calculateFieldWidth = (fieldWidth?: number) => {
  if (fieldWidth) {
    // 确保fieldWidth在1-24之间，直接作为栅格span值
    return Math.min(Math.max(fieldWidth, 1), 24)
  }
  // 没有fieldWidth则返回undefined，使用默认的maxItemsPerRow布局
  return undefined
}

// 获取下拉选择框的选项数据
const getSelectOptions = async (field: any) => {
  switch (field.selectType) {
    case '1': // 手动输入
      return (
        field.selectJson?.map((option: any) => ({
          label: option.label,
          value: option.value
        })) || []
      )

    case '2': // 接口获取
      if (field.apiUrl) {
        const data = await fetchSelectOptions(field.apiUrl, field.apiParams, field.apiMethod)
        return data.map((item: any) => ({
          label: item[field.labelKey || 'label'],
          value: item[field.valueKey || 'value']
        }))
      }
      return []

    case '3': // 数据字典
      if (field.selectDict) {
        // 转换为驼峰命名调用字典
        const dictKey = field.selectDict
          .toLowerCase()
          .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
        try {
          // 尝试获取字典数据
          const dictData = getStrDictOptions(DICT_TYPE[dictKey] || field.selectDict)
          return dictData.map((item: any) => ({
            label: item.label,
            value: item.value
          }))
        } catch (error) {
          console.warn(`字典 ${field.selectDict} 获取失败:`, error)
          return []
        }
      }
      return []

    default:
      return []
  }
}

// 获取日期选择器类型
const getDatePickerType = (dateType?: string) => {
  switch (dateType) {
    case '1': // 日期范围
      return 'date-range'
    case '2': // 单个日期
      return 'date'
    case '3': // 月份
      return 'month'
    case '4': // 年份
      return 'year'
    default:
      return 'date'
  }
}

// 获取日期快捷选项
const getDateShortcuts = (quickOptions?: string) => {
  if (!quickOptions) return undefined

  const shortcuts = []
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 解析quickOptions，支持多个选项组合（如："1,3,4"）
  const options = quickOptions.split(',').map((opt) => opt.trim())

  options.forEach((option) => {
    switch (option) {
      case '1': // 今天
        shortcuts.push({
          text: '今天',
          value: () => {
            const start = new Date(today)
            const end = new Date(today)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '2': // 昨天
        shortcuts.push({
          text: '昨天',
          value: () => {
            const yesterday = new Date(today)
            yesterday.setDate(yesterday.getDate() - 1)
            const start = new Date(yesterday)
            const end = new Date(yesterday)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '3': // 近7天
        shortcuts.push({
          text: '近7天',
          value: () => {
            const start = new Date(today)
            start.setDate(start.getDate() - 6)
            start.setHours(0, 0, 0, 0)
            const end = new Date(today)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '4': // 近30天
        shortcuts.push({
          text: '近30天',
          value: () => {
            const start = new Date(today)
            start.setDate(start.getDate() - 29)
            start.setHours(0, 0, 0, 0)
            const end = new Date(today)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '5': // 本周
        shortcuts.push({
          text: '本周',
          value: () => {
            const start = new Date(today)
            const day = start.getDay()
            const diff = start.getDate() - day + (day === 0 ? -6 : 1)
            start.setDate(diff)
            start.setHours(0, 0, 0, 0)
            const end = new Date(today)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '6': // 本月
        shortcuts.push({
          text: '本月',
          value: () => {
            const start = new Date(today.getFullYear(), today.getMonth(), 1)
            start.setHours(0, 0, 0, 0)
            const end = new Date(today)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break

      case '7': // 上月
        shortcuts.push({
          text: '上月',
          value: () => {
            const start = new Date(today.getFullYear(), today.getMonth() - 1, 1)
            start.setHours(0, 0, 0, 0)
            const end = new Date(today.getFullYear(), today.getMonth(), 0)
            end.setHours(23, 59, 59, 999)
            return [start, end]
          }
        })
        break
    }
  })

  return shortcuts.length > 0 ? shortcuts : undefined
}

// 获取单个日期的快捷选项
const getSingleDateShortcuts = (quickOptions?: string) => {
  if (!quickOptions) return undefined

  const shortcuts = []
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 解析quickOptions，支持多个选项组合（如："1,2"）
  const options = quickOptions.split(',').map((opt) => opt.trim())

  options.forEach((option) => {
    switch (option) {
      case '1': // 今天
        shortcuts.push({
          text: '今天',
          value: () => {
            return new Date(today)
          }
        })
        break

      case '2': // 昨天
        shortcuts.push({
          text: '昨天',
          value: () => {
            const yesterday = new Date(today)
            yesterday.setDate(yesterday.getDate() - 1)
            return yesterday
          }
        })
        break

      case '3': // 本周第一天
        shortcuts.push({
          text: '本周第一天',
          value: () => {
            const start = new Date(today)
            const day = start.getDay()
            const diff = start.getDate() - day + (day === 0 ? -6 : 1)
            start.setDate(diff)
            return start
          }
        })
        break

      case '4': // 本月第一天
        shortcuts.push({
          text: '本月第一天',
          value: () => {
            return new Date(today.getFullYear(), today.getMonth(), 1)
          }
        })
        break

      case '5': // 上月第一天
        shortcuts.push({
          text: '上月第一天',
          value: () => {
            return new Date(today.getFullYear(), today.getMonth() - 1, 1)
          }
        })
        break
    }
  })

  return shortcuts.length > 0 ? shortcuts : undefined
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const data = await props.config.api.getList(queryParams)
    console.log('TableList getList data:', data)
    console.log('TableList getList list:', data.list)
    // 保存原始数据
    originalList.value = data.list || []
    // 更新本地列表数据并应用列筛选
    const filteredList = applyColumnFilters(data.list || [])
    console.log('TableList getList filteredList:', filteredList)
    list.value = filteredList
    // 通过 emit 通知父组件更新数据（保持兼容性）
    emit('update:data', list.value)
    emit('update:loading', false)
    total.value = data.total
  } finally {
    loading.value = false        
    pageInitLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  
  // 处理输入框类型字段，过滤前后空格
  const searchItems = searchFormConfig.value?.items || []
  searchItems.forEach((item: any) => {
    // 检查是否是输入框类型
    if (item.type === 'input' && item.field in queryParams) {
      const value = queryParams[item.field]
      if (typeof value === 'string') {
        queryParams[item.field] = value.trim()
      }
    }
    
    // 检查是否是时间范围类型且有field1和field2属性
    if (item.type === 'date-range' && item.field1 && item.field2) {
      const rangeValue = queryParams[item.field]
      if (Array.isArray(rangeValue) && rangeValue.length === 2) {
        // 将时间范围数组的值分别赋给field1和field2
        queryParams[item.field1] = rangeValue[0]
        queryParams[item.field2] = rangeValue[1]
      } else {
        // 如果清除了查询参数的field，同步清除field1、field2
        delete queryParams[item.field1]
        delete queryParams[item.field2]
      }
    }
  })
  
  if (props.config.onSearch) {
    props.config.onSearch(queryParams)
  } else {
    getList()
  }
  // 保存查询条件到 localStorage
  saveQueryParamsToStorage(queryParams)
}

// 高级搜索
const handleAdvancedSearch = () => {
  showAdvancedPopover.value = false
  handleSearch()
}

// 重置
const handleReset = () => {
  // queryFormRef.value?.resetFields()
  // 重置到初始状态，保留分页参数和初始查询参数
  Object.keys(queryParams).forEach((key) => {
    // 保留分页参数
    if (key === 'pageNo' || key === 'pageSize') {
      return
    }
    // 保留从 props.config.queryParams 传进来的初始参数
    if (props.config.queryParams && key in props.config.queryParams) {
      queryParams[key] = props.config.queryParams[key]
      return
    }
    // 删除其他参数（用户手动添加的查询参数）
    delete queryParams[key]
  })
  queryParams.pageNo = 1

  // 重新设置默认值（使用延迟，确保动态字段配置已加载）
  nextTick(() => {
    initializeDefaultValues()
  })

  // 清除 localStorage 中的查询条件
  clearQueryParamsFromStorage()
  // 清除 localStorage 中的展开/收起状态
  clearExpandStateFromStorage()

  if (props.config.onReset) {
    props.config.onReset()
  } else {
    handleSearch()
  }
}

// 重置并刷新
const handleResetRefresh = () => {
  // 重置所有列的筛选条件
  columnFilters.value = {}
  tempColumnFilters.value = {}
  // 重置查询参数
  handleReset()
}

// 分页变化
const handlePaginationChange = (e: any) => {
  console.log(e)
  queryParams.pageNo = e.page
  queryParams.pageSize = e.limit
  getList()
}

// 获取行类名（用于单选模式的视觉反馈）
const getRowClassName = ({ row }: { row: any }) => {
  // 只在单选模式下添加选中样式
  if (props.config.table.selection === false) {
    const isSelected = selectedRows.value.some((selected) => selected === row)
    return isSelected ? 'selected-row' : ''
  }
  return ''
}

// 展开变化事件（处理树形表格的展开/折叠）
const handleExpandChange = (row: any, expanded: boolean) => {
  const rowId = row[props.config.table.rowKey || 'id']

  if (expanded) {
    // 展开时，添加到展开列表
    if (!internalExpandRowKeys.value.includes(rowId)) {
      internalExpandRowKeys.value.push(rowId)
    }
  } else {
    // 折叠时，从展开列表移除
    const index = internalExpandRowKeys.value.indexOf(rowId)
    if (index > -1) {
      internalExpandRowKeys.value.splice(index, 1)
    }
  }
}

// 行点击事件（处理单选模式）
const handleRowClick = (row: any, column: any, event: Event) => {
  // 只在单选模式下启用行点击选择（config.table.selection 为 false 时表示单选模式）
  if (props.config.table.selection === false) {
    if (Array.isArray(selectedRows.value) && selectedRows.value.length > 0) {
      // 如果已经选中了行，检查是否点击的是已选中的行
      const selectedIndex = selectedRows.value.findIndex((selected) => selected === row)
      if (selectedIndex > -1) {
        // 点击已选中的行，取消选中
        selectedRows.value = []
      } else {
        // 点击未选中的行，选中该行
        selectedRows.value = [row]
      }
    } else {
      // 没有选中任何行，选中当前行
      selectedRows.value = [row]
    }

    // 发射选择变化事件
    emit('selectionChange', [...selectedRows.value])
    // 调用父组件的回调
    if (props.config.onSelectionChange) {
      props.config.onSelectionChange([...selectedRows.value])
    }
  }
}
// 行双击事件（触发行双击事件）
const handleRowDblClick = (row: any, column: any, cell: HTMLElement, event: Event) => {
  console.log('rowDblClick', row)
  // 发射双击事件，传递行数据
  emit('rowDblClick', row)
}
// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  // 发射选择变化事件
  emit('selectionChange', selection)
  // 调用父组件的回调
  if (props.config.onSelectionChange) {
    props.config.onSelectionChange(selection)
  }
}

// 更新查询参数
const updateQueryParams = (newParams: Record<string, any>) => {
  Object.keys(newParams).forEach((key) => {
    if (newParams[key] !== undefined) {
      queryParams[key] = newParams[key]
    } else {
      delete queryParams[key]
    }
  })
}

// 更新展开的行键
const updateExpandRowKeys = (keys: any[]) => {
  internalExpandRowKeys.value = keys
}

// 暴露方法给父组件
defineExpose({
  getList,
  handleSearch,
  handleReset,
  selectedRows,
  queryParams,
  updateQueryParams,
  updateExpandRowKeys
})

// 初始化
onMounted(async () => {
  calculateTableContainerHeight()
  window.addEventListener('resize', calculateTableContainerHeight)
  // 处理静态列：对每个列的formatter进行解析
  internalColumns.value = props.config.table.columns.map((col) => ({
    ...col,
    formatter: resolveFormatter(col.formatter) // 关键：统一解析，无formatter则返回undefined
  }))

  // 如果有 gridCode，先加载字段配置
  if (props.config.gridCode) {
    await loadFieldConfig()
  } else {
    // 没有动态字段时直接初始化默认值
    initializeDefaultValues()
    // 从 localStorage 恢复上次的查询条件
    const storedParams = loadQueryParamsFromStorage()
    if (storedParams) {
      Object.assign(queryParams, storedParams)
    }
    // 初始化展开/收起状态
    initCollapseState()
    // 根据 autoLoad 属性决定是否自动加载数据
    if (autoLoad.value) {
      getList()
    }
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', calculateTableContainerHeight)
})
watch(
  [() => props.config, () => props.autoLoad],
  async ([newConfig, newAutoLoad]) => {
    if (newConfig) {
      // 重新扩展 queryParams
      const newQueryParams: any = {
        pageNo: 1,
        pageSize: newConfig.pagination?.pageSize || 10,
        ...newConfig.queryParams
      }
      // 使用 Object.assign 更新 reactive 对象
      Object.assign(queryParams, newQueryParams)
      
      // 重新初始化 internalColumns
      internalColumns.value = newConfig.table.columns.map((col) => ({
        ...col,
        formatter: resolveFormatter(col.formatter)
      }))
      
      // 重新加载字段配置（如果有 gridCode）
      if (newConfig.gridCode) {
        await loadFieldConfig()
      } else {
        // 没有动态字段时重新初始化默认值
        initializeDefaultValues()
        // 从 localStorage 恢复上次的查询条件
        const storedParams = loadQueryParamsFromStorage()
        if (storedParams) {
          Object.assign(queryParams, storedParams)
        }
        // 初始化展开/收起状态
        initCollapseState()
        // 如果 autoLoad 为 true（默认为 true），调用 getList()
        // 注意：loadFieldConfig() 会内部调用 getList()，所以这里只在没有 gridCode 时调用
        if (newAutoLoad === undefined || newAutoLoad === true) {
          getList()
        }
      }
    }
  },
  { deep: true, immediate: false }
)
</script>

<style scoped>
.table-list {
  width: 100%;
  transition: all 0.3s ease;
  overflow-y: auto;
}
.full-height {
  height: calc(
    100vh - var(--top-tool-height) - var(--tags-view-height) - 60px
  );
}
/**
.table-list.full-height {
  overflow-y: hidden;
}
**/
/* 全屏状态下的样式 */
.table-list:fullscreen {
  background-color: #fff;
  padding: 20px;
  overflow: auto;
}

.table-list:-webkit-full-screen {
  background-color: #fff;
  padding: 20px;
  overflow: auto;
}

.table-list:-moz-full-screen {
  background-color: #fff;
  padding: 20px;
  overflow: auto;
}

.table-list:-ms-fullscreen {
  background-color: #fff;
  padding: 20px;
  overflow: auto;
}

/* 单选模式下的选中行样式 */
:deep(.selected-row) {
  background-color: #ecf5ff !important;
  cursor: pointer;
}

:deep(.selected-row:hover) {
  background-color: #d9ecff !important;
}

:deep(.el-table__body tr) {
  cursor: pointer;
}

/* 单选模式下鼠标悬停效果 */
:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.selected-row:hover > td) {
  background-color: #d9ecff !important;
}

/* 全屏状态下的表格容器样式优化 */
.table-list:fullscreen .ContentWrap,
.table-list:-webkit-full-screen .ContentWrap,
.table-list:-moz-full-screen .ContentWrap,
.table-list:-ms-fullscreen .ContentWrap {
  max-height: none;
  height: calc(100vh - 40px);
}

.table-list:fullscreen .el-table,
.table-list:-webkit-full-screen .el-table,
.table-list:-moz-full-screen .el-table,
.table-list:-ms-fullscreen .el-table {
  max-height: calc(100vh - 200px);
  overflow: auto;
}

.size-options {
  padding: 4px 0;
}

.size-option {
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.2s;
  border-radius: 4px;
}

.size-option:hover {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.size-option.active {
  background-color: var(--el-color-primary);
  color: white;
}

.column-settings-content {
  padding: 16px 0;
  padding-top: 0px;
}

.settings-tip {
  margin: 10px 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.column-list {
  max-height: 400px;
  overflow-y: auto;
  min-height: 60px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.column-list.drag-over {
  background-color: var(--el-color-primary-light-9);
  border: 2px dashed var(--el-color-primary);
}

.column-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 6px;
  cursor: move;
  transition: all 0.2s;
  border: 1px solid var(--el-border-color);
  color: rgba(0, 0, 0, 0.88);
}

.column-item:hover {
  color: var(--el-color-primary);
  border-color: var(--el-color-primary);
}

.column-item.column-hidden {
  opacity: 0.6;
  background-color: var(--el-fill-color-lighter);
}

.column-item.column-hidden .column-label {
  color: var(--el-text-color-disabled);
}

.column-item.dragging {
  opacity: 0.7;
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  position: relative;
}

.drag-handle {
  margin-right: 8px;
  color: var(--el-text-color-secondary);
}

.column-label {
  flex: 1;
  font-size: 14px;
  margin-left: 6px;
}

.table-actions {
  display: flex;
  gap: 0px;
  flex-wrap: wrap;
}

.search-form-item {
  margin-bottom: 18px;
}

.search-form-item .el-form-item {
  margin-bottom: 0;
}

.search-buttons-row {
  margin-top: 10px;
}

.search-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.search-buttons .el-form-item {
  margin-bottom: 0;
}

/* 查询条件label文字省略样式 */
.search-form-item :deep(.el-form-item__label) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100%;
}
.actions-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.ml-10px {
  margin-left: 10px;
}
.setting-btns {
  display: flex;
  align-items: center;
  margin-left: auto;
  padding-right: 10px;
}

.cursor-pointer {
  cursor: pointer;
}

.hover\:text-primary:hover {
  color: var(--el-color-primary);
}
.-mb-10px {
  margin-bottom: -10px;
}

/* 下载列选择弹窗样式 */
.download-columns-content {
  padding: 16px 0;
}

.download-columns-header {
  margin-bottom: 8px;
  padding-left: 8px;
}

.download-columns-list {
  max-height: 400px;
  overflow-y: auto;
}

.download-column-item {
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.download-column-item:last-child {
  border-bottom: none;
}

/* 修改列设置提示样式 */
.settings-tip {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  margin: 10px 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.table-list {
  :deep(.el-form-item__label) {
    text-align: right !important;
  }
}
:deep(.noCard.el-card) {
  box-shadow: none !important;
}
:deep(.noCard.el-card .el-card__body) {
  padding: 0 !important;
}
</style>
