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';
// 扩展 JSX 命名空间，添加 wx-open-launch-weapp 组件类型定义
declare global {
  namespace JSX {
    interface IntrinsicElements {
      'wx-open-launch-weapp': {
        id: string;
        username: string;
        path: string;
        style?: React.CSSProperties;
        // 添加 children 属性
        children?: React.ReactNode; 
      };
    }
  }
}
@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;
    }
    const suc = await gameStore.start();
    if (!suc) return;

    PageCtrl.changePage(GamePage);
  })

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

  /** 规则按钮*/
  clickRule = () => {
    if (!store.judgeActTime(true, false)) return;
    ModalCtrl.showModal(Rulepop);
  }
  clickDraw = () => {
    if (!store.judgeActTime()) return;
    ModalCtrl.showModal(Drawpop, {});
  }
  clickShop = () => {
    if (!store.judgeActTime()) return;
    miniGoUrl(store.frontVariable.shopUrl)
  }
  doTask = _asyncThrottle((item: { code: string; }) => {
    if (!store.judgeActTime()) return;
    if (item.code == "invite") {
      // 分享
      ModalCtrl.showModal(Posterpop)
      return;
    } else if (item.code == "scan") {
      miniGoUrl(store.frontVariable.scanUrl)
      return;
    }
  })

  getTaskPrize = _asyncThrottle(async (item) => {
    if (!store.judgeActTime()) return;
    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()
    }
  })

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


  render() {
    const { remainTimes, remainDrawTimes, rank } = store.indexData
    return <div className="homepage" 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" onClick={this.clickRank}>
          <span className="rankarr"></span>
          <span className="ranklab">我的排名</span>
          <span className="ranknum">{rank?.rank == -1 ? "未上榜" : rank?.rank + "名"}</span>
        </div>
      </div>
      <span className="title"></span>
      <Button className="prizebtn" onClick={this.clickPrize}></Button>
      <Button className="rulebtn" onClick={this.clickRule}></Button>
      {/* <span className="musicon"></span>
      <span className="musicf"></span> */}
      <MusicBtn className={`${musicStore.mute ? 'musicf' : 'musicon'}`}></MusicBtn>
      <Button className="mainbtn" onClick={this.startGame}>
        <SvgaPlayer className='btnsvga' src={btnSvga}></SvgaPlayer>
        <span className="mianimg"></span>
        <span className="mainnum">剩余次数：{remainTimes || 0}</span>
      </Button>
      <Button className="shopbtn" onClick={this.clickShop}></Button>
      <Button className="drawbtn" 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>
      {
        <wx-open-launch-weapp
          id="launch-btn"
          username="gh_57d1c303c3b4"
          path='/pages/collectStep/collectStep'
          style={{ width: '3.98rem', height: '1.87rem', position: 'absolute' }} 
          >
          <template>
            <style></style>
            <img style={{ width: '3.98rem', height: '1.87rem', position: 'absolute' }} src="https://yun.duiba.com.cn/zhongherenshou/df17ab45-a411-45b5-8373-8bb506fd9dea.png"></img>
          </template></wx-open-launch-weapp>
      }

    </div>;
  }
}

export default HomePage;
