import { _decorator, Button, easing, Label, Node, Tween, tween, v3 } from 'cc';
import Scene from "db://assets/Module/Scene";
import { getWebData, LOG_TYPE, sendLog, sendLogList, WebNetName } from "db://assets/Scripts/Utils/WebNet/WebNet";
import { MainGame } from "db://assets/Scripts/Scenes/MainGame";
import { changeScene, showPanel, showToast } from "db://assets/Module/UIFast";
import GameMgr from "db://assets/Scripts/GameMgr";
import RulePanel from '../Panels/RulePanel';
import { getUrlParam } from '../Utils/Utils';
import { RankScene } from './RankScene/RankScene';
import ShareCenter from '../ShareCenter';
import { RecordScene } from './RecordScene/RecordScene';
import { ChangeEquipPanel } from '../Panels/ChangeEquipPanel/ChangeEquipPanel';
import { TaskPanel } from '../Panels/TaskPanel/TaskPanel';
import ToolBuyPanel from '../Panels/ToolBuyPanel';
import store from "../../store/store";
import { observer, render } from "../../store/decorators";
import { PrizeScene } from "./PrizeScene/PrizeScene";
import { appShare } from "../../AppTool";

const {ccclass, property} = _decorator;

@observer
@ccclass('HomeScene')
export class HomeScene extends Scene {

    static skin: string = "HomeScene";
    static group: string[] = ["HomeScene"];

    /** 去挑战按钮 */
    @property(Node)
    startBtn: Node = null;

    /** 任务按钮 */
    @property(Node)
    taskBtn: Node = null;

    /** 返回按钮 */
    @property(Node)
    shareBtn: Node = null;

    /** 我的奖品按钮 */
    @property(Node)
    prizeBtn: Node = null;

    /** 规则按钮 */
    @property(Node)
    ruleBtn: Node = null;

    /** 明细按钮 */
    @property(Node)
    detailBtn: Node = null;

    /** 排行榜按钮 */
    @property(Node)
    rankBtn: Node = null;

    /** 剩余次数 */
    @property(Label)
    gameCountLabel: Label = null;

    /** 财富积分值 */
    @property(Label)
    pointLabel: Label = null;

    /** 当前排名值 */
    @property(Label)
    currentRankLabel: Label = null;

    /** 佩戴财富圈 */
    @property(Node)
    circleBtn: Node = null;

    /** 天降财神 */
    @property(Node)
    toolBtn: Node = null;

    onLoad() {

        this.startBtn.on(Button.EventType.CLICK, this.clickStart, this);
        this.taskBtn.on(Button.EventType.CLICK, this.clickTask, this);
        this.shareBtn.on(Button.EventType.CLICK, this.clickShare, this);
        this.prizeBtn.on(Button.EventType.CLICK, this.clickPrize, this);
        this.ruleBtn.on(Button.EventType.CLICK, this.clickRule, this);
        this.detailBtn.on(Button.EventType.CLICK, this.clickDetail, this);
        this.rankBtn.on(Node.EventType.TOUCH_END, this.clickRank, this);
        this.circleBtn.on(Button.EventType.CLICK, this.clickCircle, this);
        this.toolBtn.on(Button.EventType.CLICK, this.clickTool, this);


        sendLog(LOG_TYPE.EXPOSURE, 5)
        sendLog(LOG_TYPE.EXPOSURE, 6)
        sendLog(LOG_TYPE.EXPOSURE, 7)
        sendLog(LOG_TYPE.EXPOSURE, 8)
        sendLog(LOG_TYPE.EXPOSURE, 9)
        sendLog(LOG_TYPE.EXPOSURE, 10)
        sendLog(LOG_TYPE.EXPOSURE, 11)
        sendLog(LOG_TYPE.EXPOSURE, 12)

    }

    async start() {
        store.getBaseInfo();
        // 因为助力成功也会给助力者发放次数 所以在首页接口前调用
        await ShareCenter.ins.doAssist()
        store.updateIndex();
    }

