import T from 'ant-design-vue/es/table/Table'
import get from 'lodash.get'
import { mapState } from 'vuex'
import { STABLE_VIRTUAL_SCROLL_MIN_ROWS } from '@vue2-client/components/STable/virtualScrollThreshold'
import { executeStrFunctionByContext } from '@vue2-client/utils/runEvalFunction'

export default {
  data() {
    return {
      clickedRowKey: null,
      hoveredRowKey: null, // 跟踪鼠标悬浮的行
      needTotalList: [],

      selectedRows: [],
      selectedRowKeys: [],

      localLoading: false,
      localDataSource: [],
      localPagination: Object.assign({}, this.pagination),

      sortField: undefined,
      sortOrder: undefined,
      pageNum: 1,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40']
    }
  },
  props: Object.assign({}, T.props, {
    rowKey: {
      type: [String, Function],
      default: 'key'
    },
    data: {
      type: Function,
      required: true
    },
    setScrollYHeight: {
      type: Function,
      required: true
    },
    showSizeChanger: {
      type: Boolean,
      default: true
    },
    showSummary: {
      type: Boolean,
      default: false
    },
    selectRowMode: {
      type: String,
      default: 'default'
    },
    size: {
      type: String,
      default: 'default'
    },
    /**
     * alert: {
     *   show: true,
     *   clear: Function
     * }
     */
    alert: {
      type: [Object, Boolean],
      default: null
    },
    rowSelection: {
      type: Object,
      default: null
    },
    /** @Deprecated */
    showAlertInfo: {
      type: Boolean,
      default: false
    },
    showPagination: {
      type: [String, Boolean],
      default: 'auto'
    },
    // 是否隐藏翻页，如果隐藏，彻底不显示翻译
    hidePagination: {
      type: Boolean,
      default: false
    },
    // 是否显示表头已选择部分
    showSelected: {
      type: Boolean,
      default: true
    },
    /**
     * enable page URI mode
     *
     * e.g:
     * /users/1
     * /users/2
     * /users/3?queryParam=test
     * ...
     */
    pageURI: {
      type: Boolean,
      default: false
    },
    // 最大分页大小，如果设置则使用该值作为分页大小并隐藏分页组件
    pageMaxSize: {
      type: Number,
      default: null
    },
    // 是否使用自定义分页样式
    customPagination: {
      type: Boolean,
      default: false
    },
    // 行样式函数，用于控制每行的样式类型
    rowStyleFunction: {
      type: [Function, String],
      default: null
    },
    // 默认查询的当页行数
    defaultPageSize: {
      type: Number,
      default: 10
    },
    pageSizeArray: {
      type: Array,
      default: () => ['10', '20', '30', '40']
    },
    /**
     * 为 false 时不向底层 a-table 传递 expandedRowRender 插槽。
     * Vue 2 中带 slot 名的 template 即使 v-if 为 false，仍可能把 expandedRowRender 注册进 $scopedSlots，导致出现展开列。
     */
    expandedRowEnabled: {
      type: Boolean,
      default: true
    }
  }),
  computed: {
    ...mapState('setting', ['theme']), // 添加 theme 到计算属性

    // 计算点击行的背景色，使用 10% 透明度
    clickedRowColor() {
      const themeColor = this.$store.state.setting.theme.color
      return this.hexToRgba(themeColor || '#1890ff', 0.1)
    },
    /** 当前页数据行数（仅监听长度变更，避免对行对象做深度 watch） */
    localDataSourceLength() {
      return Array.isArray(this.localDataSource) ? this.localDataSource.length : 0
    }
  },
  watch: {
    'localPagination.current'(val) {
      this.pageURI &&
        this.$router.push({
          ...this.$route,
          name: this.$route.name,
          params: Object.assign({}, this.$route.params, {
            pageNo: val
          })
        })
      // change pagination, reset total data
      this.needTotalList = this.initTotalList(this.columns)
      if (this.selectRowMode === 'default') {
        this.selectedRowKeys = []
        this.selectedRows = []
      }
    },
    pageNum(val) {
      Object.assign(this.localPagination, {
        current: val
      })
    },
    pageSize(val) {
      Object.assign(this.localPagination, {
        pageSize: val
      })
    },
    showSizeChanger(val) {
      Object.assign(this.localPagination, {
        showSizeChanger: val
      })
    },
    pageMaxSize: {
      handler(val) {
        if (val && !this.defaultPageSize) {
          this.pageSize = val
          // 更新 localPagination
          if (this.localPagination) {
            Object.assign(this.localPagination, {
              pageSize: val
            })
          }
        }
      },
      immediate: true
    },
    pageSizeArray: {
      handler(val) {
        if (val && val.length) {
          this.pageSizeOptions = [...val]
        }
      },
      immediate: true
    },
    /** 同步当前数据源行数供外层（如 XTableWrapper）与纵向虚拟滚动行为对齐 */
    localDataSourceLength: {
      handler(len) {
        this.$emit('localDataSourceLengthChange', len)
      },
      immediate: true
    }
  },
  created() {
    const { pageNo } = this.$route.params
    const localPageNum = (this.pageURI && pageNo && parseInt(pageNo)) || this.pageNum

    // 优先使用 defaultPageSize，其次才使用 pageMaxSize（向后兼容）
    if (this.defaultPageSize) {
      this.pageSize = this.defaultPageSize
    }
    // 即将删除的过期属性
    if (this.pageMaxSize) {
      this.pageSize = this.pageMaxSize
    }
    // 新增属性-分页选项
    if (this.pageSizeArray && this.pageSizeArray.length) {
      this.pageSizeOptions = this.pageSizeArray
    }

    this.localPagination =
      (['auto', true].includes(this.showPagination) &&
        Object.assign({}, this.localPagination, {
          current: localPageNum,
          pageSize: this.pageSize,
          showSizeChanger: this.showSizeChanger
        })) ||
      false
    this.needTotalList = this.initTotalList(this.columns)
    // this.loadData()
  },
  methods: {
    /**
     * 为虚拟滚动写入稳定行键（与 ant-design-vue rowKey 语义对齐）
     */
    ensureVirtualKeysForRows(rows) {
      if (!rows || !rows.length) return
      const rk = this.rowKey
      rows.forEach((row, index) => {
        let keyVal
        if (typeof rk === 'function') {
          keyVal = rk(row, index)
        } else if (rk === '序号') {
          keyVal = index
        } else {
          keyVal = row[rk]
        }
        const k = keyVal != null && keyVal !== '' ? String(keyVal) : `__row_${index}`
        this.$set(row, '__v_key', k)
      })
    },
    /**
     * 父组件 setScrollYHeight 回调后，同步刷新虚拟表测量（表格高度/滚动容器变化）
     */
    invokeSetScrollYHeight(opts) {
      if (typeof this.setScrollYHeight === 'function') {
        this.setScrollYHeight(opts)
      }
      this.$nextTick(() => {
        const vt = this.$refs.vtable
        if (vt && typeof vt.update === 'function') {
          vt.update()
        }
      })
    },
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param Boolean bool
     */
    refresh(bool = false) {
      bool &&
        (this.localPagination = Object.assign(
          {},
          {
            current: 1,
            pageSize: this.pageSize
          }
        ))
      this.loadData()
    },
    /**
     * 加载数据方法
     * @param {Object} pagination 分页选项器
     * @param {Object} filters 过滤条件
     * @param {Object} sorter 排序条件
     */
    loadData(pagination, filters, sorter) {
      this.localLoading = true
      // 暂存排序方式，避免 refresh 之后排序失效
      if (sorter && sorter.field) {
        this.sortField = sorter.field
      }
      if (sorter && sorter.order) {
        this.sortOrder = sorter.order
      }

      // 确定 pageSize
      let finalPageSize = this.pageSize
      if (this.showPagination === false) {
        // 当 showPagination 为 false 时，优先使用传入的 pageSize
        finalPageSize = this.defaultPageSize || pagination?.pageSize
      } else if (pagination && pagination.pageSize) {
        finalPageSize = pagination.pageSize
      } else if (this.localPagination && this.localPagination.pageSize) {
        finalPageSize = this.localPagination.pageSize
      }

      const parameter = Object.assign(
        {
          querySummary: !pagination && this.showSummary, // 分页查询的情况不重新获取汇总数据
          pageNo:
            (pagination && pagination.current) || (this.showPagination && this.localPagination.current) || this.pageNum,
          pageSize: finalPageSize
        },
        (this.sortField && { sortField: this.sortField }) || {},
        (this.sortOrder && { sortOrder: this.sortOrder }) || {},
        { ...filters }
      )

      // 在加载新数据前，将当前数据传递给父组件
      if (this.localDataSource && this.localDataSource.length > 0) {
        // 变化前的数据: oldData, 分页信息: pagination, 过滤条件: filters, 排序信息: sorter
        this.$emit('beforeDataChange', {
          oldData: this.localDataSource,
          pagination: this.localPagination,
          filters: filters,
          sorter: sorter
        })
      }

      const result = this.data(parameter)
      // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.totalCount, r.data
      // eslint-disable-next-line
      if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
        result.then(
          r => {
            this.localPagination =
              (this.showPagination &&
                Object.assign({}, this.localPagination, {
                  current: r.pageNo, // 返回结果中的当前分页数
                  total: r.totalCount, // 返回结果中的总记录数
                  showSizeChanger: this.showSizeChanger,
                  pageSize: finalPageSize
                })) ||
              false
            // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
            if (r.data.length === 0 && this.showPagination && this.localPagination.current > 1) {
              this.localPagination.current--
              this.loadData()
              return
            }

            // 这里用于判断接口是否有返回 r.totalCount 且 this.showPagination = 'auto' 且 pageNo 和 pageSize 存在 且 totalCount 小于等于 pageNo * pageSize 的大小
            // 当情况满足时，表示数据不满足分页大小，关闭 table 分页功能
            try {
              if (['auto'].includes(this.showPagination) && r.totalCount <= r.pageNo * this.localPagination.pageSize) {
                this.localPagination.hideOnSinglePage = true
              }
            } catch (e) {
              this.localPagination = false
            }
            this.ensureVirtualKeysForRows(r.data)
            this.localDataSource = r.data // 返回结果中的数组数据
            this.localLoading = false
            // 清除选中行状态（翻页或重新查询时）
            this.clickedRowKey = null
            this.invokeSetScrollYHeight({ type: 'default' })
          },
          () => {
            this.localLoading = false
            this.invokeSetScrollYHeight({ type: 'default' })
          }
        )
      }
    },
    setLocalDataSource(data) {
      this.ensureVirtualKeysForRows(data)
      this.localDataSource = data
    },
    initTotalList(columns) {
      const totalList = []
      columns &&
        columns instanceof Array &&
        columns.forEach(column => {
          if (column.needTotal) {
            totalList.push({
              ...column,
              total: 0
            })
          }
        })
      return totalList
    },
    /**
     * 用于更新已选中的列表数据 total 统计
     * @param selectedRowKeys
     * @param selectedRows
     */
    updateSelect(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
      const list = this.needTotalList
      this.needTotalList = list.map(item => {
        return {
          ...item,
          total: selectedRows.reduce((sum, val) => {
            const total = sum + parseInt(get(val, item.dataIndex))
            return isNaN(total) ? 0 : total
          }, 0)
        }
      })
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected() {
      if (this.rowSelection) {
        this.rowSelection.onChange([], [])
        this.updateSelect([], [])
      }
    },
    /**
     * 处理交给 table 使用者去处理 clear 事件时，内部选中统计同时调用
     * @param callback
     * @returns {*}
     */
    renderClear(callback) {
      if (this.selectedRowKeys.length <= 0) return null
      return (
        <a
          style="margin-left: 24px"
          onClick={() => {
            callback()
            this.clearSelected()
          }}
        >
          清空
        </a>
      )
    },
    renderAlert() {
      // 绘制统计列数据
      const needTotalItems = this.needTotalList.map(item => {
        return (
          <span style="margin-right: 12px">
            {item.title}总计{' '}
            <a style="font-weight: 600">{!item.customRender ? item.total : item.customRender(item.total)}</a>
          </span>
        )
      })

      // 绘制 清空 按钮
      const clearItem =
        typeof this.alert.clear === 'boolean' && this.alert.clear
          ? this.renderClear(this.clearSelected)
          : typeof this.alert.clear === 'function'
          ? this.renderClear(this.alert.clear)
          : null

      // 绘制 alert 组件
      return (
        <a-alert showIcon={true} style={{ marginBottom: '8px', fontSize: '14px' }}>
          <template slot="message">
            <span style="margin-right: 12px;">
              已选择: <a style="font-weight: 600">{this.selectedRows.length}</a>
            </span>
            {needTotalItems}
            {clearItem}
          </template>
        </a-alert>
      )
    },
    onExpand(expanded, record) {
      this.$emit('expand', expanded, record)
    },
    handleRowClick(record, index, event, options = {}) {
      const { forceSelect = false, emitRowClick = true } = options
      const isRowKeySequence = this.rowKey === '序号'
      const currentRowKey = isRowKeySequence ? index : record[this.rowKey]
      const isDoubleClick = event && event.detail > 1
      const isSameRow = this.clickedRowKey === currentRowKey

      // 如果点击的是编辑单元格或操作列内的元素，不触发行点击事件
      if (event && event.target) {
        const clickedElement = event.target.closest
          ? event.target.closest('.innerTable, .ant-dropdown, .x-table-action-dropdown')
          : null
        if (clickedElement) {
          return
        }
      }

      if (forceSelect || isDoubleClick) {
        this.clickedRowKey = currentRowKey
        emitRowClick && this.$emit('rowClick', record)
        return
      }

      // 如果点击的是已选中的行，则取消选中；否则选中该行
      if (isSameRow) {
        this.clickedRowKey = null
        emitRowClick && this.$emit('rowClick', null) // 传递 null 表示取消选中
      } else {
        this.clickedRowKey = currentRowKey
        emitRowClick && this.$emit('rowClick', record)
      }
    },
    handleRowDoubleClick(record, index, event) {
      this.handleRowClick(record, index, event, { forceSelect: true })
      this.$emit('rowDblClick', record)
    },
    /** 悬停：默认关闭（避免 hoveredRowKey 触发 STable 整表重绘，滚动更顺）。需行 hover 高亮时再恢复内部赋值与 emit */
    handleRowMouseEnter() {},
    handleRowMouseLeave() {},
    hexToRgba(hex, alpha = 1) {
      try {
        const r = parseInt(hex.slice(1, 3), 16)
        const g = parseInt(hex.slice(3, 5), 16)
        const b = parseInt(hex.slice(5, 7), 16)
        return `rgba(${r}, ${g}, ${b}, ${alpha})`
      } catch (e) {
        return '#e6f7ff'
      }
    },
    // 获取行样式类型
    getRowStyleType(record, index) {
      if (this.rowStyleFunction) {
        try {
          // 如果是函数对象，直接执行
          if (typeof this.rowStyleFunction === 'function') {
            return this.rowStyleFunction(record, index)
          }
          // 如果是字符串函数，使用executeStrFunctionByContext执行
          if (typeof this.rowStyleFunction === 'string') {
            return executeStrFunctionByContext(this, this.rowStyleFunction, [record, index])
          }
        } catch (e) {
          console.warn('Row style function error:', e)
          return 'info'
        }
      }
      return 'info'
    },
    // 根据行样式类型和是否激活获取背景色
    // isActive: 是否处于 hover 或 selected 状态
    getRowBgColor(styleType, isActive = false) {
      const colorMap = {
        success: {
          normal: 'rgba(82, 196, 26, 0.2)',
          active: 'rgba(82, 196, 26, 0.2)'
        },
        warning: {
          normal: 'rgba(250, 173, 20, 0.1)',
          active: 'rgba(250, 173, 20, 0.2)'
        },
        error: {
          normal: 'rgba(245, 34, 47, 0.1)',
          active: 'rgba(245, 34, 47, 0.2)'
        },
        danger: {
          normal: 'rgba(245, 34, 47, 0.1)',
          active: 'rgba(245, 34, 47, 0.2)'
        },
        magic: {
          normal: 'rgba(114, 46, 209, 0.1)',
          active: 'rgba(114, 46, 209, 0.2)'
        },
        warn: {
          normal: 'rgba(250, 173, 20, 0.1)',
          active: 'rgba(250, 173, 20, 0.2)'
        },
        info: {
          normal: '',
          active: 'rgba(24, 144, 255, 0.2)'
        }
      }

      const colors = colorMap[styleType] || colorMap.info
      return isActive ? colors.active : colors.normal
    },
    // 获取行样式颜色（根据当前行的 hover 和 selected 状态）
    getRowStyleClass(record, index) {
      const isRowKeySequence = this.rowKey === '序号'
      const currentRowKey = isRowKeySequence ? index : record[this.rowKey]

      // 判断是否是选中行或悬浮行
      const isActive = this.clickedRowKey === currentRowKey || this.hoveredRowKey === currentRowKey

      // 获取行样式类型
      const styleType = this.getRowStyleType(record, index)

      // 返回对应颜色
      return this.getRowBgColor(styleType, isActive)
    }
  },

  render() {
    const props = {}
    const localKeys = Object.keys(this.$data)
    const showAlert =
      (typeof this.alert === 'object' &&
        this.alert !== null &&
        this.alert.show &&
        typeof this.rowSelection.selectedRowKeys !== 'undefined') ||
      this.alert

    Object.keys(T.props).forEach(k => {
      const localKey = `local${k.substring(0, 1).toUpperCase()}${k.substring(1)}`
      if (localKeys.includes(localKey)) {
        props[k] = this[localKey]
        return props[k]
      }
      if (k === 'rowSelection') {
        if (showAlert && this.rowSelection) {
          // 如果需要使用alert，则重新绑定 rowSelection 事件
          props[k] = {
            ...this.rowSelection,
            selectedRows: this.selectedRows,
            selectedRowKeys: this.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              this.updateSelect(selectedRowKeys, selectedRows)
              typeof this[k].onChange !== 'undefined' && this[k].onChange(selectedRowKeys, selectedRows)
            }
          }
          return props[k]
        } else if (!this.rowSelection) {
          // 如果没打算开启 rowSelection 则清空默认的选择项
          props[k] = null
          return props[k]
        }
      }
      this[k] && (props[k] = this[k])
      return props[k]
    })
    // 取消原有的分页组件 产品设计分页组件和汇总在一行 重新分页逻辑
    props.pagination = false
    const tableData = Array.isArray(props.dataSource) ? props.dataSource : []
    if (props.scroll && props.scroll.y && tableData.length > STABLE_VIRTUAL_SCROLL_MIN_ROWS) {
      props.scroll = {
        ...props.scroll,
        virtual: { itemHeight: 60, overscan: 10 }
      }
    }

    // 使用 rowClassName 实现响应式行样式
    props.rowClassName = (record, index) => {
      const isRowKeySequence = this.rowKey === '序号'
      const currentRowKey = isRowKeySequence ? index : record[this.rowKey]

      const classes = []

      // 判断是否是选中行（点击状态）
      if (this.clickedRowKey === currentRowKey) {
        classes.push('row-clicked')
      }

      // 添加行样式类型（用于不同的颜色主题）
      const styleType = this.getRowStyleType(record, index)
      classes.push(`row-style-${styleType}`)

      return classes.join(' ')
    }

    // 在 props 中添加自定义行事件
    props.customRow = (record, index) => {
      return {
        on: {
          click: event => this.handleRowClick(record, index, event),
          dblclick: event => this.handleRowDoubleClick(record, index, event),
          mouseenter: () => this.handleRowMouseEnter(record, index),
          mouseleave: () => this.handleRowMouseLeave(record, index)
        }
      }
    }
    // 自定义底部汇总插槽组件
    const pagination = !!this.showPagination && (
      <a-row type={'flex'} justify={'start'} style={{ marginTop: '8px' }}>
        <a-col
          flex="1"
          style={{
            alignItems: 'center',
            display: 'flex',
            justifyContent: 'start',
            boxSizing: 'border-box',
            paddingRight: '2rem'
          }}
        >
          {this.$slots.fixedfooter}
        </a-col>
        <a-col flex="0 0">
          {this.customPagination ? (
            <div class="custom-pagination-container">
              {/* 首页按钮 */}
              <div
                class={['custom-pagination-btn', { disabled: this.localPagination.current === 1 }]}
                onClick={() => {
                  if (this.localPagination.current > 1) {
                    this.pageSize = this.localPagination.pageSize
                    this.pageNum = 1
                    this.loadData({
                      current: 1,
                      pageSize: this.localPagination.pageSize
                    })
                  }
                }}
              >
                <span class="custom-pagination-icon icon-rotate-right">⌅</span>
              </div>

              {/* 上一页按钮 */}
              <div
                class={['custom-pagination-btn', { disabled: this.localPagination.current === 1 }]}
                onClick={() => {
                  if (this.localPagination.current > 1) {
                    this.pageSize = this.localPagination.pageSize
                    this.pageNum = this.localPagination.current - 1
                    this.loadData({
                      current: this.localPagination.current - 1,
                      pageSize: this.localPagination.pageSize
                    })
                  }
                }}
              >
                &lt;
              </div>

              {/* 当前页按钮 */}
              <div class="custom-pagination-btn active">{this.localPagination.current}</div>

              {/* 下一页按钮 */}
              <div
                class={[
                  'custom-pagination-btn',
                  {
                    disabled:
                      this.localPagination.current ===
                        (this.localPagination && this.localPagination.pageSize
                          ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                          : 0) ||
                      !(this.localPagination && this.localPagination.pageSize
                        ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                        : 0)
                  }
                ]}
                onClick={() => {
                  const totalPages =
                    this.localPagination && this.localPagination.pageSize
                      ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                      : 0
                  if (totalPages > 0 && this.localPagination.current < totalPages) {
                    this.pageSize = this.localPagination.pageSize
                    this.pageNum = this.localPagination.current + 1
                    this.loadData({
                      current: this.localPagination.current + 1,
                      pageSize: this.localPagination.pageSize
                    })
                  }
                }}
              >
                &gt;
              </div>

              {/* 末页按钮 */}
              <div
                class={[
                  'custom-pagination-btn',
                  {
                    disabled:
                      this.localPagination.current ===
                        (this.localPagination && this.localPagination.pageSize
                          ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                          : 0) ||
                      !(this.localPagination && this.localPagination.pageSize
                        ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                        : 0)
                  }
                ]}
                onClick={() => {
                  const totalPages =
                    this.localPagination && this.localPagination.pageSize
                      ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                      : 0
                  if (totalPages > 0 && this.localPagination.current < totalPages) {
                    this.pageSize = this.localPagination.pageSize
                    this.pageNum = totalPages
                    this.loadData({
                      current: totalPages,
                      pageSize: this.localPagination.pageSize
                    })
                  }
                }}
              >
                <span class="custom-pagination-icon icon-rotate-left">⌅</span>
              </div>

              {/* 分页信息 */}
              <div class="custom-pagination-info">
                共
                {this.localPagination && this.localPagination.pageSize
                  ? Math.ceil((this.localPagination.total || 0) / (this.localPagination.pageSize || 1))
                  : 0}
                页,{' '}
                {this.localPagination && typeof this.localPagination.total !== 'undefined'
                  ? this.localPagination.total
                  : 0}
                条
              </div>
            </div>
          ) : (
            <a-pagination
              total={this.localPagination.total}
              pageSize={this.localPagination.pageSize}
              current={this.localPagination.current}
              pageSizeOptions={this.pageSizeOptions}
              onChange={(page, pageSize) => {
                this.pageSize = pageSize
                this.pageNum = page
                this.loadData({
                  current: page,
                  pageSize: pageSize
                })
              }}
              onShowSizeChange={(page, pageSize) => {
                this.pageSize = pageSize
                this.pageNum = page
                this.loadData({
                  current: page,
                  pageSize: pageSize
                })
              }}
              show-total={(total, range) =>
                range[0] === range[1] ? `${range[0]} | 共 ${total} 项` : `${range[0]}-${range[1]} | 共 ${total} 项`
              }
              showSizeChanger={this.localPagination.showSizeChanger}
            />
          )}
        </a-col>
      </a-row>
    )
    const forwardedScopedSlots = { ...(this.$scopedSlots || {}) }
    if (!this.expandedRowEnabled) {
      delete forwardedScopedSlots.expandedRowRender
    }
    const table = (
      <a-table
        {...{ props, scopedSlots: forwardedScopedSlots }}
        onChange={this.loadData}
        onExpand={(expanded, record) => this.onExpand(expanded, record)}
      >
        {Object.keys(this.$slots).map(name => (
          <template slot={name}>{this.$slots[name]}</template>
        ))}
      </a-table>
    )
    return (
      <div class="table-wrapper">
        {showAlert && this.showSelected && this.selectRowMode === 'default' ? this.renderAlert() : null}
        {table}
        {!this.hidePagination ? pagination : null}
      </div>
    )
  }
}

