import {_decorator, Button, easing, Label, Node, tween, v3} from 'cc';
import Scene from "db://assets/Module/Scene";
import {getWebData, LOG_TYPE, sendLog, sendWebNet, 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, wait} from '../Utils/Utils';
import {RankScene} from './RankScene';
import InvitePanel from '../Panels/InvitePanel';
import ShareCenter from '../ShareCenter';
import {RecordScene} from './RecordScene';
import {ChangeEquipPanel} from '../Panels/ChangeEquipPanel/ChangeEquipPanel';
import {GetRankPrizePanel} from '../Panels/GetRankPrizePanel';
import {NoGetRankPrizePanel} from '../Panels/NoGetRankPrizePanel';
import {GuidePrizePanel} from '../Panels/GuidePrizePanel';
import {BeautyPanel} from '../Panels/BeautyPanel';
import {TaskPanel} from '../Panels/TaskPanel/TaskPanel';
import ToolBuyPanel from '../Panels/ToolBuyPanel';
import ChoosePrizePanel from '../Panels/ChoosePrizePanel';

const { ccclass, property } = _decorator;

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

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

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

    /** 送惊喜按钮 */
    @property(Node)
    surpriseBtn: Node = null;

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

    /** 返回按钮 */
    @property(Node)
    backBtn: 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;

    startBtnTween = null;

    onLoad() {

        this.startBtn.on(Button.EventType.CLICK, this.clickStart, this);
        this.surpriseBtn.on(Button.EventType.CLICK, this.clickSurprise, this);
        this.taskBtn.on(Button.EventType.CLICK, this.clickTask, this);
        this.backBtn.on(Button.EventType.CLICK, this.clickBack, 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);
        
    }

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

        sendLog(LOG_TYPE.EXPOSURE, 1)
        sendLog(LOG_TYPE.EXPOSURE, 2)
        sendLog(LOG_TYPE.EXPOSURE, 3)
        sendLog(LOG_TYPE.EXPOSURE, 4)
        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)
    }

    /** 获取首页 */
    getHomeInfo = async () => {
        const { success, data } = await sendWebNet(WebNetName.index);
        if (success) {
            const {
                remainGameTime = 0, // 剩余挑战次数
                rankScore = 0, // 总榜积分
                rank = 0, // 总榜排名(0:未参与 -1:排名超出999)
                assistPopInfo, // 助力弹窗信息
                boolFirstEnter, // 是否首次登录 true:是 false:不是
                boolBeauty, // 女神节弹窗，true：弹，false：不弹
                weekRankPopInfo, // 周排行榜发奖弹窗信息
                rankPopInfo, // 总排行榜发奖弹窗信息
                beautyLoginSend, // 女神节女性用户登陆赠送游戏次数
                boolChooseRankPrize, // 是否需要选择排行榜奖品(true-需要选择 false-不需要选择)
            } = data || {}
            this.gameCountLabel.string = `游戏剩余次数：${remainGameTime}`
            // 最多展示7位数字，超过7位数展示为999999+
            this.pointLabel.string = rankScore > 9999999 ? '999999+' : rankScore

            // 有次数 主按钮 呼吸动效
            if (remainGameTime) {
                this.startBtnTween = tween(this.startBtn)
                    .repeatForever(
                        tween(this.startBtn)
                            .to(0.5, { scale: v3(1.1, 1.1, 1.1) }, { easing: easing.smooth })
                            .to(0.5, { scale: v3(0.9, 0.9, 0.9) }, { easing: easing.smooth })
                    )
                    .start();
            } else {
                this.startBtnTween && this.startBtnTween.stop();
            }

            // 最多超过999名就展示999+  未参与游戏展示—
            if (rank === 0) {
                this.currentRankLabel.string = '999+'
            } else if (rank === -1 || rank > 999) {
                this.currentRankLabel.string = '999+'
            } else {
                this.currentRankLabel.string = rank
            }

            // 女神节女性用户登陆赠送游戏次数
            if (beautyLoginSend) {
                showToast(`女神节惊喜福利！\n江苏银行送您额外游戏次数*${beautyLoginSend}`)
            }

            /** 周排行榜获奖 */
            if (!!weekRankPopInfo?.boolShowPop) {
                if (!!weekRankPopInfo?.boolGetPrize) {
                    showPanel(GetRankPrizePanel, weekRankPopInfo)
                } else {
                    showPanel(NoGetRankPrizePanel, weekRankPopInfo);
                }
            }

            /** 总排行榜获奖 */
            if (!!rankPopInfo?.boolShowPop) {
                if (!!rankPopInfo?.boolGetPrize) {
                    showPanel(GetRankPrizePanel, rankPopInfo)
                } else {
                    showPanel(NoGetRankPrizePanel, rankPopInfo);
                }
            }

            /** 首次登录 */
            if (!!boolFirstEnter) {
                showPanel(GuidePrizePanel);
            }

            /** 女神弹窗 */
            if (!!boolBeauty) {
                showPanel(BeautyPanel);
            }

            /** 奖品二选一弹窗 */
            if (boolChooseRankPrize) {
                showPanel(ChoosePrizePanel);
            }

            // 助力弹窗信息
            if (assistPopInfo && assistPopInfo.newAssistNum) {
                if (beautyLoginSend) {
                    await wait(2.3)
                }
                showToast(`${assistPopInfo.newAssistNum}位好友为你助力～已获得${assistPopInfo.newChallengeNum}次挑战次数`)
            }
        }
    }

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

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

        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, 10)
        await changeScene(RankScene)
    }

    /** 送惊喜 */
    clickSurprise = async () => {
        sendLog(LOG_TYPE.CLICK, 4)
        if (!this.checkActStatus()) return false
        showPanel(InvitePanel)
    }

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

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

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

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

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

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

    /** 返回 */
    clickBack = async () => {
        sendLog(LOG_TYPE.CLICK, 6)
        sessionStorage.clear();
        const ThirdApp = window['ThirdApp']
        if (ThirdApp) {
            ThirdApp.setSession('final', {})
            ThirdApp.gotoBack();
        }
    }

    update(deltaTime: number) {

    }
}

