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

import JiaZai from "../../Script/JiaZai";
import Utils from "../../Script/module/Pay/Utils";
import NumberToImage from "../../Script/NumberToImage";
import { MiniGameSdk } from "../../Script/Sdk/MiniGameSdk";

// import JiaZai from "./JiaZai";
// import Utils from "./module/Pay/Utils";
// import NumberToImage from "./NumberToImage";
// import { MiniGameSdk } from "./Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DailyQuests extends cc.Component {

    @property(cc.Node)
    content: cc.Node = null;
    //月卡按钮切换
    @property(cc.Node)
    getBtn: cc.Node = null;

    public juwai = false;
    btn_Touch: boolean = false;

    private iosPrice: number = 0;
    private iosProductId: string = "";
    private iosCount: number = 1;
    public home: number = 0;
    public touchStart: boolean = false;
    public reward: boolean = false;

    onLoad() {
        this.btn_Touch = true;
        // 检测微信小游戏切到后台
        this.home = 0;
    }



    start() {
        // this.init();
    }
    init(data) {
        cc.fx.GameConfig.GM_INFO.tasks.levelPass = data["levelPass"];
        cc.fx.GameConfig.GM_INFO.tasks.share = data["share"];
        cc.fx.GameConfig.GM_INFO.tasks.useEnergy = data["useEnergy"];
        cc.fx.GameConfig.GM_INFO.tasks.useProp = data["useProp"];
        this.touchStart = true;
        this.reward = false;
        // 一键领取按钮状态
        this.getBtn.active = false;
        this.node.getChildByName("finishi").active = false;
        // 通过关卡已经领取
        for (let i = this.content.children.length - 1; i >= 0; i--) {
            const child = this.content.children[i];
            // 根据索引匹配不同任务类型
            if (
                (i === 0 && data.levelPass.state === 2) ||
                (i === 1 && data.share.state === 2) ||
                (i === 2 && data.useEnergy.state === 2) ||
                (i === 3 && data.useProp.state === 2)
            ) {
                child.removeFromParent();
            }
        }

        // 对剩余节点进行排序 - state == 1的排在上面
        const children = this.content.children;
        children.sort((a, b) => {
            const aName = a.name;
            const bName = b.name;
            const aState = data[aName].state;
            const bState = data[bName].state;

            // state == 1的排前面
            if (aState === 1 && bState !== 1) return -1;
            if (aState !== 1 && bState === 1) return 1;
            return 0;
        });

        // 重新设置节点顺序
        for (let i = 0; i < children.length; i++) {
            children[i].setSiblingIndex(i);
        }

        // 强制更新布局
        this.content.getComponent(cc.Layout).updateLayout();
        // 检查是否有未领取的任务
        if (this.content.children.length == 0) {
            this.node.getChildByName("finishi").active = true;
        } else {
            for (let j = 0; j < this.content.children.length; j++) {
                let child = this.content.children[j];
                child.getChildByName("progress").getComponent(cc.Sprite).fillRange = 0;
                child.getChildByName("get").active = false;
                child.getChildByName("jump").active = false;
                let name = this.content.children[j].name;
                if (data[name].value > data[name].target) {
                    data[name].value = data[name].target;
                }
                let progress = data[name].value / data[name].target;
                if (data[name].state == 1 && progress == 1) {
                    child.getChildByName("get").active = true;
                    child.getChildByName("jump").active = false;
                    setTimeout(() => {
                        this.getBtn.active = true;
                    }, 0);
                }
                else if (data[name].state == 0) {
                    child.getChildByName("get").active = false;
                    child.getChildByName("jump").active = true;
                }
                let time = 0.3;
                if (progress == 0) time = 0;
                cc.tween(child.getChildByName("progress").getComponent(cc.Sprite))
                    .delay(j * 0.1)
                    .to(time, { fillRange: progress })
                    .start();
                NumberToImage.numberToImageNodes(data[name].value, 40, 15, "coin_", child.getChildByName("target"), false);
                NumberToImage.numberToImageNodes(data[name].target, 40, 15, "coin_", child.getChildByName("total"), false);
            }
        }

    }
    //入场动画
    setAction() {
        this.node.getChildByName("gold_1").getComponent(sp.Skeleton).setAnimation(0, "animation", false);
        setTimeout(() => {
            this.node.getChildByName("qipao3").active = true;
            this.node.getChildByName("qipao3").getComponent(sp.Skeleton).setAnimation(0, "animation", false);
            cc.tween(this.node.getChildByName("propBg1"))
                .delay(0.1)
                .to(0.2, { opacity: 255 })
                .start();
        }, 400);
        setTimeout(() => {
            this.node.getChildByName("qipao2").active = true;
            this.node.getChildByName("qipao2").getComponent(sp.Skeleton).setAnimation(0, "animation", false);
            cc.tween(this.node.getChildByName("propBg2"))
                .delay(0.1)
                .to(0.2, { opacity: 255 })
                .start();
        }, 600);
        setTimeout(() => {
            this.node.getChildByName("gold_2").active = true;
            this.node.getChildByName("qipao1").active = true;
            this.node.getChildByName("qipao1").getComponent(sp.Skeleton).setAnimation(0, "animation", false);
            cc.tween(this.node.getChildByName("propBg3"))
                .delay(0.1)
                .to(0.2, { opacity: 255 })
                .start();
        }, 800);
        setTimeout(() => {
            // this.node.getChildByName("gold_2").active = true;
            this.node.getChildByName("baoxiang").active = true;
        }, 1000);
    }

    //购买月卡
    openReward(name, res) {
        let data = null;
        if (name == "levelPass") {
            data = [
                { type: "coin", count: 100 },
                { type: "freeze", count: 2 }
            ]
            let data2 = {
                id: 0,
                status: "claim"
            }
            cc.fx.GameTool.shushu_Track("daily_task", data2);
        }
        else if (name == "useProp") {
            data = [
                { type: "hammer", count: 1 }
            ]
            let data2 = {
                id: 3,
                status: "claim"
            }
            cc.fx.GameTool.shushu_Track("daily_task", data2);
        }
        else if (name == "useEnergy") {
            data = [
                { type: "coin", count: 100 },
                { type: "magic", count: 1 }
            ]
            let data2 = {
                id: 2,
                status: "claim"
            }
            cc.fx.GameTool.shushu_Track("daily_task", data2);
        }
        else if (name == "share") {
            data = [
                { type: "infinite_health", count: 900 },
            ]
            let data2 = {
                id: 1,
                status: "claim"
            }
            cc.fx.GameTool.shushu_Track("daily_task", data2);
        }
        else if (name == "all") {
            data = res;
        }
        console.log("获得任务奖励", data);
        let shuju = {
            "coin": 0,
            "freeze": 0,
            "hammer": 0,
            "magic": 0,
            "infinite_health": 0,
        }
        for (let i = 0; i < data.length; i++) {
            let type = data[i].type;
            let count = data[i].count;
            shuju[type] += count;
        }
        let propData = {
            "freeze": shuju.freeze || 0,
            "hammer": shuju.hammer || 0,
            "magic_wand": shuju.magic || 0,
            "price": 0
        }
        this.getShopProp(propData);
        if (shuju.coin > 0) {
            cc.fx.GameTool.changeCoin(shuju.coin);
        }
        if (shuju.infinite_health > 0) {
            cc.fx.GameTool.setUserPowerTime(shuju.infinite_health);
        }

        const canvasTemp = cc.find("Canvas"); // 假设 Canvas 节点
        if (canvasTemp) {
            const JiaZai = canvasTemp.getComponent("JiaZai");
            if (JiaZai) {
                JiaZai.openRewardWindow(data);
                if (shuju.coin > 0) {
                    JiaZai.updateCoin();
                }
                if (shuju.infinite_health > 0) {
                    JiaZai.updatePower();
                }
            }
        }
    }

    setReward(id) {
    }

    closeDailyQuests() {
        this.node.active = false;
        const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
        const jiazaiComp = jiazaiNode.getComponent(JiaZai);
        if (jiazaiComp) {
            jiazaiComp.checkTasks();
        }
    }

    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());
    }

    openConfirmBox() {
        this.closeLoad();
        this.node.getChildByName("ConfirmBox").active = true;
    }
    closeConfirmBox() {
        this.node.getChildByName("ConfirmBox").active = false;
    }

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

    //点击去完成
    clickBtn(event, data) {
        if (data == "useProp" || data == "levelPass" || "useEnergy" == data) {
            this.closeDailyQuests();
            const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
            const jiazaiComp = jiazaiNode.getComponent(JiaZai);
            if (jiazaiComp) {
                jiazaiComp.startGame();
            }
        }
        else if (data == "share") {
            let img = "https://mmocgame.qpic.cn/wechatgame/OiaWk33I6QjgWiatrb5YVUq2p0QRmQgO6rLUWxEQDZ4ib9Ny4Pr8iaHnHI6WdxibY2nPL/0";
            if (Math.random() < 0.5) {
                img = "https://mmocgame.qpic.cn/wechatgame/CG5xBibollws251aYD4msEPWCiafrcn4Fgtic4T2wME6sWmdfAUtfibgsWoxm59VadDD/0";
            }
            const shareParams = {
                title: '如果你突然打了个喷嚏，那一定是我在等你帮忙过关!', // 分享标题
                imageUrl: img // 分享图片链接
            };
            // 调用微信分享 API
            if (cc.sys.platform === cc.sys.WECHAT_GAME) {
                //@ts-ignore
                wx.shareAppMessage(shareParams);
                setTimeout(() => {
                    this.closeDailyQuests();
                }, 500);
                const jiazaiNode = cc.find("Canvas"); // 假设 JiaZai 挂在 Canvas 节点
                const jiazaiComp = jiazaiNode.getComponent(JiaZai);
                console.log("分享出去了");
                if (cc.fx.GameConfig.GM_INFO.tasks.share.value < cc.fx.GameConfig.GM_INFO.tasks.share.target) {
                    cc.fx.GameConfig.GM_INFO.tasks.share.value += 1;
                    cc.fx.GameTool.setDailyQuestInfo((data) => {
                        if (data.code == 1) {
                            if (jiazaiComp) {
                                setTimeout(() => {
                                    jiazaiComp.openDailyQuests();
                                }, 1000);
                            }
                        }
                    });
                    if (cc.fx.GameConfig.GM_INFO.tasks.share.value == cc.fx.GameConfig.GM_INFO.tasks.share.target) {
                        let data = {
                            id: 1,
                            status: "complete"
                        }
                        cc.fx.GameTool.shushu_Track("daily_task", data);
                    }
                }
            }
        }
    }

    getReward(event, data) {
        if (this.touchStart == false) {
            return;
        }
        this.touchStart = false;
        this.reward = true;
        let shuju = [data];
        Utils.getDailyQuestReward(shuju, (res) => {
            this.touchStart = true;
            this.reward = false;
            if (res.code == 1) {
                let dataNode = null;
                for (let i = 0; i < this.content.children.length; i++) {
                    if (this.content.children[i].name === data) {
                        dataNode = this.content.children[i];
                        break;
                    }
                }
                dataNode.getChildByName("get").active = false;
                cc.tween(dataNode)
                    .to(0.4, { x: dataNode.x - 1000, opacity: 50 })
                    .call(() => {
                        this.openReward(dataNode.name, null);
                        this.touchStart = true;
                        dataNode.removeFromParent();
                        this.content.getComponent(cc.Layout).updateLayout();
                        this.checkGetReward();
                    })
                    .start();
            }
            else {
                MiniGameSdk.API.showToast("网络异常，领取奖励失败");
            }
        })
        setTimeout(() => {
            if (this.reward == true && this.touchStart == false) {
                this.touchStart = true;
            }
        }, 5000);
    }

    getAllReward() {
        if (this.touchStart == false) {
            return;
        }
        this.touchStart = false;
        this.reward = true;
        let shuju = [];
        for (let i = 0; i < this.content.children.length; i++) {
            let dataNode = this.content.children[i];
            if (dataNode.getChildByName("get").active == true) {
                shuju.push(dataNode.name);
            }
        }
        console.log("准备上传的任务", shuju);
        Utils.getDailyQuestReward(shuju, (res) => {
            this.touchStart = true;
            this.reward = false;
            if (res.code == 1) {
                let data = [
                    { type: "coin", count: 0 },
                    { type: "freeze", count: 0 },
                    { type: "hammer", count: 0 },
                    { type: "magic", count: 0 },
                    { type: "infinite_health", count: 0 },
                ]
                for (let i = 0; i < this.content.children.length; i++) {
                    let dataNode = this.content.children[i];
                    if (dataNode.getChildByName("get").active == true) {
                        dataNode.getChildByName("get").active = false;
                        if (dataNode.name == "levelPass") {
                            data[0].count += 100;
                            data[1].count += 2;
                            let data2 = {
                                id: 0,
                                status: "claim"
                            }
                            cc.fx.GameTool.shushu_Track("daily_task", data2);
                        }
                        else if (dataNode.name == "useProp") {
                            data[2].count += 1;
                            let data2 = {
                                id: 3,
                                status: "claim"
                            }
                            cc.fx.GameTool.shushu_Track("daily_task", data2);
                        }
                        else if (dataNode.name == "useEnergy") {
                            data[0].count += 100;
                            data[3].count += 1;
                            let data2 = {
                                id: 2,
                                status: "claim"
                            }
                            cc.fx.GameTool.shushu_Track("daily_task", data2);
                        }
                        else if (dataNode.name == "share") {
                            data[4].count += 900;
                            let data2 = {
                                id: 1,
                                status: "claim"
                            }
                            cc.fx.GameTool.shushu_Track("daily_task", data2);
                        }
                        cc.tween(dataNode)
                            .to(0.4, { x: dataNode.x - 1000, opacity: 50 })
                            .call(() => {
                                this.touchStart = true;
                                dataNode.removeFromParent();
                                this.content.getComponent(cc.Layout).updateLayout();
                                this.checkGetReward();
                            })
                            .start();
                    }
                }
                for (let j = 0; j < data.length; j++) {
                    if (data[j].count == 0) {
                        data.splice(j, 1);
                        j--;
                    }
                }
                this.openReward("all", data);
            }
            else {
                MiniGameSdk.API.showToast("网络异常，领取奖励失败");
            }
        })
        setTimeout(() => {
            if (this.reward == true && this.touchStart == false) {
                this.touchStart = true;
            }
        }, 5000);
    }

    checkGetReward() {
        this.getBtn.active = false;
        if (this.content.children.length == 0) {
            this.getBtn.active = false;
            this.node.getChildByName("finishi").active = true;
        }
        else {
            for (let j = 0; j < this.content.children.length; j++) {
                let child = this.content.children[j];
                if (child.getChildByName("get").active) {
                    this.getBtn.active = true;
                    break;
                }
            }
        }
    }

    getShopProp(propData) {
        //@ts-ignore
        if (typeof wx !== 'undefined' && wx !== null) {
            const num = 0;
            //console.log("_________道具增加的数量为:", num);
            cc.fx.GameConfig.GM_INFO.freezeAmount += propData.freeze;
            cc.fx.GameConfig.GM_INFO.hammerAmount += propData.hammer;
            cc.fx.GameConfig.GM_INFO.magicAmount += propData.magic_wand;
            cc.fx.GameTool.setUserProp(0, num, (data) => {
            })
            const data1 = {
                change_reason: "quests",
                id: 2001,
                num: propData.freeze,
                compensate: false
            }
            cc.fx.GameTool.shushu_Track("resource_get", data1);
            const data2 = {
                change_reason: "quests",
                id: 2002,
                num: propData.hammer,
                compensate: false
            }
            cc.fx.GameTool.shushu_Track("resource_get", data2);
            const data3 = {
                change_reason: "quests",
                id: 2003,
                num: propData.magic_wand,
                compensate: false
            }
            cc.fx.GameTool.shushu_Track("resource_get", data3);
        }
    }

    onDestroy() {

    }

    update() {

    }
}
