import {_decorator, Button, instantiate, Label, math, Node, Prefab, Sprite} from 'cc';
import Scene from "db://assets/Module/Scene";
import {observer, render} from "../store/decorators";
import {sendWebNet, sendWebNetWithToken, WebNetName} from "db://assets/Scripts/Utils/WebNet/WebNet";
import { backScene, changeScene, showPanel, showShareGuide, showToast } from "db://assets/Module/UIFast";
import {HomeScene} from "db://assets/Scripts/Scenes/HomeScene";
import {getUrlParams} from "../Utils/WebNet/web/webTools";
import OpenLuckyPanel from "../Panels/OpenLuckyPanel";
import shareStore from "../store/shareStore";
import GetPrize from "db://assets/Scripts/Panels/GetPrize";
import store from "../store/store";
import { VList } from "../../Test/VList";
import { _asyncThrottle } from "../Utils/Utils";
import { unwatchPageVisibility, watchPageVisibility } from "../Utils/pageVisibilityNotify";

const {ccclass, property} = _decorator;

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

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


    @property(Node) backBtn: Node = null;
    @property(Node) noactive_silverBag: Node = null;
    @property(Node) notactive_goldBag: Node = null;
    @property(Node) notactive_diamondBag: Node = null;
    @property(Node) notactive_toEarn: Node = null;
    @property(Node) Node_sliver: Node = null;
    @property(Node) Node_gold: Node = null;
    @property(Node) Node_diamond: Node = null;
    @property(Node) Node_earn: Node = null;

    @property(Node) active_silverBag: Node = null;
    @property(Node) active_goldBag: Node = null;
    @property(Node) active_diamondBag: Node = null;
    @property(Node) active_toEarn: Node = null;


    @property(Node) Sliver_One_Btn: Node = null;
    @property(Node) Sliver_Five_Btn: Node = null;
    @property(Node) Gold_One_Btn: Node = null;
    @property(Node) Gold_Five_Btn: Node = null;
    @property(Node) Diamond_One_Btn: Node = null;
    @property(Node) Diamond_Five_Btn: Node = null;

    @property(Label) Label_num: Label = null;
    @property(Label) Label_five_gold: Label = null;
    @property(Label) Label_one_gold: Label = null;
    @property(Label) Label_five_diamond: Label = null;
    @property(Label) Label_one_diamond: Label = null;

    //福袋轮播图
    @property(Prefab) prize_list: Prefab = null;

    @property(VList) sliverList: VList = null;
    @property(VList) goldList: VList = null;
    @property(VList) diamondList: VList = null;


    //赚福袋任务界面
    @property(Prefab) earn_list: Prefab = null;
    @property(Node) content: Node = null;


    onLoad() {
        this.backBtn.on(Button.EventType.CLICK, this.backbtn, this);
        this.noactive_silverBag.on(Button.EventType.CLICK, this.silverBag, this);
        this.notactive_goldBag.on(Button.EventType.CLICK, this.goldBag, this);
        this.notactive_diamondBag.on(Button.EventType.CLICK, this.diamondBag, this);
        this.notactive_toEarn.on(Button.EventType.CLICK, this.toEarn, this);

        this.Sliver_One_Btn.on(Button.EventType.CLICK, this.SliverOneBtn, this);
        this.Sliver_Five_Btn.on(Button.EventType.CLICK, this.SliverFiveBtn, this);
        this.Gold_One_Btn.on(Button.EventType.CLICK, this.GoldOneBtn, this);
        this.Gold_Five_Btn.on(Button.EventType.CLICK, this.GoldFiveBtn, this);
        this.Diamond_One_Btn.on(Button.EventType.CLICK, this.DiamondOneBtn, this);
        this.Diamond_Five_Btn.on(Button.EventType.CLICK, this.DiamondFiveBtn, this);

        //赚福袋任务界面
        // this.Task1_invite_btn.on(Button.EventType.CLICK, this.DiamondFiveBtn, this);


    }

    TaskInfo = {}

    @render
    render() {
        const {
            remainBagSilverNum,
            bagSilverToGold,
            bagSilverToDiamond,
            bagPrizeVO
        } = store.bagInfo;

        this.Label_num.string = `数量：${remainBagSilverNum}`;
        this.Label_one_gold.string = `花费${bagSilverToGold}个银福袋`;
        this.Label_five_gold.string = `花费${bagSilverToGold * 5}个银福袋`;
        this.Label_one_diamond.string = `花费${bagSilverToDiamond}个银福袋`;
        this.Label_five_diamond.string = `花费${bagSilverToDiamond * 5}个银福袋`;
    }

    async start() {
        this.Node_sliver.active = true;
        this.Node_gold.active = false;
        this.Node_diamond.active = false;
        this.Node_earn.active = false;
        this.active_silverBag.active = true;
        this.active_goldBag.active = false;
        this.active_diamondBag.active = false;
        this.active_toEarn.active = false;

        const suc = await store.getBagInfo();

        if (!suc) return;

        const { bagPrizeVO } = store.bagInfo;

        const updateItem = (node, data) => {
            node.getChildByName("prizeImg")
                .getComponent(Sprite).spriteFrame = data.prizeImg;

            node.getChildByName("numBg")
                .getChildByName("num")
                .getComponent(Label).string = `X${data.sendCount}`;

            node.getChildByName("prizeName")
                .getComponent(Label).string = data.prizeName;
        };

        bagPrizeVO.map((item) => {
            //银福袋轮播
            if (item.type === 1) {
                this.sliverList.init(item.prizeVOList, updateItem);
            }

            //金福袋轮播
            if (item.type === 2) {
                this.goldList.init(item.prizeVOList, updateItem);
            }

            //钻石福袋轮播
            if (item.type === 3) {
                this.diamondList.init(item.prizeVOList, updateItem);
            }
        })


        //赚福袋任务界面
        this.updateTask();

        watchPageVisibility(this.pageVisibilityNotify);
    }

    protected onDestroy() {
        unwatchPageVisibility(this.pageVisibilityNotify);
    }

    pageVisibilityNotify = (visible: boolean) => {
        if(visible){
            this.updateTask();
        }
    }

    updateTask = async () => {
        const {success: TaskSuccess, data: TaskData} = await store.getTaskInfo();
        if (!TaskSuccess) return
        this.TaskInfo = TaskData
        console.log(TaskData)
        let item = TaskData.item
        console.log(item)
        this.content.removeAllChildren();
        item.map((item: any, index: any) => {

            const EarnList = instantiate(this.earn_list)
            this.content.addChild(EarnList)
            const Label_task_name = EarnList.getChildByName("Label_task_name")


            if (item.code == "task_invite"){
                Label_task_name.getComponent(Label).string = item.title

                const activeBtn = EarnList.getChildByName("active_btn")
                const activeLabel = activeBtn.getChildByName("ActiveLabel")
                activeLabel.getComponent(Label).string = "去邀请"
            }else{
                Label_task_name.getComponent(Label).string = `${item.title}(${item.completedSize}/${item.intervalLimitSize})`
            }

            const bag_num = EarnList.getChildByName("bag_num")
            bag_num.getComponent(Label).string = item.subTitle

            const activeBtn = EarnList.getChildByName("active_btn")
            const activeLabel = activeBtn.getChildByName("ActiveLabel")
            // activeLabel.getComponent(Label).string = item.buttonText

            const notActiveBtn = EarnList.getChildByName("notActive_btn")
            const notActiveLabel = notActiveBtn.getChildByName("notActiveLabel")
            // notActiveLabel.getComponent(Label).string = item.buttonText


            //判断是否完成，完成则置灰，不完成置亮
            //邀请任务没有【已完成】的状态，一直都是【去邀请】高亮展示
            if (item.completedSize >= item.intervalLimitSize && item.code != "task_invite") {
                activeBtn.active = false
                notActiveBtn.active = true
            } else {
                activeBtn.active = true
                notActiveBtn.active = false
            }

            //去完成任务
            activeBtn.on(Button.EventType.CLICK, () => this.clickTofinish(item.id, item.code, item.jumpUrl))
        })
    }

    // 点击返回按钮
    backbtn = _asyncThrottle(async () => {
        // changeScene(HomeScene)
        await backScene();
    });

    //银福袋按钮
    silverBag() {
        this.Node_sliver.active = true;
        this.Node_gold.active = false;
        this.Node_diamond.active = false;
        this.Node_earn.active = false;

        this.active_silverBag.active = true;
        this.active_goldBag.active = false;
        this.active_diamondBag.active = false;
        this.active_toEarn.active = false;
    }

    //金福袋按钮
    goldBag() {
        this.Node_sliver.active = false;
        this.Node_gold.active = true;
        this.Node_diamond.active = false;
        this.Node_earn.active = false;

        this.active_silverBag.active = false;
        this.active_goldBag.active = true;
        this.active_diamondBag.active = false;
        this.active_toEarn.active = false;
    }

    //钻石福袋按钮
    diamondBag() {
        this.Node_sliver.active = false;
        this.Node_gold.active = false;
        this.Node_diamond.active = true;
        this.Node_earn.active = false;

        this.active_silverBag.active = false;
        this.active_goldBag.active = false;
        this.active_diamondBag.active = true;
        this.active_toEarn.active = false;
    }

    //去赚福袋按钮
    toEarn() {
        this.Node_sliver.active = false;
        this.Node_gold.active = false;
        this.Node_diamond.active = false;
        this.Node_earn.active = true;

        this.active_silverBag.active = false;
        this.active_goldBag.active = false;
        this.active_diamondBag.active = false;
        this.active_toEarn.active = true;
    }

    //银福袋开启一个
    SliverOneBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < 1) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 1, type: "sliver"});
        }
    });

    //银福袋开启五个
    SliverFiveBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < 5) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 5, type: "sliver"});
        }
    });

    //金福袋开启一个
    GoldOneBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < store.bagInfo.bagSilverToGold) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 1, type: "gold"})
        }
    });

    //金福袋开启五个
    GoldFiveBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < store.bagInfo.bagSilverToGold * 5) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 5, type: "gold"})
        }
    });

    //钻石福袋开启五个
    DiamondOneBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < store.bagInfo.bagSilverToDiamond) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 1, type: "diamond"});
        }
    });

    //钻石福袋开启一个
    DiamondFiveBtn = _asyncThrottle(async () => {
        if (store.bagInfo.remainBagSilverNum < store.bagInfo.bagSilverToDiamond * 5) {
            showToast("福袋数量不足");
        } else {
            await showPanel(OpenLuckyPanel, {num: 5, type: "diamond"});
        }
    });


    //去赚福袋任务
    async clickTofinish(taskId, taskCode, jumpUrl) {

        if (taskCode == "task_invite") {
            shareStore.doShare();
        } else {
            // const {success, data} = await sendWebNetWithToken(WebNetName.finishTask, {taskId, taskCode})
            // if (!success) return

            if (jumpUrl.indexOf("http") > -1) {
                window.location.href = jumpUrl
            } else {
                if (jumpUrl.indexOf("new-year-festival") > -1) {
                    // @ts-ignore
                    wx.miniProgram.reLaunch({
                        url: `${jumpUrl}?taskId=${getUrlParams("taskToken")}`,
                        success: () => {
                            console.log("new-year-festival跳转成功");
                        },
                        fail: (e) => {
                            console.error("new-year-festival跳转失败", e);
                        }
                    });
                } else {
                    // @ts-ignore
                    wx.miniProgram.navigateTo({
                        url: `${jumpUrl}?taskId=${getUrlParams("taskToken")}`,
                        success: () => {
                            console.log("跳转成功");
                        },
                        fail: (e) => {
                            console.error("跳转失败", e);
                        }
                    });
                }
            }
        }
    }

}

