<template>
  <div :class="{ hidden: hidden }" class="pagination-container">
    <el-pagination
      v-model:current-page="myCurrentPage"
      size="mini"
      :page-sizes="pageSizes"
      v-model:page-size="myLimit"
      :layout="layout"
      :total="total"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue'

export default defineComponent({
  name: 'pagination',
  props: {
    total: {
      required: true,
      type: Number
    },
    page: {
      type: Number,
      default: 1
    },
    limit: {
      type: Number,
      default: 10
    },
    pageSizes: {
      type: Array,
      default: () => {
        return [10, 20, 30, 50]
      }
    },
    layout: {
      type: String,
      default: 'total,sizes,prev, pager, next, jumper'
    },
    background: {
      type: Boolean,
      default: true
    },
    autoScroll: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    },
    sync: {
      type: Boolean,
      default: false
    },
    saveKey: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    let myCurrentPage = computed({
      get() {
        return props.page
      },
      set(val) {
        emit('update:page', val)
      }
    })

    let myLimit = computed({
      get() {
        return props.limit
      },
      set(val) {
        emit('update:limit', val)
      }
    })

    // 赋值回显
    const handleSizeChange = (val: any) => {
      emit('update:page', 1)
      emit('pagination', { page: myCurrentPage, limit: val })
      if (props.autoScroll) {
        scrollTo(0, 800)
      }
    }
    // 设置当前页
    const handleCurrentChange = (val: any) => {
      emit('pagination', { page: val, limit: myLimit })
      if (props.autoScroll) {
        scrollTo(0, 800)
      }
    }
    return {
      myCurrentPage,
      myLimit,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>
<style scoped lang="scss">
.pagination-container {
  background: #fff;
  padding: 32px 16px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.pagination-container.hidden {
  display: none;
}
</style>
