<template>
  <a-table
   class="custom-table"
    v-bind="$attrs"
    :data-source="list"
    :columns="columns"
    :size="size"
    :row-key="rowKey"
    :loading="loading"
    :pagination="pagination"
    :customRow="customRow"
    @change="handleTableChange"
  >
    <!-- 处理 scopedSlots -->
    <template v-for="slotName of scopedSlotsKeys" :slot="slotName" slot-scope="text, record, index">
      <slot :name="slotName" :text="text" :record="record" :index="index"></slot>
    </template>
  </a-table>
</template>
<script>
import {cloneDeep} from 'lodash'
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    },
    size: {
      type: String,
      default: 'middle'
    },
    rowKey: {
      type: String,
      default: 'id'
    },
    loading: {
      type: Boolean
    },
    pagination: {
      type: Object
    },
    selectedRowKeys: {
      type: Array
    }
  },
  data() {
    return {
        innerSelectedRowKeys: cloneDeep(this.selectedRowKeys)
    }
  },
  methods: {
    // 实现单击选中/反选功能
    customRow(record) {
      return {
        class: this.innerSelectedRowKeys.includes(record[this.rowKey]) ? 'ant-table-row-selected' : '',
        on: {
          click: () => {
            if (this.innerSelectedRowKeys.includes(record[this.rowKey])) {
              this.innerSelectedRowKeys = []
            } else {
              this.innerSelectedRowKeys = [record[this.rowKey]]
            }
            this.$emit('update:selectedRowKeys', this.innerSelectedRowKeys)
          }
        }
      }
    },
    handleTableChange(pagination, filters, sorter) {
      this.$emit('change', pagination, filters, sorter)
    }
  },
  watch: {
    selectedRowKeys () {
        this.innerSelectedRowKeys = cloneDeep(this.selectedRowKeys)
    }
  },
  computed: {
    scopedSlotsKeys() {
      return Object.keys(this.$scopedSlots)
    }
  }
}
</script>
<style lang="less" scoped>
.custom-table {
  ::v-deep {
    .ant-table-row {
      cursor: pointer;
    }
  }
}
</style>
