<template>
  <div class="uif-paginate clearfix">
    <div class="uif-paginate-content clearfix">
      <span class="uif-paginate-item" :class="{disabled: !hasPrev}" @click="hasPrev && change(value - 1)">上一页</span>
      <span v-if="value >= 5" class="uif-paginate-item" @click="change(1)">1</span>
      <span v-if="value >= 5" class="uif-paginate-item more">...</span>
      <template v-for="idx in center">
        <span :key="idx" class="uif-paginate-item" :class="{active: idx === value}" @click="change(idx)">{{idx}}</span>
      </template>
      <span v-if="value + 4 < max" class="uif-paginate-item more">...</span>
      <span v-if="value + 4 < max" class="uif-paginate-item" @click="change(max)">{{max}}</span>
      <span class="uif-paginate-item" :class="{disabled: !hasNext}" @click="hasNext && change(value + 1)">下一页</span>
      <span class="uif-paginate-text">共{{max}}页 转到</span>
      <u-input v-model="v" :number="0"></u-input>
      <span class="uif-paginate-text">页</span>
      <u-button @click="confirm">确定</u-button>
    </div>
  </div>
</template>
<script>
import UButton from '@uif/hq/src/components/button'
import UInput from '@uif/hq/src/components/input'
import {toNumber} from '@uif/hq/src/utils/format'
export default {
  name: 'u-paginate',
  components: {UButton, UInput},
  props: {
    // 当前页码
    value: {
      type: Number,
      default: 1
    },
    // 数据总数
    total: {
      type: Number,
      default: 0
    },
    // 每页条数
    size: {
      type: Number,
      default: 50
    }
  },
  data () {
    return {
      v: this.value
    }
  },
  computed: {
    max () {
      return Math.ceil(this.total / this.size) || 1
    },
    center () {
      const start = this.value - 3
      const items = []
      for (let i = 0; i < 8; i++) {
        const index = start + i
        if (index >= 1 && index <= this.max) {
          items.push(index)
        }
      }
      return items
    },
    hasPrev () {
      return this.value > 1
    },
    hasNext () {
      return this.value < this.max
    }
  },
  watch: {
    value (value) {
      this.v = value
    }
  },
  methods: {
    change (value) {
      this.$emit('input', value)
      this.$emit('change', value)
    },
    confirm () {
      this.v = Math.min(Math.max(toNumber(this.v), 1), this.max)
      this.change(this.v)
    }
  }
}
</script>
