import React from 'react';
import { observer } from 'mobx-react';
import './HomePage.less';
import { Button, Toast } from "@grace/ui";
import { _asyncThrottle, getUrlParam, miniGoUrl } from "@/utils/utils.ts";
import store from "@/store/store.ts";
import { SvgaPlayer } from "@grace/svgaplayer";
import homeSvga from "../../../src/assets/svga/2输出首页氛围.svga";
import btnSvga from "../../../src/assets/svga/3输出按钮.svga";
import taskSvga from "../../../src/assets/svga/1底框.svga";
import gameStore from "@/store/gameStore.ts";
import MusicBtn from "@/core/components/MusicBtn/MusicBtn.tsx";
import { ModalCtrl } from "@/core/ctrls/ModalCtrl.tsx";
import PrizePanel from "@/panels/PrizePanel/PrizePanel.tsx";
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import GamePage from "@/pages/GamePage/GamePage.tsx";
import musicStore from '@/store/musicStore';
import Drawpop from '@/components/drawpop/drawpop';
import Posterpop from '@/components/posterpop/posterpop';
import API from '@/api';
import Rankpage from '../rankpage/rankpage';
import Rulepop from '@/components/rulepop/rulepop';
import Prizepage from '../prizepage/prizepage';
import WxOpenModule from '@/components/wxOpenModule/wxOpenModule';
import { handleLogClick } from '@/MD';
import { accessLog } from '@/built-in/duiba-utils';

@observer
class HomePage extends React.Component<any, any> {

  root: HTMLDivElement;

  componentDidMount() {
    store.updateIndex();
    store.queryTask()
    if (getUrlParam('inviteCode')) {
      store.doAssist()
    }
  }

  /** 开始游戏按钮*/
  startGame = _asyncThrottle(async () => {

    if (!store.judgeActTime()) return;
    if (store.indexData.remainTimes == 0) {
      Toast.show("暂无游戏次数哦")
      return;
    }
    accessLog(502, { join_type: 1 })
    const suc = await gameStore.start();
    if (!suc) return;
  })

  /** 奖品按钮*/
  clickPrize = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return;
    PageCtrl.changePage(Prizepage)
  })

  /** 规则按钮*/
  clickRule = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return;
    ModalCtrl.showModal(Rulepop);
  })
  clickDraw = _asyncThrottle(() => {
    if (!store.judgeActTime()) return;
    if (store.indexData.remainDrawTimes == 0) {
      Toast.show('暂无抽奖机会哦')
      return;
    }
    accessLog(502, { join_type: 3 })
    ModalCtrl.showModal(Drawpop, {});
  })
  clickShop = () => {
    console.info('shop')
    // if (!store.judgeActTime()) return;
    accessLog(502, { join_type: 2 })
    miniGoUrl('')
  }
  doTask = _asyncThrottle((item: { code: string; }) => {
    if (!store.judgeActTime()) return;
    if (item.code == "invite") {
      // 分享
      handleLogClick(10, 1)
      ModalCtrl.showModal(Posterpop)
      return;
    } else if (item.code == "scan") {
      handleLogClick(11, 1)
      miniGoUrl(store.frontVariable.scanUrl)
      return;
    }
  })

  getTaskPrize = _asyncThrottle(async (item) => {
    if (!store.judgeActTime()) return;
    accessLog(502, { join_type: 4 })
    if (item.code == 'login') {
      handleLogClick(9)
    } else if (item.code == 'invite') {
      handleLogClick(10, 2)
    } else if (item.code == 'scan') {
      handleLogClick(11, 2)
    }
    const { success, data } = await API.sendPrize({
      prizePendingCode: item.prizePendingCode,
      taskId: item.id,
      taskCode: item.code
    })
    if (success) {
      Toast.show("游戏次数+" + data.options[0].sendCount)
      store.updateIndex()
      store.queryTask()
    }
  })

  clickRank = _asyncThrottle(() => {
    if (!store.judgeActTime()) return;
    PageCtrl.changePage(Rankpage);
  })


  render() {
    const { remainTimes, remainDrawTimes, rank } = store.indexData
    return <div className="homepage md1" ref={(el) => this.root = el}>
      <span className="bg"></span>
      <div className="infobox">
        <span className="infobg"></span>
        <div className="prizeingo">
          <span className="prizename">{rank?.prizeName}</span>
          <span className="prizerank">前50名可得</span>
          <span className="prizeimg">
            <img src={rank?.prizeImg}></img>
          </span>
        </div>
        <div className="rankinfo md5" onClick={this.clickRank}>
          <span className="rankarr"></span>
          <span className="ranklab">我的排名</span>
          <span className="ranknum">{(rank?.rank == -1 ? "999+" : rank?.rank > 999 ? '999+' : ((rank?.rank || '--') + "名"))}</span>
        </div>
      </div>
      <span className="title"></span>
      <Button className="prizebtn md2" onClick={this.clickPrize}></Button>
      <Button className="rulebtn md3" onClick={this.clickRule}></Button>
      {/* <span className="musicon"></span>
      <span className="musicf"></span> */}
      <MusicBtn className={`${musicStore.mute ? 'musicf md4' : 'musicon md4'}`}></MusicBtn>
      <Button className="mainbtn md7" onClick={this.startGame}>
        <SvgaPlayer className='btnsvga' src={btnSvga}></SvgaPlayer>
        <span className="mianimg"></span>
        <span className="mainnum">剩余次数：{remainTimes || 0}</span>
      </Button>
      <Button className="shopbtn md6" onClick={this.clickShop}>
        <WxOpenModule
          id={"shopbtn"}
          appid={'wxc911dd6c6bc128de'}
          username={'gh_de562905dee7'}
          envVersion={'release'}
          path={'/pages/retail/festival-event/festival-act?id=859442452439264065&orgId=58929495997939712&programId=84796583983972352'}></WxOpenModule>
      </Button>
      <Button className="drawbtn md8" onClick={this.clickDraw}>
        <span className="drawimg"></span>
        <div className="drawnum">
          <span className="drawnumbg"></span>
          <span className="drawnumlab">{remainDrawTimes || 0}</span>
        </div>
      </Button>
      <div className="tasklist">
        {
          store.taskList?.map((item: any, index) => {
            return (
              <div className="taskitem" key={"task" + index}>
                {/* <span className="taskbg"></span> */}
                <SvgaPlayer className='taskbg' src={taskSvga}></SvgaPlayer>
                {
                  item.taskStatus == 2 ? <span className="taskfinishbtn"></span>
                    : item.taskStatus == 1 ? <Button className="taskgetbtn" onClick={() => this.getTaskPrize(item)}></Button>
                      : item.code == "invite" ? <Button className="taskinvitebtn" onClick={() => this.doTask(item)}></Button>
                        : item.code == "scan" ? <Button className="taskscanbtn" onClick={() => this.doTask(item)}></Button>
                          : ''// <span className="taskgetbtn">{item.taskStatus}</span>
                }
                <span className="tasktit">{item.title}({item.completedSize}/{item.intervalLimitSize})</span>
                <span className="tasksub">{item.subTitle}</span>
                <span className="taskicon">
                  <img src={item.icon}></img>
                </span>
              </div>
            )
          })
        }
      </div>
      <span className="tasktitle"></span>
      <span className="logo"></span>
      <SvgaPlayer className='homesvga' src={homeSvga}></SvgaPlayer>


    </div>;
  }
}

export default HomePage;
