// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import GameManager from "./GameManager";
import NumberToImage from "./NumberToImage";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
import { LQCollideSystem } from "./lq_collide_system/lq_collide_system";
import AudioManager from "./module/Music/AudioManager";
import Utils from "./module/Pay/Utils";
const { ccclass, property } = cc._decorator;

@ccclass
export default class JiaZai extends cc.Component {

    // 缓存 shop 预制体
    private static cachedShopPrefab: cc.Prefab | null = null;
    // 缓存 shop 节点
    private shopNode: cc.Node | null = null;

    // 缓存 reward 预制体
    private static cachedRewardPrefab: cc.Prefab | null = null;
    // 缓存 reward 奖励窗口 节点
    private RewardNode: cc.Node | null = null;

    @property(cc.Node)
    node1: cc.Node = null;

    @property(cc.Node)
    node2: cc.Node = null;

    @property(cc.Node)
    node3: cc.Node = null;



    @property({ type: [cc.SpriteAtlas], tooltip: "方块颜色" })
    Block_Color: Array<cc.SpriteAtlas> = [];

    @property(cc.EditBox)
    custom: cc.EditBox = null;



    @property(cc.Node)
    level: cc.Node = null;

    @property(cc.Node)
    coin: cc.Node = null;
    // 健康值
    @property(cc.Prefab)
    health: cc.Prefab = null;
    @property(cc.Node)
    Stamina: cc.Node = null;
    scheduleCallback: any;
    private heath: any; // 用于存储heath预制体
    private lastPauseClickTime: number = 0; // 用于记录上次点击的时间戳
    // 弹窗倒计时调度器
    private heathScheduleCallback: Function = null;
    @property(cc.Node)
    setUi: cc.Node = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        cc.game.setFrameRate(63);
        LQCollideSystem.is_enable = true;
        // //console.log("加载关卡配置2");
        // window.initMgr();
        GameManager._instance.Block_Color = this.Block_Color;
        let version = cc.fx.GameTool.getWechatGameVersion();
        if (version == "开发版" || version == "体验版") {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = true;
        }
        else if (version == "正式版") {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = false
        }
        else {
            this.node.getChildByName("Load").getChildByName("New EditBox").active = true;
        }
        // 预加载 shop 预制体
        if (!JiaZai.cachedShopPrefab) {
            cc.assetManager.loadBundle('shop', (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                bundle.load('prefab/shop', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedShopPrefab = prefab;
                });
                bundle.load('prefab/RewardWindow', cc.Prefab, (err: Error, prefab: cc.Prefab) => {
                    if (err) {
                        cc.error(err.message || err);
                        return;
                    }
                    JiaZai.cachedRewardPrefab = prefab;
                    // let data = [
                    //     { type: "coin", count: 125294 },
                    //     { type: "coin", count: 7498 },
                    //     { type: "freeze", count: 2 },
                    //     { type: "hammer", count: 2 },
                    //     { type: "magic", count: 2 },
                    //     { type: "coin", count: 250 },
                    // ]

                    // this.openRewardWindow(data);
                    this.getOrder();
                });
            });
        }

        if (cc.fx.GameConfig.GM_INFO.first) {
            //console.log("————————准备注册事件", cc.fx.GameConfig.GM_INFO.openid);
            const group = cc.fx.GameTool.setWechatGameGroup(2);
            if (group == 0) {
                cc.fx.GameConfig.GM_INFO.musicOpen = true;
            }
            else if (group == 1) {
                cc.fx.GameConfig.GM_INFO.musicOpen = false;
            }
            const audioInfo = {
                "musicOpen": cc.fx.GameConfig.GM_INFO.musicOpen,             //音乐
                "effectOpen": cc.fx.GameConfig.GM_INFO.effectOpen,            //音效
                "vibrateOpen": cc.fx.GameConfig.GM_INFO.vibrateOpen,           //震动
            }
            cc.fx.StorageMessage.setStorage("music", audioInfo);

            if (cc.fx.GameConfig.GM_INFO.openid != "") {
                //console.log("————————发送注册事件");
                const time = cc.fx.GameTool.formatDate(new Date());
                let data = {
                    register_time: time, // 注册时间
                }
                cc.fx.GameTool.shushu_Track("register", data);
                MiniGameSdk.API.shushu_SetSuperProperties(time, false);
            }
            cc.fx.AudioManager._instance.playEffect("zhuan1", null);
            this.node.getChildByName("zhuanchang").active = true;
            this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
            setTimeout(() => {
                cc.fx.GameConfig.GM_INFO.first = false;
                cc.director.loadScene("GameScene");
            }, 1000);

        }
        //console.log("音乐开关", cc.fx.GameConfig.GM_INFO.musicOpen);
        AudioManager._instance.playMusicGame();
    }

    start() {
        // //console.log("已经进入Home界面");
        // //console.log("金币",cc.fx.GameConfig.GM_INFO.coin);
        // //console.log("关卡",cc.fx.GameConfig.GM_INFO.level+1);

        cc.fx.GameTool.getHealth(null);
        // cc.fx.GameConfig.LEVEL_INFO_init(false,0);
        setTimeout(() => {
            NumberToImage.numberToImageNodes((cc.fx.GameConfig.GM_INFO.level + 1), 43, 15, "level_", this.level, true);
            NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
            this.setHealthInfo();
        }, 0);
        if (cc.fx.GameConfig.GM_INFO.gameState) {
            this.node.getChildByName("zhuanchang").active = true;
            setTimeout(() => {
                cc.fx.AudioManager._instance.playEffect("zhuan2", null);
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "down", false);
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setCompleteListener((entry) => {
                    if (entry.animation.name === "down" && !cc.fx.GameConfig.GM_INFO.first) {
                        // 动画播放结束后执行的逻辑
                        this.node.getChildByName("zhuanchang").active = false;
                    }
                });
            }, 500);
        }
        else {
            if (!cc.fx.GameConfig.GM_INFO.first)
                this.node.getChildByName("zhuanchang").active = false;
        }


        // //打开heath弹窗
        //  this.openHeath();
        this.uploadToCloud(cc.fx.GameConfig.GM_INFO.level + 1);

    }

    //打开heath弹窗,创建预制体
    // 打开heath弹窗，创建预制体并启动自己的倒计时
    openHeath() {
        let health = cc.instantiate(this.health);
        this.node.addChild(health);
        let heathPop = health.getComponent("heathnum").heatht;
        heathPop.scale = 0.7;
        this.heath = heathPop; // 保存heath预制体引用
        let swichs = health.getComponent("heathnum").switchNode;
        let timeNode = health.getComponent("heathnum").timeNode;
        let switchButtons = health.getComponent("heathnum").switchButtons;
        let coin = health.getComponent("heathnum").coin;
        // 启动弹窗自己的倒计时
        if (cc.fx.GameConfig.GM_INFO.hp < 5) {
            this.startHeathTimeCutDown(timeNode);
        }
        if (cc.fx.GameConfig.GM_INFO.hp == 0) {
            // 体力为0，显示spriteFrames[1]，只显示第二个按钮

            if (switchButtons[0]) { switchButtons[0].active = false; swichs[0].active = false; }
            if (switchButtons[1]) { switchButtons[1].active = true; swichs[1].active = true; }
        } else if (cc.fx.GameConfig.GM_INFO.hp < 5 && cc.fx.GameConfig.GM_INFO.hp > 0) {
            // 体力小于5但大于0，显示spriteFrames[1]，只显示第一个按钮
            if (switchButtons[0]) { switchButtons[0].active = true; swichs[0].active = false; }
            if (switchButtons[1]) { switchButtons[1].active = false; swichs[1].active = true; }
        } else if (cc.fx.GameConfig.GM_INFO.hp >= 5) {

            // 体力为5，显示spriteFrames[0]，只显示第一个按钮
            if (switchButtons[0]) { switchButtons[0].active = true; swichs[0].active = true; }
            if (switchButtons[1]) { switchButtons[1].active = false; swichs[1].active = false; }
        }
        NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 40, 20, "time_", heathPop, true);
        // 设置金币花费数

        // NumberToImage.numberToImageNodes(1000, 35, 15, "button_", coin, true);


    }

    // 弹窗倒计时
    startHeathTimeCutDown(timeLabelNode?: cc.Node) {
        this.stopHeathTimeCutDown();
        this.heathScheduleCallback = function () {
            if (cc.fx.GameConfig.GM_INFO.min_Time <= 0) {
                this.stopHeathTimeCutDown();

                let timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                //console.log("健康值倒计时结束，当前时间：", timeTemp, cc.fx.GameConfig.GM_INFO.min_Time);
                if (timeLabelNode) {
                    NumberToImage.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time, 50, "time_", timeLabelNode);
                }
                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 40, 20, "time_", this.heath, true);
            } else {
                cc.fx.GameConfig.GM_INFO.min_Time -= 0;
                let timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                if (timeLabelNode) {
                    NumberToImage.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time, 50, "time_", timeLabelNode);
                }
            }
        }.bind(this);
        this.heathScheduleCallback();
        this.schedule(this.heathScheduleCallback, 1);
    }

    stopHeathTimeCutDown() {
        if (this.heathScheduleCallback) {
            this.unschedule(this.heathScheduleCallback);
            this.heathScheduleCallback = null;
        }
    }
    //开始倒计时
    startTimeCutDown() {
        this.scheduleCallback = function () {
            if (this.pause) return;
            if (cc.fx.GameConfig.GM_INFO.min_Time <= 0) {
                this.stopTimeCutDown();
                var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("time")) {
                    this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
                }
                if (cc.fx.GameConfig.GM_INFO.hp < 5) {
                    MiniGameSdk.API.showToast("恢复一点体力");
                    cc.fx.GameTool.setUserHealth(1, (data) => {
                        cc.fx.GameTool.getHealth(null);
                        this.setHealthInfo();
                    })
                }

            }
            else {
                cc.fx.GameConfig.GM_INFO.min_Time -= 1;
                var timeTemp = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                // 同步显示
                if (this.Stamina && this.Stamina.getChildByName("time")) {
                    this.Stamina.getChildByName("time").getComponent(cc.Label).string = timeTemp;
                }
            }
        }.bind(this);
        this.schedule(this.scheduleCallback, 1);
    }
    // 停止倒计时
    stopTimeCutDown() {
        if (this.scheduleCallback) {
            this.unschedule(this.scheduleCallback);
        }
    }

    uploadToCloud(level: number) {
        if (typeof wx !== 'undefined') {
            //@ts-ignore
            wx.setUserCloudStorage({
                KVDataList: [
                    { key: 'level', value: String(level) }
                ],
                success: () => console.log('✅ 数据上传成功'),
                fail: (err) => console.error('❌ 上传失败', err)
            });
        }
    }


    setHealthInfo() {
        if (cc.fx.GameConfig.GM_INFO.hp >= 5) {
            this.Stamina.getChildByName("man").active = true;
            this.Stamina.getChildByName("health").active = true;
            NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
            this.Stamina.getChildByName("time").active = false;
        }
        else {
            this.Stamina.getChildByName("man").active = false;
            this.Stamina.getChildByName("health").active = true;
            NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.hp, 25, 15, "hp_", this.Stamina.getChildByName("health"), false);
            this.Stamina.getChildByName("time").active = true;
            if (cc.fx.GameConfig.GM_INFO.min_Time != 0) {
                let time = cc.fx.GameTool.getTimeMargin(cc.fx.GameConfig.GM_INFO.min_Time);
                this.Stamina.getChildByName("time").getComponent(cc.Label).string = time;
                this.startTimeCutDown();
            }
        }
    }


    startGame() {
        cc.fx.AudioManager._instance.playEffect("anniu_Big", null);
        if (cc.fx.GameConfig.GM_INFO.hp < 1) {
            MiniGameSdk.API.showToast("体力值不足");
            setTimeout(() => {
                this.openHeath();
            }, 500);
            return;
        }
        if (this.node.getChildByName("Load").getChildByName("startBtn").getComponent("btnControl")._touch) {
            this.node.getChildByName("Load").getChildByName("startBtn").getComponent("btnControl").setTouch(false);
            let version = cc.fx.GameTool.getWechatGameVersion();
            if (version == "开发版" || version == "体验版") {
                if (this.custom.string != "") {
                    cc.fx.GameConfig.GM_INFO.level = parseInt(this.custom.string) - 1;
                    // cc.fx.StorageMessage.setStorage("level",cc.fx.GameConfig.GM_INFO.level.toString()); 
                    cc.fx.GameConfig.LEVEL_INFO_init(true);
                }
                else {
                    cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                    this.node.getChildByName("zhuanchang").active = true;
                    this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 1000);
                }
            }
            else if (version == "正式版") {
                cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                this.node.getChildByName("zhuanchang").active = true;
                this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                cc.fx.GameConfig.LEVEL_INFO_init(true, 1000);
            }
            else {
                if (this.custom.string != "") {
                    cc.fx.GameConfig.GM_INFO.level = parseInt(this.custom.string) - 1;
                    // cc.fx.StorageMessage.setStorage("level",cc.fx.GameConfig.GM_INFO.level.toString()); 
                    cc.fx.GameConfig.LEVEL_INFO_init(true);
                }
                else {
                    cc.fx.AudioManager._instance.playEffect("zhuan1", null);
                    this.node.getChildByName("zhuanchang").active = true;
                    this.node.getChildByName("zhuanchang").getComponent(sp.Skeleton).setAnimation(1, "up", false);
                    cc.fx.GameConfig.LEVEL_INFO_init(true, 1000);
                }
            }
        }



    }

    //打开商店
    openShop() {
        if (!JiaZai.cachedShopPrefab) {
            cc.error('Shop prefab is not loaded yet.');
            return;
        }

        if (!this.shopNode) {
            // 第一次使用，创建节点
            this.shopNode = cc.instantiate(JiaZai.cachedShopPrefab);
            this.node.addChild(this.shopNode);
        } else {
            // 非第一次使用，直接激活节点
            this.shopNode.active = true;
            this.shopNode.getComponent("shop").init();
        }
        // //console.log("shopNode parent:", this.shopNode.parent);
    }

    openRewardWindow(data) {
        if (!JiaZai.cachedRewardPrefab) {
            cc.error('Reward prefab is not loaded yet.');
            return;
        }
        if (!this.RewardNode) {
            // 第一次使用，创建节点
            this.RewardNode = cc.instantiate(JiaZai.cachedRewardPrefab);
            this.node.addChild(this.RewardNode);
            this.RewardNode.getComponent("Reward").init(data);
        }
        else {
            this.RewardNode.destroy();
            this.RewardNode = null;
            this.RewardNode = cc.instantiate(JiaZai.cachedRewardPrefab);
            this.node.addChild(this.RewardNode);
            this.RewardNode.getComponent("RewardWindow").init(data);
        }
    }

    // 关闭商店
    closeShop() {
        if (this.shopNode) {
            this.shopNode.active = false;
        }
    }

    closeRank() {
        this.node.getChildByName("Rank").active = false;
    }

    openRank() {
        this.node.getChildByName("Rank").active = true;
    }

    openReward() {
        this.node.getChildByName("Reward").active = true;
    }

    clickShop() {
        // 假设已经获取到了 userId 和 productId


    }


    openPause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        //console.log(cc.fx.GameConfig.GM_INFO);
        if (cc.fx.GameConfig.GM_INFO.openid == undefined) {
            //console.log(cc.fx.GameConfig.GM_INFO.openid);
            cc.fx.GameConfig.GM_INFO.openid = "";
        }
        this.node.getChildByName("Pause").active = true;
        this.node.getChildByName("Pause").getChildByName("openID").getComponent(cc.Label).string = cc.fx.GameConfig.GM_INFO.openid;
    }

    closePause() {
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        this.node.getChildByName("Pause").active = false;

    }

    openSet() {
        const now = Date.now();
        if (now - this.lastPauseClickTime < 300) {
            // 0.3秒内禁止再次点击
            return;
        }
        this.lastPauseClickTime = now;
        cc.fx.AudioManager._instance.playEffect("anniu_little", null);
        if (cc.fx.GameConfig.GM_INFO.openid == undefined) {
            cc.fx.GameConfig.GM_INFO.openid = "";
        }
        if (!this.setUi.active) {
            // 第一次点击，打开并播放动画
            this.setUi.active = true;
            this.setUi.getComponent(cc.Animation).play();
        } else {
            // 再次点击，关闭节点
            this.setUi.active = false;
        }
    }

    closeReward() {
        this.node.getChildByName("Reward").active = false;
    }

    openStamina() {
        this.node.getChildByName("Stamina").active = true;
    }

    closeStamina() {
        this.node.getChildByName("Stamina").active = false;
    }

    updateCoin() {
        //console.log("主页更新金币", cc.fx.GameConfig.GM_INFO.coin);
        NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
    }

    getOrder() {
        if (typeof wx !== 'undefined' && wx !== null) {
            // 判断设备系统
            let systemType = "Android";
            try {
                //@ts-ignore
                const systemInfo = wx.getSystemInfoSync();
                if (systemInfo.platform === 'ios') {
                    systemType = "ios";
                }
            } catch (e) {
                console.error('获取系统信息失败', e);
            }
            if (cc.fx.GameConfig.GM_INFO.allOutTradeNo.length != 0) {
                //console.log("有需要补发数据", cc.fx.GameConfig.GM_INFO.allOutTradeNo);

                // 递归函数，按顺序处理每个订单
                const processOrder = (index: number) => {
                    if (index >= cc.fx.GameConfig.GM_INFO.allOutTradeNo.length) {
                        return; // 所有订单处理完成
                    }

                    let order = cc.fx.GameConfig.GM_INFO.allOutTradeNo[index];
                    console.log("需要补发数据", order);
                    if (order.itemid == "gold_1" || order.itemid == "gold_2" || order.itemid == "gold_3"
                        || order.itemid == "gold_4" || order.itemid == "gold_5" || order.itemid == "gold_6"
                    ) {
                        this.openLoad();
                        console.log("补发名称:", order.itemid);
                        let productId = order.itemid;
                        Utils.setPayInfo(
                            (res) => {
                                console.log("设置轮训结果:", res);
                                this.closeLoad();
                                if (res.code === 1) {
                                    console.log("7.14_________正式发货");
                                    let coinTemp = 0;
                                    if (order.itemid == "gold_1") { coinTemp = 1200; }
                                    else if (order.itemid == "gold_2") { coinTemp = 8000; }
                                    else if (order.itemid == "gold_3") { coinTemp = 16000; }
                                    else if (order.itemid == "gold_4") { coinTemp = 32000; }
                                    else if (order.itemid == "gold_5") { coinTemp = 100000; }
                                    else if (order.itemid == "gold_6") { coinTemp = 240000; }
                                    let title = "充值补发奖励金币：" + coinTemp;
                                    MiniGameSdk.API.showToast(title);
                                    cc.fx.GameTool.shopBuy(productId);
                                    console.log("充值成功获得金币");
                                } else {
                                    MiniGameSdk.API.showToast("网络异常，充值奖励将在登录后再次发放");
                                    const dataFail4 = {
                                        outTradeNo: Utils.outTradeNo,
                                        price: parseInt(order.goodsPrice),
                                        payment_name: productId,
                                        payment_num: 1,
                                        type: systemType,
                                        fail_reason: "成功付款，但是发货时请求服务器失败，重新进入游戏后轮训发货又失败",
                                    }
                                    cc.fx.GameTool.shushu_Track("payment_fail", dataFail4);
                                }
                                NumberToImage.numberToImageNodes(cc.fx.GameConfig.GM_INFO.coin, 30, 15, "coin_", this.coin, true);
                                this.updateCoin();

                                // 处理下一个订单
                                processOrder(index + 1);
                            }, order.outTradeNo);
                    } else {
                        // 如果当前订单不处理，直接处理下一个订单
                        processOrder(index + 1);
                    }
                };

                // 从第一个订单开始处理
                processOrder(0);
            }
        }
    }

    openLoad() {
        this.node.getChildByName("Loading").active = true;
        this.node.getChildByName("Loading").getChildByName("load").stopAllActions();
        this.node.getChildByName("Loading").getChildByName("load").runAction(cc.rotateTo(2, 1080).repeatForever());
    }

    closeLoad() {
        this.node.getChildByName("Loading").active = false;
    }
    // update (dt) {}
}
