'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import './drawpage.less';
import API from '@src/api';
import { _asyncThrottle, _throttle } from '@src/utils/utils';
import modalStore from '@src/store/modal';
import store from '@src/store';
import { CHANNEL_PARAMS, PAGE_MAP } from '@src/utils/constants';
import { CircleTurntable } from '@spark/circle-turntable'
import { Button } from '@src/components/Button';
import { Marquee, Toast } from '@spark/ui';
import { isWeChat } from '@src/utils/share';
import { LOG_KEY, pageView, sensorLog } from '@src/utils/sensors';

@observer
class Drawpage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      drawInfo: {}
    }
    this.btnStarting = false  // 转盘是否启动
    this.turntableRef = null  // 大转盘
    this.drawResultInfo = {}
  }

  componentDidMount() {
    this.getDrawInfo()
    pageView("b12842", {
      page_name: "抽奖大转盘",
    });
    sensorLog(LOG_KEY.exposure, "b12842", "d12843", {
      page_name: "抽奖大转盘",
      button_name: "立即抽奖按钮",
    });
    sensorLog(LOG_KEY.exposure, "b12842", "d12844", {
      page_name: "抽奖大转盘",
      button_name: "做任务，赚次数按钮",
    });
    sensorLog(LOG_KEY.exposure, "b12842", "d12845", {
      page_name: "抽奖大转盘",
      button_name: "返回按钮",
    });
  }

  /** 获取转盘信息 */
  getDrawInfo = async () => {
    const { success, data } = await API.drawIndex()
    if (success && data) {
      this.setState({
        drawInfo: data || {}
      })
    }
  }

  // 开始抽奖
  lottteryHandle = _asyncThrottle(async () => {
    sensorLog(LOG_KEY.click, "b12842", "d12843", {
      page_name: "抽奖大转盘",
      button_name: "立即抽奖按钮",
    });
    // 微信端拦截
    if (isWeChat()) {
      // 友客小程序
      if (CFG.channel == CHANNEL_PARAMS.YK_MINI) {
        return Toast("请前往人保寿险管家app活动抽奖～")
      }
      // 其他微信端 提醒唤端弹窗
      else {
        return modalStore.pushPop("CodePop")
      }
    }

    const { prizeVOs, remainDrawTimes } = this.state.drawInfo
    // 抽奖次数为0
    if (!remainDrawTimes) {
      return Toast("抽奖次数不足，快去做任务赚次数吧～")
    }

    if (this.btnStarting) return false
    this.btnStarting = true
    const { success, data } = await API.drawJoin()
    if (success && data) {
      // 转盘转动开始抽奖
      this.turntableRef.launch()
      this.drawResultInfo = data || {}

      // 转盘停止转动，指针停在index
      const index = prizeVOs?.findIndex(item => item.prizeId === (this.drawResultInfo.prizeId || 'thanks'))
      console.info('index', index)
      this.turntableRef.braking(index);
    } else {
      this.btnStarting = false
      this.getDrawInfo()
    }
  })

  // 转盘停止处理
  stopOkHandle = () => {
    this.btnStarting = false

    if (!this.drawResultInfo?.prizeId) {
      modalStore.pushPop("NoPrizeCard", { data: this.drawResultInfo })
    } else {
      modalStore.pushPop("Pop_winprize", { data: this.drawResultInfo })
    }
    this.getDrawInfo()
  }

  /** 返回 */
  backHome = _throttle(() => {
    sensorLog(LOG_KEY.click, "b12842", "d12845", {
      page_name: "抽奖大转盘",
      button_name: "返回按钮",
    });
    if (this.btnStarting) return false
    store.changePage(PAGE_MAP.HOME_PAGE)
  })

  goTask = _throttle(() => {
    sensorLog(LOG_KEY.click, "b12842", "d12844", {
      page_name: "抽奖大转盘",
      button_name: "做任务，赚次数按钮",
    });

    if (this.btnStarting) return false
    modalStore.pushPop("Taskpop", { onClose: () => this.getDrawInfo() })
  })

  render() {
    const { prizeVOs, remainDrawTimes } = this.state.drawInfo
    return (
      <div className="drawpage modal_center">
        <span className="bg"></span>
        <Button className="back_btn md19" onClick={this.backHome} />
        <Button className="task_btn md21" onClick={this.goTask} />
        <Button className="draw_btn_box md20" onClick={this.lottteryHandle}>
          <span className="draw_btn"></span>
          <span className="left_num">剩余次数：{remainDrawTimes || 0}</span>
        </Button>
        <div className="turantable">
          <CircleTurntable
            className="turantable_box"
            ref={ref => this.turntableRef = ref}
            options={prizeVOs || []}
            angleOffset={30}  // 角度偏移量
            radian={100}  // 奖项半径
            launchDuration={1000}  // 启动时间
            // 大转盘背景
            renderBackground={<div className="turantable_bg"></div>}
            // 大转盘指针
            renderStartButton={<></>}
            // 渲染奖品信息
            renderOption={(option) => {
              return <div className="prize_item">
                <div className="prize_name">{option.prizeName}</div>
                <img className="prize_img"
                  src={option.prizeImg}
                  alt="" />
              </div>
            }}
            didStop={this.stopOkHandle}
          />
          <span className="pointer"></span>
        </div>
        <span className="cover"></span>
      </div>
    );
  }
}
export default Drawpage;
