"use strict";

import React from "react";
import { observer } from "mobx-react";
import "./DrawPage.less";
import { _asyncThrottle, _throttle } from "../../utils/utils.ts";
import store from "../../store/store.ts";
import { CHANNEL_PARAMS } from "../../utils/constants.ts";
import { CircleTurntable } from "@spark/circle-turntable";
import { isWeiXin } from "../../AppTools.ts";
import API from "../../api/index.ts";
import { Button, Toast } from "@grace/ui";
import { PageCtrl } from "@/core/ctrls/PageCtrl";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl";
import { SvgaPlayer } from "@grace/svgaplayer";
import Homepage from "../HomePage/HomePage.tsx";

import machineSvga from "../../assets/svga/1输出扭蛋机常态.svga";
import normalSvga from "../../assets/svga/2输出待机啊.svga";
import dynamicSvga from "../../assets/svga/3输出出奖啊.svga";

// import { LOG_KEY, pageView, sensorLog } from '@src/utils/sensors';


@observer
class Drawpage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      drawInfo: {},
      btnDynamic: false, // 抽奖机是否动态中
    };
    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 (isWeiXin()) {
      // 友客小程序
      if (CFG.channel == CHANNEL_PARAMS.YK_MINI) {
        return Toast.show("请前往人保寿险管家app活动抽奖～");
      }
      // 其他微信端 提醒唤端弹窗
      else {
        // return modalStore.pushPop("CodePop");  //TODO
      }
    }

    const { prizeVOs, remainDrawTimes } = this.state.drawInfo;

    // 抽奖次数为0
    if (!remainDrawTimes) {
      return Toast.show("抽奖次数不足，快去做任务赚次数吧～");
    }

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

      const index = prizeVOs?.findIndex(
        (item) => item.prizeId === (this.drawResultInfo.prizeId || "thanks")
      );
      console.info("index", index);
      // 抽奖机停止转动
      setTimeout(() => {
        this.setState({ btnDynamic: false });
        this.stopOkHandle();
      }, 2000);
      // 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)
    PageCtrl.changePage(Homepage);
  });

  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 { btnDynamic } = this.state;
    const { prizeVOs, remainDrawTimes } = this.state.drawInfo;
    return (
      <div className="drawpage modal_center">
        <span className="bg"></span>
        <span className="logo"></span>
        <Button className="back_btn" onClick={this.backHome} />
        {/* <Button className="task_btn" onClick={this.goTask} /> */}
        <Button className="draw_btn_box" onClick={this.lottteryHandle}>
          <span className="draw_btn"></span>
          <span className="left_num">剩余次数：{remainDrawTimes || 0}</span>
        </Button>
        {btnDynamic ? (
          <SvgaPlayer className="dynamic" src={dynamicSvga} />
        ) : (
          <SvgaPlayer className="normal" src={normalSvga} />
        )}
        <SvgaPlayer className="machine" src={machineSvga} />
        {/* <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;
