import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { rouletteAlgorithm } from '@/utils'
import './index.scss'

export default class Lottery extends Component {
  // 对prop传值进行限制
  static propTypes = {
    history: PropTypes.object,
    route: PropTypes.object,
    routes: PropTypes.array
  }
  constructor(props) {
    super(props)
    this.state = {
      lotteryTimes: 10, // 可抽奖次数，默认10次
      isRotate: false,
      transform: '',
      transition: '',
      gifts: [
        { 
          start: 0,
          end: 90,
          tips: '谢谢参与',
          weight: 50 // 权重值，值越大，该奖品中奖概率就越大
        },
        {
          start: 91,
          end: 180,
          tips: '三等奖',
          weight: 3
        },
        {
          start: 271,
          end: 360,
          tips: '一等奖',
          weight: 1
        },
        {
          start: 181,
          end: 270,
          tips: '二等奖',
          weight: 3
        }
      ]
    }
  }
  lottery = () => {
    if (this.state.lotteryTimes <= 0) return alert('您当前暂无抽奖机会！')
    if (this.state.isRotate) return
    const lotteryTimes = this.state.lotteryTimes - 1
    const gifts = this.state.gifts
    // 获取中奖的索引
    const _bounsIndex = rouletteAlgorithm(this.state.gifts)
    console.log(_bounsIndex, '中奖索引', gifts[_bounsIndex].tips)
    const start = gifts[_bounsIndex].start
    const end = gifts[_bounsIndex].end
    // 随机生成一个在中奖奖品的start和end区间数
    let deg = Math.floor(Math.random()*(end - start) + start)
    console.log(deg, 'deg')
    this.setState({
      lotteryTimes,
      isRotate: true,
      transform: `rotate(${360 * 3 * (10 - lotteryTimes) + deg}deg)`,
      transition: 'all 4s ease-in-out'
    })
    setTimeout(()=>{
      alert(gifts[_bounsIndex].tips)
      this.setState({
        isRotate: false,
        transition: 'none'
      })
    }, 4500)
  }
  toGift = () => {
    this.props.history.push({ pathname: '/gift' })
  }
  render() {
    return (
      <div className="lottery">
        <div className="lottery-times">可免费抽奖{this.state.lotteryTimes}次</div>
        <div className="lottery-layer">
          <div style={{transform: this.state.transform, transition: this.state.transition}} className="lottery-layer-plate" />
          <div className="lottery-layer-pointer" onClick={this.lottery} />
        </div>
        <div className="lottery-gift" onClick={this.toGift}>查看我的奖品</div>
      </div>
    )
  }
}