"use strict";

import React from "react";
import { observer } from "mobx-react";
import "./CapsulePage.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 { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper";
import "swiper/css";
import Homepage from "../HomePage/HomePage.tsx";
import Prizepop from "../../components/prizepop/prizepop.jsx";
import NoPrizeCard from "../../components/NoPrizeCard/NoPrizeCard.jsx";

import machineSvga from "../../assets/svga/1输出扭蛋机常态.svga";
import normalSvga from "../../assets/svga/2输出待机啊.svga";
import dynamicSvga from "../../assets/svga/3输出出奖啊.svga";
import output1Svga from "../../assets/svga/4中奖扭蛋.svga";
import output2Svga from "../../assets/svga/5中奖弹窗.svga";

import { LOG_KEY, pageView, sensorLog } from "../../utils/sensors.js";

@observer
class Capsulepage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      drawInfo: {},
      btnDynamic: false, // 抽奖机是否动态中
      btnOutput: false, // 开扭蛋效果是否启动
    };
    this.btnStarting = false; // 抽奖机是否启动
    // this.turntableRef = null; // 大转盘
    // this.drawResultInfo = {};
  }

  componentDidMount() {
    this.getDrawInfo();
    pageView("b14280", {
      page_name: "抽奖页面",
    });
    sensorLog(LOG_KEY.exposure, "b14280", "d14281", {
      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, "b14280", "d14281", {
      page_name: "抽奖页面",
      button_name: "立即抽奖按钮",
    });
    // 微信端拦截
    if (isWeiXin()) {
      // 友客小程序
      if (CFG.channel == CHANNEL_PARAMS.YK_MINI) {
        return Toast.show("请前往人保寿险管家app活动抽奖～");
      }
      // 其他微信端 提醒唤端弹窗
      else {
        // return modalStore.pushPop("CodePop");  //TODO
      }
    }

    const { remainDrawTimes = 0 } = 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 {
        boolPrize = false,
        prizeInfo = {},
        productInfos = [],
      } = data || {};

      // const index = prizeVOs?.findIndex(
      //   (item) => item.prizeId === (this.drawResultInfo.prizeId || "thanks")
      // );
      // console.info("index", index);

      // 抽奖机停止转动
      setTimeout(() => {
        this.setState({ btnOutput: true });
      }, 1600);
      setTimeout(() => {
        this.setState({ btnDynamic: false });
        this.stopOkHandle(boolPrize, prizeInfo, productInfos);
      }, 2000);
      // this.turntableRef.braking(index);
    } else {
      this.btnStarting = false;
      this.getDrawInfo();
    }
  });

  // 抽奖停止处理
  stopOkHandle = (boolPrize, prizeInfo, productInfos) => {
    this.btnStarting = false;
    setTimeout(() => {
      this.setState({ btnOutput: false });
    }, 1600);

    // 此时判断是否中奖 true-中奖，取prizeInfo信息，false-为中奖，取productInfos
    if (boolPrize) {
      // 中奖
      setTimeout(() => {
        ModalCtrl.showModal(Prizepop, { prizeInfo });
      }, 1600);
    } else {
      // 没中奖
      setTimeout(() => {
        ModalCtrl.showModal(NoPrizeCard, { productInfos });
      }, 1600);
    }

    this.getDrawInfo();
  };

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

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

  render() {
    const { btnDynamic, btnOutput } = this.state;
    const { prizeInfo = [], remainDrawTimes = 0 } = this.state.drawInfo;
    console.log(prizeInfo);
    return (
      <div className="capsule">
        <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} />
        {btnOutput && (
          <>
            <span className="mengceng"></span>
            <SvgaPlayer className="output1" src={output1Svga} />
            <SvgaPlayer className="output2" src={output2Svga} />
          </>
        )}

        {/* 底部奖品轮播 */}
        <div className="bottomprize">
          <div className="prizeindex">
            <Swiper
              autoplay={{
                disableOnInteraction: false,
                delay: 300,
              }}
              modules={[Autoplay]}
              slidesPerView={3.6}
              loop={true}
              initialSlide={0}
              speed={1600}
              freeMode={true}
              freeModeSticy={true}
            >
              {prizeInfo?.map((item, index) => (
                <SwiperSlide key={index}>
                  <div className="psample">
                    <img className="psimg" src={item.prizeImg} alt={item.prizeName} />
                    <span className="psname">{item.prizeName}</span>
                  </div>
                </SwiperSlide>
                
              ))}
            </Swiper>
          </div>
        </div>
      </div>
    );
  }
}
export default Capsulepage;
