import React from 'react'
import styles from './index.module.css'

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

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 = ''} : PagingProps) {
  const clickHandle = (select: number) => current !== select && handleChange(select)
  const { min, max } = intercept(current, total, show)

  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}>{items}</div>
  )
}

export default Paging