<!-- 分页组件 -->
<template>
  <div :style="alignStyle">
    <el-pagination
      class="cus-pagination"
      background
      prev-text="上一页"
      next-text="下一页"
      size="small"
      :pager-count="pagerCount"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page="pagination.currentPage"
      :page-sizes="pageSizes"
      :page-size="pagination.pageSize"
      :layout="layout"
      :total="pagination.totals"
    >
      <slot v-if="$slots.default"></slot>
      <span v-else class="el-pagination__total">总共 {{ pagination.totals }} 条，{{ Math.ceil(pagination.totals / pagination.pageSize) }} 页</span>
    </el-pagination>
  </div>
</template>

<script>
/*
  pagination: {
    currentPage: 1,
    pageSize: 20,
    totals: 0
  }
*/
export default {
  name: 'SyPaging',
  props: {
    align: {
      type: String,
      default: 'right',
      validator: function (value) {
        return ['left', 'center', 'right'].indexOf(value) !== -1
      }
    },
    layout: {
      type: String,
      default: 'slot, prev, pager, next, sizes, jumper'
    },
    pagination: {
      type: Object,
      required: true
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 50, 100, 200]
      }
    },
    pagerCount: {
      type: Number,
      default: 7
    }
  },
  computed: {
    alignStyle() {
      return {
        'text-align': this.align
      }
    }
  },
  methods: {
    // 每页数量发生改变
    handleSizeChange(val) {
      const { currentPage, totals } = this.pagination
      const maxNum = Math.ceil(totals / val)
      this.pagination.currentPage = maxNum < currentPage ? maxNum : currentPage
      this.pagination.pageSize = val
      this.handleChange('pageSize')
    },
    // 页码发生改变
    handlePageChange(val) {
      this.pagination.currentPage = val
      this.handleChange('currentPage')
    },

    handleChange(type) {
      const { currentPage, pageSize } = this.pagination
      this.$emit('change', { currentPage, pageSize }, type)
    }
  }
}
</script>
