import React from "react";
import { observer } from "mobx-react";
import store from "@src/store";
import { _asyncThrottle, _throttle, dateFormatter, getUrlParam, prefixInteger, windowJumpUrl } from "@src/utils/utils";
import modalStore from "@src/store/modal";
import { PAGE_MAP } from "@src/utils/constants";
import { Button } from "@src/components/Button";
import "./userhomepage.less";
import "./rank.less";
import classNames from "classnames";
import { Swiper } from "antd-mobile";
import { SvgaPlayer } from "@spark/svgaplayer";
import { RES_PATH } from "../../../sparkrc";
import shareStore from "@src/store/share";
import musicStore from "@src/store/musicStore";
import MusicBtn from "@src/components/MusicBtn/MusicBtn";
import API from "@src/api";


@observer
class Userhomepage extends React.Component {

  state = {
    dNum: 0,
    hNum: 0,
    mNum: 0,
    sNum: 0
  };

  async componentDidMount() {

    await store.getHomeInfo();
    this.flushCD();
    shareStore.doAssist();

  }

  /** 规则按钮*/
  clickRule = () => {
    if (!store.checkActTime("rule")) return;
    modalStore.pushPop("RulePop");
  };

  /** 奖品按钮*/
  clickPrize = () => {
    if (!store.checkActTime("prize")) return;
    if (!store.setIndex?.privacy) {
      modalStore.pushPop("Yinsirulepop");
      return;
    }
    store.changePage(PAGE_MAP.PRIZE_PAGE);
  };

  /** 抽奖按钮*/
  clickDraw = () => {
    if (!store.checkActTime()) return;
    API.assistJoin();
    store.changePage(PAGE_MAP.DRAW_PAGE);
  };

  clickVisit = () => {
    if (!store.checkActTime()) return;
    windowJumpUrl(store.frontVariable?.SaleManUrl
      + "&actPlatforms=" + getUrlParam("actPlatforms")
      + "&agentCode=" + getUrlParam("agentCode")
      + "&actId=" + getUrlParam("actId")
      + "&channel=" + CFG.channel);
  };

  clickDetails = () => {
    if (!store.checkActTime()) return;
    store.changePage(PAGE_MAP.LIKE_LOG_PAGE);
  };

  clickInvite = () => {
    if (!store.checkActTime()) return;
    shareStore.doInvite();
    API.assistJoin();
  };

  clickShare = () => {
    if (!store.checkActTime()) return;
    shareStore.doShare();
  };

  getRankIndex = (index) => {
    if (index == -1 || !index) {
      return "未上榜";
    }

    return index;
  };


  interval = null;
  flushCD = () => {
    const { rankInfo, currentTimestamp } = store.setIndex;
    let diff = (rankInfo.openTime - currentTimestamp) / 1000;
    if (diff <= 0) {
      return;
    }

    const flush = () => {
      diff--;
      if (diff <= 0) {
        clearInterval(this.interval);
        store.getHomeInfo().then(() => this.flushCD());
        return;
      }
      const s = ~~diff;
      const m = s / 60 >> 0;
      const h = m / 60 >> 0;
      const d = h / 24 >> 0;

      this.setState({
        dNum: prefixInteger(d, 2),
        hNum: prefixInteger(h, 2),
        mNum: prefixInteger(m % 60, 2),
        sNum: prefixInteger(s % 60, 2)
      });
    };

    flush();
    this.interval = setInterval(flush, 1000);
  };

  render() {

    const { dNum, hNum, mNum, sNum } = this.state;

    const { userId, rankInfo = {}, actStartTimestamp, actEndTimestamp } = store.setIndex;

    const { openTime, rankInfos, myRank = {}, rankOptions = [] } = rankInfo;

    const sTxt = dateFormatter(actStartTimestamp, `yyyy年M月d日`);
    const eTxt = dateFormatter(actEndTimestamp, `yyyy年M月d日`);
    const eRTxt = dateFormatter(openTime, `yyyy.MM.dd`);

    return (
      <div className="HomePage">
        <div className="bg" />
        {/* <div className="title" /> */}
        <SvgaPlayer className="homeEffect" src={RES_PATH + "svga/3输出首页氛围.svga"} />
        <div className="logo" />
        <div className="subTitle">活动时间：{sTxt}-{eTxt}</div>
        <div className="uid">用户ID：{userId}</div>
        <div className="strategy" />
        <Button className="rule md5" onClick={this.clickRule} />
        <Button className="prize md6" onClick={this.clickPrize} />
        <Button className="inviteDetails md7" onClick={this.clickDetails} />

        <Button className="visitList md8" onClick={this.clickVisit}>
          <SvgaPlayer
            className="visitListSvga"
            src={RES_PATH + "svga/2输出拜访.svga"}
          />
        </Button>

        <Button className="shareBtn md9" onClick={this.clickShare}>
          <SvgaPlayer
            className="shareBtnSvga"
            src={RES_PATH + "svga/1输出分析好友.svga"}
          />
        </Button>

        <Button className="drawBtn md11" onClick={this.clickDraw}>
          <SvgaPlayer
            className="drawBtnSvga"
            src={RES_PATH + "svga/7输出抽奖.svga"}
          />
        </Button>
        <Button className="inviteBtn md10" onClick={this.clickInvite}>
          <div className="inviteBtnImg" />
        </Button>

        <MusicBtn className="musicBtn" />

        <div className="rankBg" style={{ borderWidth: "2px" }}>
          <div className="rankTop" style={{ left: 0, top: -2 }} />
          <div className="rankBgInner">
            <div className="rankTitle" />
            <div className="rankTip">截止{eRTxt}，累计邀请人数前100名可获得旅游基金</div>
            <div className="rankPrize">
              <div className="rankTime">
                <span>{dNum}</span>天<span>{hNum}</span>:<span>{mNum}</span>:<span>{sNum}</span>后结算奖励
              </div>
              <Swiper
                className="prizeList"
                slideSize={174 / 654 * 100}
                loop={true}
                autoplay={true}
                indicator={false}
              >
                {[
                  ...rankOptions,
                  ...rankOptions,
                  ...rankOptions,
                  ...rankOptions,
                  ...rankOptions
                ].map((item, index) => {
                    const bgId = index % rankOptions.length + 1;
                    return <Swiper.Item key={index} className={`prizeItem prizeBg${bgId}`}>
                      <img src={item.image} />
                      <div className="prizeName">{item.name}</div>
                      <div className="prizeRank">{item.ranking}</div>
                    </Swiper.Item>;
                  }
                )}
              </Swiper>
            </div>

            <div className="rankItem rankListTitle">
              <div className="rank">排名</div>
              <div className="nickName">用户昵称</div>
              <div className="inviteNum">累计邀请人数</div>
            </div>
            <div className="rankItem rankListItem">
              <div className="rank">{this.getRankIndex(myRank?.index)}</div>
              <div className="nickName">{myRank?.userName || ""}（我）</div>
              <div className="inviteNum">{myRank?.score || 0}</div>
              <div className="border" />
            </div>
            <div className="rankList">
              {rankInfos?.map((item, index) => {
                const rankCls = classNames("rank", {
                  rankIcon: item.index <= 3
                });
                const rank = item.index <= 3 ? "" : this.getRankIndex(item?.index);
                return <div className="rankItem rankListItem" key={index}>
                  <div className={rankCls}>{rank}</div>
                  <div className="nickName">{item?.userName}</div>
                  <div className="inviteNum">{item?.score || 0}</div>
                  <div className="border" />
                </div>;
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Userhomepage;
