<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"
    :rowClassName="() => canSelect? 'custom-table-row': ''"
    @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, Boolean]
    },
    selectedRowKeys: {
      type: Array
    },
    canSelect: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
        innerSelectedRowKeys: cloneDeep(this.selectedRowKeys) || []
    }
  },
  methods: {
    // 实现单击选中/反选功能
    customRow(record) {
      let _this = this
      return {
        class: _this.innerSelectedRowKeys.includes(record[_this.rowKey]) ? 'ant-table-row-selected' : '',
        on: {
          click: () => {
            if(!_this.canSelect) {
              return
            }
            if (_this.innerSelectedRowKeys.includes(record[_this.rowKey])) {
              _this.innerSelectedRowKeys = []
            } else {
              _this.innerSelectedRowKeys = [record[_this.rowKey]]
            }
            _this.$emit('update:selectedRowKeys', _this.innerSelectedRowKeys)
            _this.$emit("detail",record)
          }
        }
      }
    },
    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">
.custom-table-row {
  cursor: pointer;
}
</style>
