import { _decorator, AudioClip, Button, Component, instantiate, Label, Node, Prefab, SpriteFrame } from 'cc';
import { getWebData, LOG_TYPE, sendLog, sendWebNet, WebNetName } from '../../Utils/WebNet/WebNet';
import { showPanel, showToast } from '../../../Module/UIFast';
import Scene from '../../../Module/Scene';
import { TaskPanel } from '../../Panels/TaskPanel/TaskPanel';
import RulePanel from '../../Panels/RulePanel';
import store from '../../store/store';
import { _asyncThrottle, branchJumpUrl, dateFormatter, getUrlParam } from '../../Utils/Utils';
import { AudioMgr } from '../../../core_tgx/base/AudioMgr';
import LimitPanel from '../../Panels/LimitPanel';
import NotLoginPanel from '../../Panels/NotLoginPanel';
import { VList } from '../VList';
import { Sprite } from 'cc';
import HomeGuidePanel from '../../Panels/HomeGuidePanel';
const { ccclass, property } = _decorator;

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

    static bundle: string = "runMainPage";
    static skin: string = "runMainPage";

    @property(Node)
    backBtn: Node = null;

    @property(Node)
    ruleBtn: Node = null;

    @property(Node)
    yinliuBtn: Node = null;

    @property(Node)
    startBtn: Node = null;
    @property(Label)
    startLab: Label = null;

    @property(Node)
    taskBtn: Node = null;

    // 奖品列表（小于等于4个）
    @property(Node)
    prizeList4Num: Node = null;
    // 奖品列表（大于4个）
    @property(Node)
    prizeListMore: Node = null;
    // 奖品轮播盒子
    @property(VList)
    prizeListBox: VList = null;

    @property(AudioClip)
    bgMusic: AudioClip = null

    @property(Node)
    guide1: Node = null;

    @property(Prefab)
    prizeItemPrefab: Prefab = null;

    // 主按钮 高亮态
    @property(SpriteFrame) mainBtnSF: SpriteFrame = null;
    // 主按钮 置灰态
    @property(SpriteFrame) mainBtnGreySF: SpriteFrame = null;

    private static _ins: runMainPage = null;


    static get ins() {
        return runMainPage._ins;
    }
    onLoad() {
        runMainPage._ins = this;
        AudioMgr.ins.play(this.bgMusic, { loop: true })
    }

    start() {
        this.getIndex()
        this.backBtn.on(Button.EventType.CLICK, this.click_Back, this)
        this.ruleBtn.on(Button.EventType.CLICK, this.click_Rule, this)
        this.yinliuBtn.on(Button.EventType.CLICK, this.click_Yinliu, this)
        this.startBtn.on(Button.EventType.CLICK, this.click_startGame, this)
        this.taskBtn.on(Button.EventType.CLICK, this.click_Task, this)

        sendLog(LOG_TYPE.EXPOSURE, 21);
        sendLog(LOG_TYPE.EXPOSURE, 22);
        sendLog(LOG_TYPE.EXPOSURE, 23);
    }
    async getIndex() {
        const { success, data } = await sendWebNet(WebNetName.tcs_Index);
        if (success) {
            this.startLab.string = `剩余次数：${data.remainJoinNum || 0}`
            // 主按钮置灰处理
            this.startBtn.getChildByName("runmainbtn").getComponent(Sprite).spriteFrame = data.remainJoinNum > 0 ? this.mainBtnSF : this.mainBtnGreySF;
            // 新手引导1
            if (data.alreadyGuide == 0) {
                this.guide1.active = true
            } else if (data.alreadyGuide == 1) {
                showPanel(HomeGuidePanel)
            }
            if (data.offlineNewAssist && data.offlineNewAssist > 0) {
                showToast(`一共有${data.offlineNewAssist}位好友助力，快去任务面板领取奖励次数吧～`)
            }
            // 处理奖品列表展示
            if (data.prizeShow?.length <= 4) {
                this.prizeList4Num.active = true;
                this.prizeListMore.active = false;
                data.prizeShow.forEach((item, index) => {
                    const itemr = instantiate(this.prizeItemPrefab)
                    itemr.getChildByPath("prizeImgMask/prizeImg")
                        .getComponent(Sprite).spriteFrame = item.prizeImage;
                    this.prizeList4Num.getChildByName("prizeListLess").addChild(itemr)
                })
            } else {
                const updateItem = (node, data) => {
                    node.getChildByPath("prizeImgMask/prizeImg")
                        .getComponent(Sprite).spriteFrame = data.prizeImage;
                };
                // this.prizeListBox.node.removeAllChildren();
                // this.prizeListBox.node.destroyAllChildren();
                this.prizeList4Num.active = false;
                this.prizeListMore.active = true;
                this.prizeListBox.init(data.prizeShow, updateItem);
            }
        }
    }


    click_Back = _asyncThrottle(() => {
        AudioMgr.ins.stop()
        history.back()
    })
    click_Rule = _asyncThrottle(() => {
        showPanel(RulePanel)
    })
    click_Yinliu = _asyncThrottle(() => {
        AudioMgr.ins.stop()
        // 跳转笔走龙蛇
        branchJumpUrl('cgbd.html')
    })

    click_Task = _asyncThrottle(() => {
        showPanel(TaskPanel)
        sendLog(LOG_TYPE.CLICK, 23);
    })
    click_startGame = _asyncThrottle(async () => {
        sendLog(LOG_TYPE.CLICK, 22);
        const { data, timeStamp } = getWebData(WebNetName.tcs_Index) || {};
        const {
            boolBankUser, // 是否是银行用户 true:是 false:不是
            remainJoinNum, // 剩余游戏参与次数
            boolLogin,
            activityStartTime,
            activityEndTime,
            alreadyGuide, // 新手引导-已引导步数	
            totalGuide, // 新手引导-总引导步数
        } = data || {}
        const __activityStatus = timeStamp < activityStartTime ? 0 : timeStamp > activityEndTime ? 2 : 1;
        if (__activityStatus == 0) {
            showToast(`活动于${dateFormatter(activityStartTime, 'MM月dd日')}开启，请先完成任务积攒次数哦～`)
            return
        }
        if (__activityStatus == 2) {
            showToast(`活动已结束`)
            return
        }
        if (!boolLogin) {
            showPanel(NotLoginPanel)
            return
        }
        if (!boolBankUser) {
            showPanel(LimitPanel)
            return
        }
        if (remainJoinNum <= 0) {
            showToast("当前无游戏机会，任务可获得更多游戏机会哦～")
            showPanel(TaskPanel)
            return false
        }

        if (alreadyGuide == 0) {
            // 新手引导
            const { success, data } = await sendWebNet(WebNetName.tcs_StepBranchGuide, {
                branchType: store.BRANCH_TYPE
            });
            if (!success) return;
            console.log(this, this.guide1)
            this.guide1.active = false
        }
        await store.startTCS()
    })
    update(deltaTime: number) {

    }

}


