<template>
  <div :class="{'hidden':hidden}"
       class="pagination-container">
    <!-- :background="background" -->
    <el-pagination :current-page.sync="currentPage"
                   :page-size.sync="pageSize"
                   :layout="layout"
                   :page-sizes="pageSizes"
                   :total="total"
                   v-bind="$attrs"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" />
  </div>
</template>

<script>
import { scrollTo } from '@/utils/scroll-to'
import { Searchs } from '@/helpers'
export default {
  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
    }
  },
  computed: {
    currentPage: {
      get () {
        return this.page
      },
      set (val) {
        this.$emit('update:page', val)
      }
    },
    pageSize: {
      get () {
        return this.limit
      },
      set (val) {
        this.$emit('update:limit', val)
      }
    }
  },
  watch: {
    currentPage() {
      this.syncStore()
    },
    pageSize() {
      this.syncStore()
    }
  },
  mounted() {
    if (this.sync) {
      const searchs = new Searchs(this.$route.path)
      const active = searchs.get()
      if (active && active.page) {
        for (const key in active.page) {
          if (active.page.hasOwnProperty(key)) {
            const item = active.page[key]
            this.$emit('update:' + key, item)
          }
        }
      }
    }
  },
  methods: {
    syncStore() {
      if (this.sync) {
        const searchs = new Searchs(this.$route.path)
        searchs.update(this._props, undefined, 'page')
      }
    },
    handleSizeChange (val) {
      this.$emit('pagination', { page: this.currentPage, limit: val })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
      this.syncStore()
    },
    handleCurrentChange (val) {
      this.$emit('pagination', { page: val, limit: this.pageSize })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
      this.syncStore()
    }
  }
}
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.pagination-container.hidden {
  display: none;
}
</style>
