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";
import { isWeChat } from "@src/utils/share";
import { LOG_KEY, MatterShareOpt, MatterViewDuration, MatterViewOpt, pageView, sensorLog } from "@src/utils/sensors";
import { accessLog } from "duiba-utils";


@observer
class Userhomepage extends React.Component {

  state = {
    dNum: "00",
    hNum: "00",
    mNum: "00",
    sNum: "00"
  };

  async componentDidMount() {
    this.startTime = +new Date();

    MatterViewOpt("b12833", {
      page_name: "活动首页",
    });

    sensorLog(LOG_KEY.exposure, "b12833", "d12838", {
      button_name: "邀请好友助力按钮",
      page_name: "活动首页",
    });
    sensorLog(LOG_KEY.exposure, "b12833", "d12837", {
      button_name: "抽奖按钮",
      page_name: "活动首页",
    });
    sensorLog(LOG_KEY.exposure, "b12833", "d12836", {
      button_name: "邀请明细按钮",
      page_name: "活动首页",
    });
    sensorLog(LOG_KEY.exposure, "b12833", "d12835", {
      button_name: "奖品按钮",
      page_name: "活动首页",
    });
    sensorLog(LOG_KEY.exposure, "b12833", "d12834", {
      button_name: "规则按钮",
      page_name: "活动首页",
    });

    if (isWeChat()) {
      if (!await store.checkBindStatus()) return;
    }
    // modalStore.pushPop("AssistSucPanel");

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

  }

  componentWillUnmount() {
    MatterViewDuration("b12833", +new Date() - this.startTime,{
      page_name: "活动首页",
    });
  }

  /** 规则按钮*/
  clickRule = () => {
    accessLog("502", {
      from: CFG.channel
    });
    sensorLog(LOG_KEY.click, "b12833", "d12834", {
      button_name: "规则按钮",
      page_name: "活动首页",
    });
    if (!store.checkActTime("rule")) return;
    modalStore.pushPop("RulePop");
  };

  /** 奖品按钮*/
  clickPrize = () => {
    accessLog("502", {
      from: CFG.channel
    });
    sensorLog(LOG_KEY.click, "b12833", "d12835", {
      button_name: "奖品按钮",
      page_name: "活动首页",
    });
    if (!store.checkActTime("prize")) return;
    if (!store.setIndex?.privacy) {
      modalStore.pushPop("Yinsirulepop");
      return;
    }
    store.changePage(PAGE_MAP.PRIZE_PAGE);
  };

  /** 抽奖按钮*/
  clickDraw = () => {
    accessLog("502", {
      from: CFG.channel
    });
    sensorLog(LOG_KEY.click, "b12833", "d12837", {
      button_name: "抽奖按钮",
      page_name: "活动首页",
    });
    if (!store.checkActTime()) return;
    API.assistJoin();
    store.changePage(PAGE_MAP.DRAW_PAGE);
  };

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

  clickDetails = () => {
    accessLog("502", {
      from: CFG.channel
    });
    sensorLog(LOG_KEY.click, "b12833", "d12836", {
      button_name: "邀请明细按钮",
      page_name: "活动首页",
    });
    if (!store.checkActTime()) return;
    store.changePage(PAGE_MAP.LIKE_LOG_PAGE);
  };

  clickInvite = () => {
    accessLog("502", {
      from: CFG.channel
    });
    MatterShareOpt("b12833", "d12838", {
      button_name: "邀请好友助力按钮",
      page_name: "活动首页",
    })
    if (!store.checkActTime()) return;
    shareStore.doInvite();
    API.assistJoin();
  };

  clickShare = () => {
    accessLog("502", {
      from: CFG.channel
    });
    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, agent } = 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} />

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

        {+CFG.channel == 5 && agent && <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;