    @render
    render() {
        const {
            remainGameTime = 0, // 剩余挑战次数
            rankScore = 0, // 总榜积分
            rank = 0, // 总榜排名(0:未参与 -1:排名超出999)
        } = store.homeInfo || {};

        this.gameCountLabel.string = `游戏剩余次数：${remainGameTime}`;
        this.pointLabel.string = `${rankScore > 99999999 ? '99999999+' : rankScore}`;
        if (remainGameTime) {
            tween(this.startBtn)
                .repeatForever(
                    tween(this.startBtn)
                        .to(0.666, {scale: v3(1.05, 1.05, 1.05)}, {easing: easing.smooth})
                        .to(0.666, {scale: v3(0.95, 0.95, 0.95)}, {easing: easing.smooth})
                )
                .start();
        } else {
            Tween.stopAllByTarget(this.startBtn);
        }

        if (rank === 0) {
            this.currentRankLabel.string = '-';
        } else if (rank > 5000 || rank === -1) {
            this.currentRankLabel.string = '5000+';
        } else {
            this.currentRankLabel.string = `${rank}`;
        }

    }

    /** 校验活动状态 */
    checkActStatus = () => {
        const {timeStamp} = getWebData(WebNetName.index) || {};
        const {activityStartTime, activityEndTime} = store.homeInfo || {};
        if (activityStartTime > timeStamp) {
            showToast("活动暂未开始，敬请期待~");
            return false;
        } else if (activityEndTime <= timeStamp) {
            showToast("活动已结束~");
            return false;
        }
        return true;
    }

    /** 去挑战 */
    clickStart = async () => {
        sendLog(LOG_TYPE.CLICK, 5)
        if (!this.checkActStatus()) return false;
        const {
            remainGameTime = 0, // 剩余挑战次数
            boolDayPlayLimit,   // 今日挑战是否已达上限 true:是 false:不是
        } = store.homeInfo || {};

        if (boolDayPlayLimit) {
            return showToast("今日挑战已达上限，明天再来吧～");
        }
        if (!remainGameTime) {
            return showToast("没有次数啦～快去做任务吧！\n明日再来还有免费次数哦！");
        }

        this.btnEnable(this.startBtn, false);
        try {
            const success = await GameMgr.ins.start();
            if (success) {
                await changeScene(MainGame);
            }
        } catch (e) {
            console.error(e);
        }
        this.btnEnable(this.startBtn, true);
    }

    /** 奖励排行 */
    clickRank = async () => {
        sendLog(LOG_TYPE.CLICK, 8)
        await changeScene(RankScene);
    }

    /** 任务 */
    clickTask = async () => {
        sendLog(LOG_TYPE.CLICK, 7)
        if (!this.checkActStatus()) return false
        showPanel(TaskPanel, {panelType: "scrollTop"});
    }

    /** 明细 */
    clickDetail = async () => {
        sendLog(LOG_TYPE.CLICK, 12)
        changeScene(RecordScene);
    }

    /** 佩戴财富圈 */
    clickCircle = async () => {
        sendLog(LOG_TYPE.CLICK, 6)
        if (!this.checkActStatus()) return false
        showPanel(ChangeEquipPanel);
    }

    /** 天降财神 */
    clickTool = async () => {
        if (!this.checkActStatus()) return false
        showPanel(ToolBuyPanel);
    }

    /** 我的奖品 */
    clickPrize = async () => {
        sendLog(LOG_TYPE.CLICK, 9)
        changeScene(PrizeScene);
        // setTimeout(() => {
        //     window.location.href = `prize.html?appID=${getUrlParam("appID")}&channel=${getUrlParam("channel")}`
        // }, 30)
    }

    /** 规则 */
    clickRule = async () => {
        sendLog(LOG_TYPE.CLICK, 11)
        showPanel(RulePanel);
    }

    /** 返回 */
    clickShare = async () => {
        sendLog(LOG_TYPE.CLICK, 10)
        if (!this.checkActStatus()) return false;
        await ShareCenter.ins.doShare();
    }

}

