import React, { useState } from 'react'
import styles from './index.module.css'

interface PagingProps {
  current: number,
  total: number,
  handleChange: Function,
  show: number,
  className?: string,
  number: number
}

function intercept(current: number, maxT: number, dis: number, minT = 1) {
  let cdis = Math.floor(dis / 2)
  let min = current - cdis
  let max = current + cdis

  if (min < minT) {
    max = max + (minT - min)
    min = minT
  } else if (max > maxT) {
    min = min - (max - maxT)
    max = maxT
  }

  min = min < minT ? minT : min
  max = max > maxT ? maxT : max

  return { min, max }
}

function Paging({ current = 1, show = 5, total, handleChange, className = '', number} : PagingProps) {
  const { min, max } = intercept(current, total, show)
  const [val, setVal] = useState(current)
  const clickHandle = (select: number) => {
    if (select < min || select > max) {
      select = current
    }
    setVal(select)
    handleChange(select)
  }

  let items = []
  for (let i = min; i <= max; i++) {
    items.push(<span key={i} onClick={() => clickHandle(i)} className={i === current ? styles.active: ''}>{i}</span>)
  }

  return (
    <div className={styles.paginglayer + ' ' + className}>
      <div className={styles.info}>共{number}条</div>
      <span className='icon-angle-left' onClick={() => clickHandle(current - 1)}></span>
      {items}
      <span className='icon-angle-right' onClick={() => clickHandle(current + 1)}></span>
      <div className={styles.goto}>
        前往<input value={val} onChange={ev => setVal(Number(ev.target.value) || current)} onBlur={ev => clickHandle(Number(ev.target.value))} />页
      </div>
    </div>
  )
}

export default Paging