<template>
  <div class="component-table-render">
    <el-table ref="tableRender" v-bind="config.table" :class="className" :border="border" :data="data" :max-height="maxHeight">
      <el-table-column v-for="(column, index) in schema" :key="index" show-overflow-tooltip v-bind="column">
        <template slot-scope="scope">
          <slot v-if="column.slotRender" :name="column.slotRender" v-bind="scope" />
          <span v-else>{{ (scope.column.property === 'index' || scope.column.type === 'index') ? (scope.$index + 1) : (column.valueFormatter ? column.valueFormatter(scope.row) : scope.row[column.prop]) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="pagination.total > 0"
      v-bind="config.pagination"
      :total="pagination.total"
      :current-page="pagination.currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
export const DEFAULT_PAGINATION = {
  pageSizes: [10, 20, 50],
  layout: 'total, prev, pager, next, sizes'
}

export default {
  name: 'TableRender',
  props: {
    config: {
      type: Object,
      default: () => ({
        table: {},
        pagination: DEFAULT_PAGINATION
      })
    },
    schema: {
      type: Array,
      default: () => ([])
    },
    border: {
      type: Boolean,
      default: false
    },
    className: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => ([])
    },
    pagination: {
      type: Object,
      default: () => ({
        total: 0,
        currentPage: 1,
        pageSize: 10
      })
    },
    maxHeight: {
      type: [String, Number],
      default: 'auto'
    }
  },
  methods: {
    /**
     * 当分页大小发生变化时
     * @param pageSize 当前分页大小
     */
    handleSizeChange(pageSize) {
      this.$emit('size-change', pageSize)
    },

    /**
     * 当页码发生变化时
     * @param page 当前页码
     */
    handleCurrentChange(page) {
      this.$emit('current-change', page)
    }
  }
}
</script>
