<template>
  <div class="uif-paging clearfix">
    <span class="uif-paging-item" :class="{disabled: !hasPrev}" @click="hasPrev && change(value - 1)">
      <u-icon type="chevron-l-left"></u-icon>
    </span>
    <template v-for="(data, idx) in center">
      <span v-if="data === -1" :key="idx" class="uif-paging-text">...</span>
      <span v-else :key="idx" class="uif-paging-item" :class="{active: data === value}" @click="change(data)">{{data}}</span>
    </template>
    <span class="uif-paging-item" :class="{disabled: !hasNext}" @click="hasNext && change(value + 1)">
      <u-icon type="chevron-l-right"></u-icon>
    </span>
    <span class="uif-paging-text right">跳至</span>
    <u-input v-model="v" :number="0"></u-input>
    <span class="uif-paging-text left">页</span>
    <u-button @click="confirm">跳转</u-button>
  </div>
</template>
<script>
import UButton from '@uif/hq/src/components/button'
import UInput from '@uif/hq/src/components/input'
import UIcon from '@uif/hq/src/components/icon'
import {toNumber} from '@uif/hq/src/utils/format'
import {map} from '@uif/hq/src/utils/array'
export default {
  name: 'u-paging',
  components: {UButton, UInput, UIcon},
  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 five = []
      for (let i = 1; i <= this.max; i++) {
        five.push({value: i, abs: Math.abs(i - this.value)})
      }
      five.sort((a, b) => a.abs - b.abs)
      if (five.length > 5) five.length = 5
      five.sort((a, b) => a.value - b.value)
      const data = map(five, data => data.value)
      const start = data[0]
      if (start > 2) {
        data.unshift(-1)
      }
      if (start >= 2) {
        data.unshift(1)
      }
      const end = data[data.length - 1]
      if (end < this.max - 1) {
        data.push(-1)
      }
      if (end <= this.max - 1) {
        data.push(this.max)
      }
      return data
    },
    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>
