import React, { useEffect, useRef, useState } from "react";
import './index.less'
import BScroll from 'better-scroll';
import Pullup from '@better-scroll/pull-up'

BScroll.use(Pullup)

const BetterList = () => {
  const [listData, setListData] = useState(Array(20).fill('1'))
  const [acti, setActi] = useState(-1)
  const btScrll = useRef()

  useEffect(() => {
    initBetterScroll()
  }, [])

  /** 初始化betterscroll */
  const initBetterScroll = () => {
    const wrapper = document.querySelector('.BetterList')
    const scroll = btScrll.current = new BScroll(wrapper, {
      scrollY: true,
      scrollX: false,
      click: true,
      pullUpLoad: true
    })
    scroll.on('pullingUp', handleReachBottom)
    scroll.openPullUp({})
  }

  useEffect(() => {
    btScrll.current.finishPullUp()
    refresh()
  }, [listData])

  /** 加载下一页 */
  const handleReachBottom = async () => {
    console.log(listData.push(...Array(10).fill('3')))
    const p = [...listData]
    setListData(p)
  }

  /** 重新计算betterscroll高度 */
  const refresh = () => {
    btScrll.current?.refresh?.()
  }

  const actList = (i) => {
    setActi(i)
    refresh()
  }

  return <div className='BetterList'>
    <div className='c-content'>
      {listData.map(((item, i) => {
        return <div className={i===acti?'act-i':''} key={'c-content' + i} onClick={() => actList(i)}>{i}点击展开</div>
      }))}
    </div>
  </div>
}

export default BetterList