<template>
  <div class="common-table">
    <slot name="Header"></slot>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="data"
      v-bind="$attrs"
      class="mb20"
      border
      v-on="$listeners"
      @selection-change="handleSelectionChange"
      @cell-click="tabClick"
    >
      <template v-for="(column,index) in finalColumns">
        <el-table-column v-if="$scopedSlots[column.prop]"  v-bind="column" :key="column.prop">
          <template #default="scope">
            <slot :name="column.prop" v-bind="scope"></slot>
          </template>
        </el-table-column>
        <BaseColumn  :key="index" v-else :column="column" />
      </template>
    </el-table>

    <BasePagination :pagination="pagination" @change="handleChange" />
  </div>
</template>

<script>
import BaseColumn from './column'
import BasePagination from './pagination'

const defaultColumnOption = {
  align: 'left',
  showOverflowTooltip: true,
}

export default {
  name: 'BaseTable',
  components: {
    BaseColumn,
    BasePagination,
  },
  inheritAttrs: false,
  props: {
    data: Array,
    columns: Array,
    onChange: Function,
    columnOptions: Object,
    loading: {
      type: Boolean,
      default: false,
    },
    pagination: {
      type: [Object, Boolean],
      default: () => ({}),
    },
  },
  computed: {
    finalColumns() {
      const { columnOptions, columns } = this

      return columns.map(column => ({
        ...defaultColumnOption,
        ...columnOptions,
        ...column,
      }))
    },
  },
  methods: {
    handleChange(pagination) {
      if (this.onChange) {
        this.onChange(pagination)
      }

      this.$emit('change', pagination)
    },
    handleSelectionChange(val) {
      this.$emit('selectChange', val)
    },
    tabClick(row, column, cell) {
      this.$emit('tabClick', row, column, cell)
    },
    clearSelection() {
      this.$refs.multipleTable.clearSelection()
    },
  },
}
</script>

<style lang="less" scoped>
.common-table {
  .mb20 {
    margin-bottom: 20px;
  }
}
</style>
