"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 { PAGE_MAP } from "@src/utils/constants";
import { CircleTurntable } from "@spark/circle-turntable";
import { pageLeave, sensorMdClick, sensorMdExpouse } from "@src/utils/sensorMd";
import { Button } from "@src/components/Button";
import { Toast } from "@spark/ui";

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

  async componentDidMount() {
    await this.getDrawInfo();
    sensorMdExpouse("activityPage", { pageName: "抽奖页", follow_action: this.props?.is_from == "result" ? 4 : 2 });
    pageLeave("抽奖页", 5);
  }

  /** 获取转盘信息 */
  getDrawInfo = async () => {
    const { success, data } = await API.drawIndex();
    if (success && data) {
      this.setState({
        drawInfo: {
          ...data,
          optionInfoList: data.optionInfoList?.map((item) => ({
            ...item,
            prizeName: item.name,
            prizeImg: item.icon
          })),
        },
      });
    }
  };

  // 开始抽奖
  lotteryHandle = _asyncThrottle(async () => {
    const { optionInfoList, leftDrawTimes } = this.state.drawInfo;
    sensorMdClick("activityClick", { pageName: "抽奖页", buttonName: "立即抽奖" });
    // 无抽奖次数
    if (!leftDrawTimes) {
      // return modalStore.pushPop("Drawchancepop", {
      //   refresh: () => this.getDrawInfo(),
      // });
      Toast("去参与游戏获取抽奖次数吧～");
      return;
    }

    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 = optionInfoList?.findIndex((item) => item.prizeId === this.drawResultInfo.prizeId);
      console.info("index", index);
      // !important 注意：randomOffset设置为false，这样每次旋转的偏移量就不是随机滴啦
      this.turntableRef.braking(index, { immediately: false, randomOffset: false });
    } else {
      this.btnStarting = false;
      this.getDrawInfo();
    }
  });

  // 转盘停止处理
  stopOkHandle = () => {
    this.btnStarting = false;
    console.info("this.drawResultInfo", this.drawResultInfo);

    if (this.drawResultInfo?.prize?.prizeId == "thanks") {
      modalStore.pushPop("Drawfailpop");
    } else {
      modalStore.pushPop("Drawsucpop", { ...this.drawResultInfo });
    }
    this.getDrawInfo();
  };

  /** 返回 */
  backHome = _throttle(() => {
    if (this.btnStarting) return false;
    store.changePage(PAGE_MAP.HOME_PAGE);
  });

  /** 奖品 */
  prizeHandle = _throttle(async () => {
    if (this.btnStarting) return false;
    if (!store.checkActStatus(true)) return;
    sensorMdClick("activityClick", { pageName: "抽奖页", buttonName: "奖品" });
    location.href = CFG.prize;
  });

  /** 规则 */
  ruleHandle = _throttle(async () => {
    if (this.btnStarting) return false;
    if (!store.checkActStatus(true)) return;
    sensorMdClick("activityClick", { pageName: "抽奖页", buttonName: "规则" });
    modalStore.pushPop("Rulepop");
  });
  /** 任务 */
  taskHandle = _throttle(() => {
    if (this.btnStarting) return false;
    if (!store.checkActStatus()) return;
    sensorMdClick("activityClick", { pageName: "抽奖页", buttonName: "做任务" });
    modalStore.pushPop("Taskpop", {
      refresh: () => this.getDrawInfo(),
    });
  });
  render() {
    const { optionInfoList, leftDrawTimes } = this.state.drawInfo;
    return (
      <div className="drawpage modal_center">
        <span className="beiJing"></span>
        <span className="logo"></span>
        <div className="rule_prize"></div>
        <span className="title"></span>
        <div className="turntable">
          <span className="turntable_box_bg"></span>
          <CircleTurntable
            className="turntable_box"
            ref={(ref) => (this.turntableRef = ref)}
            options={optionInfoList || []}
            angleOffset={23} // 角度偏移量
            radian={80} // 奖项半径
            launchDuration={1000} // 启动时间
            brakingDuration={0}
            maxSpeed={18}
            // 大转盘背景
            renderBackground={<div className="turntable_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>
          <span className="arrow"></span>
          {/* <span className="cloud"></span> */}
        </div>
        <Button className="back" onClick={this.backHome} />
        <Button className="rule_btn" onClick={this.ruleHandle}></Button>
        <Button className="prize_btn" onClick={this.prizeHandle}></Button>
        <Button className="task_btn md20" onClick={this.taskHandle}></Button>
        <div className="draw_btn md19" onClick={this.lotteryHandle}></div>
        <span className="left_num">剩余次数：{leftDrawTimes || 0}</span>
      </div>
    );
  }
}
export default Drawpage;