// 添加自定义分页样式
const customPaginationStyles = `
<style>
.custom-pagination-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.custom-pagination-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  color: #5D5C5C;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.custom-pagination-btn:hover {
  border-color: #0057FE;
  color: #0057FE;
}

.custom-pagination-btn.active {
  background: #0057FE;
  border-color: #0057FE;
  color: #fff;
}

.custom-pagination-btn.disabled {
  background: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
  cursor: not-allowed;
}

.custom-pagination-btn.disabled:hover {
  border-color: #d9d9d9;
  color: #bfbfbf;
}

.custom-pagination-info {
  margin-left: 16px;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}

/* 自定义图标与旋转方向 */
.custom-pagination-icon {
  display: inline-block;
  line-height: 1;
  transform-origin: center;
}
.icon-rotate-left {
  transform: rotate(90deg);
}
.icon-rotate-right {
  transform: rotate(-90deg);
}
</style>
`

// 将样式注入到页面
if (typeof document !== 'undefined') {
  const styleId = 'custom-pagination-styles'
  if (!document.getElementById(styleId)) {
    const styleElement = document.createElement('style')
    styleElement.id = styleId
    styleElement.textContent = customPaginationStyles.replace('<style>', '').replace('</style>', '')
    document.head.appendChild(styleElement)
  }
}
