import React, { Component } from 'react'
import { http } from "@/utils"
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'
import './bullet-screen.scss'

class UserBulletScreen extends Component {

  swiper

  state = {
    bulletScreenData: []
  }

  componentDidMount() {
    this.getBulletScreenData(true)
  }

  componentWillUnmount() {
    this.swiper && this.swiper.destroy()
  }


  initializeBulletScreen = () => {
    const _this = this
    const slidesPerRequest = 20
    const indexArray = [...Array(slidesPerRequest - 1).keys()]
    let removed = false
    this.swiper = new Swiper('.swiper-container', {
      direction: 'vertical',
      allowTouchMove: false,
      autoplay: true,
      on: {
        transitionEnd() {
          if (this.slides.length > slidesPerRequest) {
            this.removeSlide(0)
            this.autoplay.start()
          }
          if (this.activeIndex === this.slides.length - 1 && !removed) {
            this.autoplay.stop()
            _this.getBulletScreenData().then(res => {
              removed = true
              this.removeSlide(indexArray)
              this.appendSlide(_this.getSlides(res))
              setTimeout(() => {
                this.autoplay.start()
                removed = false
              })
            })
          }
        }
      }
    })
  }

  getSlides = list => list.map(item => {
    return `
              <li class="swiper-slide">
                <img class="avatar" src="${item.avatar_file}" alt="">
                <span>${item.user_name} ${item.msg}</span>
              </li>
            `
  })

  getBulletScreenData = (initializeSwiper = false) => {
    return http.get(`${API.home}/sys/barrage_data`)
      .then(res => {
        const {data, code} = res.data
        if (code == 200) {
          if (initializeSwiper) {
            this.setState({
              bulletScreenData: data
            }, () => {
              this.initializeBulletScreen()
            })
          } else {
            return data
          }
        }
      })
  }


  render() {
    const {bulletScreenData} = this.state
    return (
      <div id="user-bullet-screen" className='swiper-container'>
        <ul className='swiper-wrapper'>
          {
            bulletScreenData.length && bulletScreenData.map((item, index) => {
              return (
                <li className='swiper-slide' key={index}>
                  <img src={item['avatar_file']}
                       alt="" className="avatar"/>
                  <span>{item.user_name} {item.msg}</span>
                </li>
              )
            })
          }
        </ul>
      </div>
    )
  }
}

export default UserBulletScreen
