import { GDispatcher } from './../../libs/tc/util/GDispatcher';
import { IExposureData } from './../../libs/tw/data/common/IExposureData';
import { Buried } from './../../libs/tw/util/Buried';
import { TwFun } from './../../libs/tw/util/TwFun';
import { NetManager } from './../../libs/tw/manager/NetManager';
import { GCache } from './../../libs/tc/util/GCache';
import { PetsInfoData } from './../../libs/tw/data/pets/PetsInfoData';
import { DataManager } from './../../libs/tw/manager/DataManager';
import { wait } from './../GameConst';
import { ModuleTypes } from './../types/sceneTypes';
import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import Waiting from '../waiting/Waiting';
import GameConst from '../GameConst';
import Soup from './Soup';
import { SoupTypes } from './SoupTypes';
import ToastCtrl from '../ctrls/toastCtrl';
import DailyTask from './DailyTask';
import NetModel from '../NetModel';
import NetConst from '../NetConst';
import Exchange from './Exchange';
import MovieClipCtrl from '../ctrls/MovieClipCtrl';

export default class MainScene extends Scene {

    public get skinKey() { return "Main" }

    public mainBg: eui.Image;
    public title: eui.Image;
    public firewood: eui.Image;
    public fire0: eui.Image;
    public fire1: eui.Image;
    public fire2: eui.Image;
    public fire3: eui.Image;
    public mainPot: eui.Image;
    public userInfoBg: eui.Image;
    public ruleBtn: eui.Button;
    public recordBtn: eui.Button;
    public exchangeBtn: eui.Button;
    public taskBtn: eui.Button;
    public rewardCarousel: eui.Group;
    public winnerList: eui.Group;
    public msgList: eui.Group;
    public msgListMask: eui.Rect;
    public fireWoodsTxt: eui.Label;
    public coinTxt: eui.Label;
    public mainPotGroup: eui.Group;
    public pot0: eui.Group;
    public addSoup0: eui.Image;
    public pot1: eui.Group;
    public addSoup1: eui.Image;
    public pot2: eui.Group;
    public addSoup2: eui.Image;
    public pot3: eui.Group;
    public addSoup3: eui.Image;
    public isolatedLayer: eui.Rect;
    public TaskGroup: eui.Group;
    public collectPanelBg: eui.Image;
    public closeTaskBtn: eui.Button;
    public taskScroller: eui.Scroller;
    public firstSignTask: eui.Component;
    public dailySignTask: eui.Component;
    public continueSignTask: eui.Component;
    public consumeTask: eui.Component;
    public exchangeTask: eui.Component;
    public ExchangeGroup: eui.Group;
    public exchangeBg: eui.Image;
    public closeExchangeBtn: eui.Button;
    public exchangeStoreBtnBg: eui.Image;
    public exchangeListBtnBg: eui.Image;
    public exchangeableList: eui.Group;
    public randomDrawBtn: eui.Image;
    public exchangeScroller: eui.Scroller;
    public exchangeList: eui.Group;
    public storeList: eui.Group;
    public spicyNumBg: eui.Image;
    public tomatoNumBg: eui.Image;
    public threefreshNumBg: eui.Image;
    public mushroomNumBg: eui.Image;
    public tomatoNum: eui.Label;
    public spicyNum: eui.Label;
    public mushroomNum: eui.Label;
    public threefreshNum: eui.Label;
    public exchangeListBtn: eui.Rect;
    public exchangeStoreBtn: eui.Rect;
    public touchMask: eui.Rect;
    public resignGroup: eui.Group;
    public resignBtn: eui.Button;
    public guideGroup0: eui.Group;
    public guideBtn0: eui.Rect;
    public guideTips0: eui.Image;
    public finger0: eui.Image;
    public guideGroup1: eui.Group;
    public guideBtn1: eui.Rect;
    public guideTips1: eui.Image;
    public finger1: eui.Image;
    public preventLayer: eui.Rect;



    public dailyTask: DailyTask = new DailyTask(this);
    public exchange: Exchange = new Exchange(this);

    private pots = {
        //isEmpty 是否空锅 ， temperature 温度， type 种类, soup 汤底实例, isHeated 今天是否被加热过
        pot0: { isEmpty: true, temperature: 0, type: null, soup: null, isHeated: false, id: 0 }, pot1: { isEmpty: true, temperature: 0, type: null, soup: null, isHeated: false, id: 0 },
        pot2: { isEmpty: true, temperature: 0, type: null, soup: null, isHeated: false, id: 0 }, pot3: { isEmpty: true, temperature: 0, type: null, soup: null, isHeated: false, id: 0 }
    }

    public exposure = {
        "zhc": [[39, 1, 1], [216, 0]],
        "jch": [[39, 2, 1], [216, 0]],
        "xhgd": [[39, 3, 1], [216, 0]],
        "jrgd": [[39, 4, 1], [216, 0]],
        "xrqd": [[39, 5, 1], [216, 0]],
        "mrqd": [[39, 6, 1], [216, 0]],
        "lxqd": [[39, 7, 1], [216, 0]],
        "xfqwc": [[39, 8, 1], [216, 0]],
        "dhqwc": [[39, 8, 2], [216, 0]],
        "xfklq": [[39, 9, 1], [216, 0]],
        "dhklq": [[39, 9, 2], [216, 0]],
        "cp1dh": [[39, 10, 1], [216, 0]],
        "cp2dh": [[39, 10, 2], [216, 0]],
        "cp3dh": [[39, 10, 3], [216, 0]],
        "cjxhgd": [[39, 11, 1], [216, 0]],
        "cgzhcp": [[39, 12, 1], [216, 0]],
        "tjcp1": [[39, 13, 1], [216, 0]],
        "tjcp2": [[39, 13, 2], [216, 0]],
        "tjcp3": [[39, 13, 3], [216, 0]],
        "tjcp4": [[39, 13, 4], [216, 0]],
        "jrfb1": [[39, 14, 1], [216, 0]],
        "jrfb2": [[39, 14, 2], [216, 0]],
        "jrfb3": [[39, 14, 3], [216, 0]],
        "jrfb4": [[39, 14, 4], [216, 0]],
        "shfb1": [[39, 15, 1], [216, 0]],
        "shfb2": [[39, 15, 2], [216, 0]],
        "shfb3": [[39, 15, 3], [216, 0]],
        "shfb4": [[39, 15, 4], [216, 0]],
        "gdtc": [[39, 16, 1], [216, 0]],
    }

    public connectDpm(name: string): string {
        return window['CFG'].appId + '.' + this.exposure[`${name}`][0][0] + '.' + this.exposure[`${name}`][0][1] + '.' + this.exposure[`${name}`][0][2];
    }

    public connectDcm(name: string): string {
        return this.exposure[`${name}`][1][0] + '.' + window['signActId'] + '.' + window['signSkinId'] + '.' + this.exposure[`${name}`][1][1];
    }

    public createExposure(name: string, embedDomain = '//embedlog.duiba.com.cn'): IExposureData {
        const exposure: IExposureData = {
            dpm: this.connectDpm(name),
            dcm: this.connectDcm(name),
            consumerId: window['CFG'].consumerId,
            appId: window['CFG'].appId,
            domain: embedDomain
        };
        return exposure;
    }

    private soupPool: any[] = [];

    start() {
        Buried

        super.start();

        if (!DataManager.ins.getData("getPetsInfo") || !DataManager.ins.getData("getSignInfo")) {
            let data = { msg: "啊哦！网络异常\n请重新加载", type: 'reload' }
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
            return
        }

        // if (DataManager.ins.getData("getPetsInfo") && DataManager.ins.getData("getPetsInfo").data && DataManager.ins.getData("getPetsInfo").data.petOwner) {

        // }

        this.initUI()
        this.initBuired()
        this.dailySign();
        // this.initGuide();
        // let mask = GameConst.drawRect(70, 8, 670, 34);
        // this.winnerList.addChild(mask);
        // this.msgList.mask = mask;
        if (DataManager.ins.getData("winners") && DataManager.ins.getData("winners").data && DataManager.ins.getData("winners").data.length > 0) {
            let data = DataManager.ins.getData("winners").data;

            for (let i = 0; i < data.length - 1; i++) {
                let name = null;
                let prizeName = data[i].prizeName;
                if (data[i].nickname) {
                    let stars = "***";
                    let namesplit = data[i].nickname.split("");
                    if (namesplit.length > 2) {
                        let length = data[i].nickname.split("").length
                        // for (let i = 0; i < length - 2; i++) {
                        // stars += "*"
                        // }
                        name = data[i].nickname.split("")[0] + stars + data[i].nickname.split('')[data[i].nickname.split('').length - 1];
                    }
                    name = data[i].nickname.split("")[0] + stars + data[i].nickname.split('')[data[i].nickname.split('').length - 1];
                } else {
                    let stars = "***";
                    if (data[i].userId.split("").length > 2) {
                        // let length = data[i].nickname.split("").length
                        // for (let i = 0; i < length - 2; i++) {
                        //     stars += "*"
                        // }
                        name = data[i].userId.split("")[0] + stars + data[i].userId.split('')[data[i].userId.split('').length - 1];
                    }


                }

                if (name && prizeName) {
                    let msg = name + "成功获得了" + prizeName;
                    let label = new eui.Label();
                    label.size = 26;
                    label.verticalCenter = 0;
                    label.text = msg;
                    if (i == 0) {
                        label.x = 780;
                    } else {
                        label.x = 30 + this.msgPool[this.msgPool.length - 1].x + this.msgPool[this.msgPool.length - 1].width
                    }

                    this.msgList.addChild(label);
                    this.msgPool.push(label);
                }
            }
        } else {
            this.winnerList.y = -60;
        }
    }


    guide = false;
    isGuide() {
        // 是否拥有宠物
        const petOwner = DataManager.ins.getData("getPetsInfo").data.petOwner;
        if (!petOwner) {
            // 没有养过宠物，进行新手引导
            this.guide = true;
            this.initGuide();
        }
    }

    initGuide() {
        // 画第一个引导蒙层
        this.guideGroup0.visible = true;

        egret.Tween.get(this.finger0, { loop: true })
            .to({ scaleX: 0.9, scaleY: 0.9 }, 250)
            .to({ scaleX: 1, scaleY: 1 }, 250)

        egret.Tween.get(this.finger1, { loop: true })
            .to({ scaleX: 0.9, scaleY: 0.9 }, 250)
            .to({ scaleX: 1, scaleY: 1 }, 250)
    }

    initBuired() {
        // 召唤菜
        NetManager.ins.showLog(this.createExposure("zhc"));
        // 集柴火
        NetManager.ins.showLog(this.createExposure("jch"));
    }

    // 柴火实际上是宠物粮食
    private firewoods: number;
    // 捞币 实际上是积分
    private credits: number;
    updateCredits(firewoods?, credits?) {
        this.firewoods = firewoods ? firewoods : DataManager.ins.getData("getPetsInfo").data.foodNum;
        this.fireWoodsTxt.text = this.firewoods + "";

        this.credits = credits ? credits : DataManager.ins.getData("getSignInfo").credits;
        this.coinTxt.text = this.credits + ""

        console.log(this.firewoods, this.credits)
    }

    dailySign(isResign: boolean = false) {
        Waiting.instance.show();
        if (DataManager.ins.getData("getSignInfo") && DataManager.ins.getData("getSignInfo").signInfoVO && !DataManager.ins.getData("getSignInfo").signInfoVO.todaySigned) {
            // 今天没有签过到  进行签到操作
            NetConst.doSign(async (s) => {
                if (!s) {
                    // 签到失败
                    // 容错
                    Waiting.instance.hide();
                    this.showResign()
                    return
                }

                NetConst.getSignResult(
                    async (ss) => {

                        if (!ss || DataManager.ins.getData("getSignResult").creditsStatus == 1) {
                            Waiting.instance.hide();
                            ToastCtrl.instance.show("网络异常，签到奖励领取失败，请联系捞小秘~", 3000)
                        }
                        if (!DataManager.ins.getData("doSign").customInfo) {
                            ToastCtrl.instance.show("网络异常，签到奖励领取失败，请联系捞小秘~", 3000)
                        }
                        await Promise.all([NetModel.getPetsInfo(), NetModel.getSignInfo()]);
                        Waiting.instance.hide();
                        this.updateCredits(DataManager.ins.getData("getPetsInfo").data.foodNum, DataManager.ins.getData("getSignInfo").credits);
                        this.dailyTask.update()
                        this.clearTap(this.resignBtn, this.onTap_resignBtn);
                        egret.Tween.get(this.resignGroup)
                            .to({ y: -100 }, 500)
                            .call(() => {
                                this.resignGroup.visible = false;
                            })
                        // 连续签到天数
                        const continueDay = DataManager.ins.getData("doSign").signInfoVO.continueDay;
                        // 实际累积签到天数（包含补签）
                        const acmDay = DataManager.ins.getData("doSign").signInfoVO.acmDay;
                        // 签到奖励集合，类型加奖励 类型有：CONTINUE-连续奖励 CIRCLE-周期奖励 ACCUMULATE-累计奖励 FIRST_SIGN-首签奖励 FULL_SIGN-满签奖励 CONTINUE_ONCE-周期内连续奖励（单次）	

                        if (acmDay) {
                            if (acmDay == 1) {
                                // 第一天
                                PanelCtrl.instance.show(ModuleTypes.FIRST_SIGN_PRIZE_PANEL, this)
                            } else {
                                // 是否第七天
                                if (continueDay == 7) {
                                    PanelCtrl.instance.show(ModuleTypes.FULL_SIGN_PRIZE_PANEL, this)
                                } else {
                                    // 正常每日签到
                                    PanelCtrl.instance.show(ModuleTypes.SIGN_PRIZE_PANEL, this);
                                }
                            }
                        }
                    },
                    DataManager.ins.getData("doSign").logId,
                    () => {
                        return DataManager.ins.getData("getSignResult").creditsStatus == 0
                    })
            }, window["signActId"])
        } else {
            Waiting.instance.hide();
            if (isResign) {
                ToastCtrl.instance.show("今日已经签过到了~");
            }
            this.isGuide();

            egret.Tween.get(this.resignGroup)
                .to({ y: -100 }, 500)
                .call(() => {
                    this.resignGroup.visible = false;
                })
        }
    }

    showResign() {
        this.resignGroup.visible = true;
        egret.Tween.get(this.resignGroup)
            .set({ y: -100 })
            .to({ y: 0 }, 500)
        this.onTap(this.resignBtn, this.onTap_resignBtn);
    }
    onTap_resignBtn() {
        this.dailySign(true);
    }

    initUI() {
        const signData = DataManager.ins.getData("getSignInfo");
        const petsInfoData = DataManager.ins.getData("getPetsInfo") ? DataManager.ins.getData("getPetsInfo").data : null;
        this.log(signData)
        this.log(petsInfoData)


        this.dailyTask.init()
        if (petsInfoData && petsInfoData.pets && petsInfoData.pets.length > 0) {
            // 有领养过汤底  更新汤底的状态
            for (let i = 0; i < petsInfoData.pets.length; i++) {
                const idx = Number(petsInfoData.pets[i].identifier.split("_0")[1]) - 1;
                const level = petsInfoData.pets[i].petLevel + "";
                const feedCount = petsInfoData.pets[i].feedCount;
                const petId = petsInfoData.pets[i].id;
                let type = null;

                let soupIdx;
                let eleName;
                let eleNum;
                switch (petsInfoData.pets[i].petName) {
                    case "番茄锅":
                        type = SoupTypes.TOMATO;
                        soupIdx = 3;
                        eleName = "tomatoEle";
                        eleNum = 4;
                        break;
                    case "清油麻辣锅":
                        type = SoupTypes.SPICY;
                        soupIdx = 1;
                        eleName = "spicyEle";
                        eleNum = 8;
                        break;
                    case "菌菇锅":
                        type = SoupTypes.MUSHROOM;
                        soupIdx = 0;
                        eleName = "mushroomEle"
                        eleNum = 6;
                        break;
                    case "三鲜锅":
                        type = SoupTypes.THREEFRESH;
                        soupIdx = 2;
                        eleName = "threefreshEle";
                        eleNum = 13;
                        break;
                }
                // debugger
                let soup = new Soup(type);
                soup.idx = idx;
                this[`pot${idx}`].addChild(soup);
                this.pots[`pot${idx}`].soup = soup;
                this.pots[`pot${idx}`].type = type;
                this.pots[`pot${idx}`].id = petId;
                this.pots[`pot${idx}`].isEmpty = false;
                this.soupPool.push(soup);

                soup[`soupGroup${soupIdx}`].visible = true;
                soup[`soupGroup${soupIdx}`].scaleX = 1;
                soup[`soupGroup${soupIdx}`].scaleY = 1;
                // let bool = false;
                for (let i = 0; i < eleNum; i++) {
                    let ele = soup[`${eleName}${i}`];
                    ele.scaleX = 1;
                    ele.scaleY = 1;
                }
                soup.Thermometer.alpha = 1;
                let value = 0;
                switch (level) {
                    case "1":
                        value = 0;
                        break;
                    case "2":
                        value = 25;
                        break;
                    case "3":
                        value = 50;
                        break;
                    case "4":
                        value = 75;
                        break;
                    case "5":
                        value = 100;
                        break;
                }
                this.pots[`pot${idx}`].temperature = value;
                soup.Thermometer.value = value;
                soup.Thermometer['temperatureTxt'].text = value + "度";
                if (feedCount > 0) {
                    // 今天加过热了???
                    this.pots[`pot${idx}`].isHeated = true;
                } else {
                    // 今天未加热
                    if (level == "5") {
                        // 100度 待收获
                        this.pots[`pot${idx}`].temperature = 100;
                        // let fog = MovieClipCtrl.instance.getMovieClipByName(`fog_${idx}`);
                        // fog.x = -20;
                        // fog.y = -100;
                        // fog.play(-1)
                        // soup.addChildAt(fog, 4)
                    } else {

                    }
                }
                this.updateCurrTargetPots(idx).then(() => {
                    this.enableTap(true);
                })

                this.playSoupAni(soup, value)
            }
        }

        // 埋点
        for (let i = 0; i < 4; i++) {
            let pot = this.pots[`pot${i}`]
            if (!pot.isEmpty) {
                // 有锅底
                if (pot.temperature == 100) {
                    // 锅底达到100 
                    NetManager.ins.showLog(this.createExposure(`shfb${i + 1}`));
                } else {
                    if (!pot.isHeated) {
                        // 未加热
                        NetManager.ins.showLog(this.createExposure(`jrfb${i + 1}`));
                    }
                }
            } else {
                NetManager.ins.showLog(this.createExposure(`tjcp${i + 1}`))
            }
        }

        this.updateCredits();
        this.log(this.pots)
        this.exchange.updateExchangeList();
    }

    updateSoupIds() {
        if (DataManager.ins.getData("getPetsInfo") && DataManager.ins.getData("getPetsInfo").data && DataManager.ins.getData("getPetsInfo").data.pets.length > 0) {
            DataManager.ins.getData("getPetsInfo").data.pets.forEach(pet => {
                if (pet.identifier) {
                    let i = pet.identifier.split("_0")[1];
                    switch (i) {
                        case "1":
                            this.pots.pot0.id = pet.id;
                            break;
                        case "2":
                            this.pots.pot1.id = pet.id;
                            break;
                        case "3":
                            this.pots.pot2.id = pet.id;
                            break;
                        case "4":
                            this.pots.pot3.id = pet.id;
                            break;
                    }
                }

            });
        }
    }

    addSoup(idx) {
        this.log(this.currTargetSoupType);
        // this.initUI();
        this[`addSoup${idx}`].visible = false;
        let soup = new Soup(this.currTargetSoupType);
        soup.idx = idx;
        this[`pot${idx}`].addChild(soup);
        this.pots[`pot${idx}`].soup = soup;
        this.pots[`pot${idx}`].isEmpty = false;
        this.pots[`pot${idx}`].type = soup.type;
        this.soupPool.push(soup);
        this.log(this.pots)

        this.playPourAni(soup)
            .then(() => {
                if (this.guide) {
                    this.guideGroup1.visible = true;
                }
                wait(500).then(() => {

                    this.enableTap(true);
                    this.updateCurrTargetPots(idx).then(() => {
                        this.enableTap(true);
                    });

                })
            });
    }

    updateCurrTargetPots(idx?) {
        return new Promise(r => {
            let currTargetPot;
            let soup;
            let _idx = this.currTargetPotIdx || 0;
            if (idx) {
                _idx = idx
            }
            currTargetPot = this.pots[`pot${_idx}`];
            soup = this.pots[`pot${_idx}`].soup;
            // currTargetPot.isEmpty = false;
            if (currTargetPot.type == null) {
                currTargetPot.type = this.currTargetSoupType || null;
            }
            if (soup) {
                if (currTargetPot.temperature < 100) {
                    if (!currTargetPot.isHeated) {
                        if (soup.filter) {
                            soup.filter.visible = true;
                        }
                        this.showTips(soup.heatTips)
                            .then(() => {
                                for (let i = 0; i < 4; i++) {
                                    let sp = this.pots[`pot${i}`].soup;
                                    if (sp) {
                                        egret.Tween.removeTweens(sp.heatTips);
                                        egret.Tween.get(sp.heatTips, { loop: true })
                                            .set({ y: 146 })
                                            .to({ y: 146 - 16 }, 200)
                                            .to({ y: 146 }, 200)
                                            .call(() => {
                                                r();
                                            })
                                        egret.Tween.removeTweens(sp.collectTips);
                                        egret.Tween.get(sp.collectTips, { loop: true })
                                            .set({ y: 146 })
                                            .to({ y: 146 - 16 }, 200)
                                            .to({ y: 146 }, 200)
                                            .call(() => {
                                            })
                                    }
                                }

                            });
                    } else {
                        // 置灰
                        if (soup.filter) {
                            soup.filter.visible = true;
                        }
                        r();
                    }
                } else {
                    // 温度大于100
                    if (soup.filter) {
                        soup.filter.visible = true;
                    }
                    this.showTips(soup.collectTips)
                        .then(() => {
                            for (let i = 0; i < 4; i++) {
                                let sp = this.pots[`pot${i}`].soup;
                                if (sp) {
                                    egret.Tween.removeTweens(sp.heatTips);
                                    egret.Tween.get(sp.heatTips, { loop: true })
                                        .set({ y: 146 })
                                        .to({ y: 146 - 16 }, 200)
                                        .to({ y: 146 }, 200)
                                        .call(() => {
                                        })
                                    egret.Tween.removeTweens(sp.collectTips);
                                    egret.Tween.get(sp.collectTips, { loop: true })
                                        .set({ y: 146 })
                                        .to({ y: 146 - 16 }, 200)
                                        .to({ y: 146 }, 200)
                                        .call(() => {
                                            r();
                                        })
                                }
                            }
                        });
                }
            } else {
                r();
            }
        })

    }

    initEvents() {
        super.initEvents();
        window["shareCall"] = GDispatcher.dispatchEvent("shareCall")
        GDispatcher.addEvent("shareCall", () => { this.log(this) }, this)

        this.onTap(this.ruleBtn, this.onTap_ruleBtn);
        this.onTap(this.taskBtn, this.onTap_taskBtn);
        this.onTap(this.recordBtn, this.onTap_recordBtn);
        this.onTap(this.closeTaskBtn, this.onTap_closeTaskBtn);
        this.onTap(this.exchangeBtn, this.onTap_exchangeBtn);
        this.onTap(this.closeExchangeBtn, this.onTap_closeExchangeBtn);
        this.onTap(this.exchangeStoreBtn, this.onTap_exchangeStoreBtn);
        this.onTap(this.exchangeListBtn, this.onTap_exchangeListBtn);
        for (let i = 0; i < 4; i++) {
            this.onTap(this[`pot${i}`], this.onTap_pot);
        }
        this.onTap(this.guideBtn0, this.onTap_guideBtn0);
        this.onTap(this.guideBtn1, this.onTap_guideBtn1);
        this.onTap(this.randomDrawBtn, this.onTap_randomDrawBtn);
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }


    onTap_guideBtn0() {
        this.currTargetPotIdx = 0;
        this.currTargetSoupId = this.pots[`pot0`].id;
        let data = { scene: this, idx: 0 }
        PanelCtrl.instance.show(ModuleTypes.ADOPTSOUP_PANEL, data);
    }

    onTap_guideBtn1() {
        this.currTargetPotIdx = 0;
        this.currTargetSoupId = this.pots[`pot0`].id;
        PanelCtrl.instance.show(ModuleTypes.WARNING_PANEL, this)
    }

    onTap_ruleBtn() {
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    onTap_recordBtn() {
        let recordUrl = window['recordUrl'];
        if (recordUrl.indexOf("?") >= 0) {
            recordUrl += '&origins=' + window['collectRuleId'] + "03" + "," + window["plugDrawId"] + "01";
        } else {
            recordUrl += '?origins=' + window['collectRuleId'] + "03" + "," + window["plugDrawId"] + "01";
        }
        setTimeout(() => {
            window.location.reload()
        }, 1000);
        window.location.href = recordUrl;

    }

    onTap_taskBtn() {
        Waiting.instance.show();
        // 更新每日任务数据
        NetManager.ins.clickLog(this.createExposure("jch"));
        NetConst.taskList((s) => {
            Waiting.instance.hide();
            if (!s) {
                ToastCtrl.instance.show("任务状态查询失败，请重试～");
                return
            }
            this.isolatedLayer.visible = true;
            this.TaskGroup.visible = true;
            this.dailyTask.update();
            let targetHeight = Math.max(GameConst.stage.stageHeight * 2 / 3, 1000);
            this.TaskGroup.height = targetHeight;
            this.collectPanelBg.height = targetHeight;
            this.taskScroller.height = targetHeight - 300;
            egret.Tween.get(this.TaskGroup)
                .to({ y: GameConst.stage.stageHeight - targetHeight }, 400)
        }, window['CFG'].activityId)
    }

    onTap_closeTaskBtn() {
        this.isolatedLayer.visible = false;
        egret.Tween.get(this.TaskGroup)
            .to({ y: 1800 }, 400)
            .call(() => {
                this.TaskGroup.visible = false;
            })
    }

    onTap_exchangeBtn() {
        NetManager.ins.clickLog(this.createExposure("zhc"))
        Waiting.instance.show();
        // 更新兑换菜品数据
        NetConst.getCollectRule((s) => {
            Waiting.instance.hide();
            if (!s) {
                // 容错
                ToastCtrl.instance.show("网络异常，请重试~");
                return
            }
            this.isolatedLayer.visible = true;
            this.ExchangeGroup.visible = true;
            this.exchange.updateExchangeList();
            let targetHeight = Math.max(GameConst.stage.stageHeight * 2 / 3, 1000);
            this.ExchangeGroup.height = targetHeight;
            this.exchangeBg.height = targetHeight;
            this.exchangeScroller.height = targetHeight - 550;
            egret.Tween.get(this.ExchangeGroup)
                .to({ y: GameConst.stage.stageHeight - targetHeight }, 400)
        }, window['collectRuleId'])
    }

    onTap_closeExchangeBtn() {
        this.isolatedLayer.visible = false;
        egret.Tween.get(this.ExchangeGroup)
            .to({ y: 1800 }, 400)
            .call(() => {
                this.ExchangeGroup.visible = false;
            })
    }

    // 当前选中的锅
    public currTargetPotIdx: any;
    public currTargetSoupType: any;
    public currTargetSoupId: any;
    onTap_pot(e) {
        let point = { x: e.stageX - 47, y: e.stageY - 362, width: 20, height: 20 };
        // let idx = this.currTargetPotIdx;
        for (let i = 0; i < 4; i++) {
            if (GameConst.contain(this[`pot${i}`], point)) {
                this.currTargetPotIdx = i;
                let idx = i;
                this.currTargetSoupId = this.pots[`pot${i}`].id;

                if (this.pots[`pot${i}`].isEmpty) {
                    // 空锅底
                    NetManager.ins.clickLog(this.createExposure(`tjcp${i + 1}`))
                    let data = { scene: this, idx: i }
                    PanelCtrl.instance.show(ModuleTypes.ADOPTSOUP_PANEL, data);
                } else {
                    // 非空锅底
                    // 判断是否超过达到100度  

                    const is100 = this.pots[`pot${idx}`].temperature >= 100;
                    const isHeated = this.pots[`pot${idx}`].isHeated;

                    if (is100) {
                        // 达到100度
                        // 去收获锅底
                        NetManager.ins.clickLog(this.createExposure(`shfb${i + 1}`));
                        const petId: number = this.currTargetSoupId;
                        Waiting.instance.show();
                        NetConst.collectSoup((s) => {
                            if (!s) {
                                Waiting.instance.hide();
                                this.enableTap(true);
                                ToastCtrl.instance.show("网络异常！收获失败，再试一次吧~")
                                return
                            }
                            // 播放收获动效
                            Waiting.instance.hide();
                            // debugger
                            NetManager.ins.showLog(this.createExposure(`tjcp${i + 1}`));
                            let soup = this.pots[`pot${idx}`].soup;
                            soup.anchorOffsetX = 289 / 2;
                            soup.anchorOffsetX = 290 / 2;
                            soup.x = 289 / 2 + this[`pot${idx}`].x + 47;
                            soup.y = 290 / 2 + this[`pot${idx}`].y + 362;

                            let target = this[`pot${idx}`]
                            let type = this.pots[`pot${idx}`].type;
                            target.removeChild(soup);
                            GameConst.arr.removeEle(soup, this.soupPool);
                            // NetConst.getPetsInfo((s) => {
                            //     if (!s) {
                            //         ToastCtrl.instance.show("网络异常，更新柴火失败，请退出刷新重试。如有疑问，请联系捞小秘~")
                            //         return
                            //     }
                            this.updateCurrTargetPots(idx).then(() => {
                                this.enableTap(true);
                            })
                            //     // this.initUI();
                            // }, window['CFG'].activityId)
                            this.addChild(soup)

                            this.pots[`pot${idx}`].soup = null;
                            this.pots[`pot${idx}`].isEmpty = true;
                            // debugger
                            this.pots[`pot${idx}`].temperature = 0;
                            this.pots[`pot${idx}`].type = null;
                            this.pots[`pot${idx}`].isHeated = false;
                            this.pots[`pot${idx}`].id = 0;

                            egret.Tween.get(soup)
                                .to({ scaleX: 0, scaleY: 0 }, 300)
                                .call(() => {
                                    let pot = new eui.Image();
                                    pot.source = `finishedPot_png`;
                                    pot.x = soup.x;
                                    pot.y = soup.y;
                                    pot.scaleX = 0;
                                    pot.scaleY = 0;
                                    pot.anchorOffsetX = 107 / 2;
                                    pot.anchorOffsetY = 120 / 2;
                                    this.addChild(pot);
                                    egret.Tween.get(pot)
                                        .to({ scaleX: 1, scaleY: 1 }, 200)
                                        .to({ scaleX: 0, scaleY: 0, x: 201, y: 1120 }, 300)
                                        .call(() => {
                                            this.enableTap(true);
                                            let data = { scene: this, type: type }
                                            PanelCtrl.instance.show(ModuleTypes.COLLECTPOTSUC_PANEL, data)
                                            this[`addSoup${idx}`].visible = true;
                                            this.removeChild(pot);
                                            this.removeChild(soup);
                                            this.log(this.pots)
                                        })
                                })


                        }, petId, window['CFG'].activityId);
                    } else {
                        // 低于100度  
                        if (isHeated) {
                            ToastCtrl.instance.show("每个锅底每天只能加热一次，明天再来吧")
                        } else {
                            //出扣柴火弹窗
                            NetManager.ins.clickLog(this.createExposure(`jrfb${i + 1}`))
                            PanelCtrl.instance.show(ModuleTypes.WARNING_PANEL, this)
                        }
                    }
                }
                break
            }
        }
    }

    onTap_exchangeStoreBtn() {
        this.exchangeStoreBtnBg.visible = true;
        this.exchangeListBtnBg.visible = false;
        this.exchangeableList.visible = false;
        this.storeList.visible = true;
    }

    onTap_exchangeListBtn() {
        this.exchangeStoreBtnBg.visible = false;
        this.exchangeListBtnBg.visible = true;
        this.exchangeableList.visible = true;
        this.storeList.visible = false;
    }

    onTap_randomDrawBtn() {
        let option0 = DataManager.ins.getData("getCollectRule").collectGoods.length > 0
        let option1 = false;
        if (option0) {
            for (let i = 0; i < DataManager.ins.getData("getCollectRule").collectGoods.length; i++) {
                let good = DataManager.ins.getData("getCollectRule").collectGoods[i];
                if (good.count > 0) {
                    option1 = true
                    break
                }
            }
        }
        if (!option1) {
            // 没有可用汤底
            ToastCtrl.instance.show("还没有沸腾的锅底哦，快去加热吧～");
        } else {
            // 出选锅底
            PanelCtrl.instance.show(ModuleTypes.CONSUME_PANEL, this);
        }

    }

    private msgPool: any[] = []
    private isHideMsg: boolean = false;
    onEnterFrame() {

        if (this.msgPool && this.msgPool.length > 0 && !this.isHideMsg) {
            if (this.msgPool[this.msgPool.length - 1].x < -this.msgPool[this.msgPool.length - 1].width - 30) {
                this.isHideMsg = true;
                egret.Tween.get(this.winnerList)
                    .to({ y: -60 }, 500)
            } else {
                this.msgPool.forEach((msg) => {
                    msg.x -= 1;
                })
            }
        }

    }

    removeEvents() {
        super.removeEvents();
        this.clearTap(this.ruleBtn, this.onTap_ruleBtn);
        this.clearTap(this.taskBtn, this.onTap_taskBtn);
        this.clearTap(this.closeTaskBtn, this.onTap_closeTaskBtn);
        this.clearTap(this.exchangeBtn, this.onTap_exchangeBtn);
        this.clearTap(this.closeExchangeBtn, this.onTap_closeExchangeBtn);
        this.clearTap(this.exchangeStoreBtn, this.onTap_exchangeStoreBtn);
        this.clearTap(this.exchangeListBtn, this.onTap_exchangeListBtn);
        for (let i = 0; i < 4; i++) {
            this.clearTap(this[`pot${i}`], this.onTap_pot);
        }
        this.clearTap(this.randomDrawBtn, this.onTap_randomDrawBtn);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 动效部分 ↓
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // 倒汤动效
    playPourAni(soup: Soup) {
        return new Promise((r) => {
            let tips: eui.Image = new eui.Image()
            let soupIdx = 0;
            let eleName = "mushroom"
            let eleNum: number = 4;

            switch (soup.type) {
                case SoupTypes.MUSHROOM:
                    tips.source = `pourTips0_png`;
                    soupIdx = 0;
                    eleName = "mushroomEle"
                    eleNum = 6;
                    break;
                case SoupTypes.SPICY:
                    tips.source = `pourTips1_png`;
                    soupIdx = 1;
                    eleName = "spicyEle";
                    eleNum = 8;
                    break;
                case SoupTypes.THREEFRESH:
                    tips.source = `pourTips2_png`;
                    soupIdx = 2;
                    eleName = "threefreshEle";
                    eleNum = 13;
                    break;
                case SoupTypes.TOMATO:
                    soupIdx = 3;
                    tips.source = `pourTips3_png`;
                    eleName = "tomatoEle";
                    eleNum = 4;
                    break;
            }
            switch (this.currTargetPotIdx + "") {
                case "0":
                    tips.x = 0
                    tips.y = 360;
                    tips.scaleX = 1;
                    break;
                case "1":
                    tips.x = 750;
                    tips.y = 360;
                    tips.scaleX = -1;
                    break;
                case "2":
                    tips.x = 0;
                    tips.y = 660;
                    tips.scaleX = 1;
                    break;
                case "3":
                    tips.x = 750;
                    tips.y = 660;
                    tips.scaleX = -1;
                    break;
            }
            this.addChild(tips);
            let bool = false;

            egret.Tween.get(soup[`soupGroup${soupIdx}`])
                .to({ scaleX: 1, scaleY: 1 }, 400)
                .wait(50)
                .call(() => {
                    this.removeChild(tips)
                    wait(200).then(() => {
                        egret.Tween.get(soup[`Thermometer`])
                            .set({ y: 211 - 30, alpha: 0 })
                            .to({ y: 211, alpha: 1 }, 300)
                    })
                    for (let i = 0; i < eleNum; i++) {
                        let ele = soup[`${eleName}${i}`];
                        egret.Tween.get(ele)
                            .to({ scaleX: 1.06, scaleY: 1.06 }, 200)
                            .to({ scaleX: 1, scaleY: 1 }, 100)
                            .call(() => {
                                if (!bool) {
                                    bool = true

                                    r();
                                }
                            })
                    }
                })
        });
    }

    // 正常循环动效
    playSoupAni(soup: Soup, temperature: number = 0) {
        return new Promise((r) => {
            let eleName = "mushroom";
            let eleNum: number = 4;
            let time: number = 1000;
            let scale: number = 0.96;
            let rate: number = 3;
            switch (soup.type) {
                case SoupTypes.MUSHROOM:
                    eleName = "mushroomEle"
                    eleNum = 6;
                    break;
                case SoupTypes.SPICY:
                    eleName = "spicyEle";
                    eleNum = 8;
                    break;
                case SoupTypes.THREEFRESH:
                    eleName = "threefreshEle";
                    eleNum = 13;
                    break;
                case SoupTypes.TOMATO:
                    eleName = "tomatoEle";
                    eleNum = 4;
                    break;
            }
            switch (temperature + "") {
                case "25":
                    time = 700;
                    scale = 0.93;
                    rate = 3;
                    break;
                case "50":
                    time = 500;
                    scale = 0.90;
                    rate = 2.5;
                    break;
                case "75":
                    time = 300;
                    scale = 0.85;
                    rate = 2
                    break;
                case "100":
                    time = 100;
                    scale = 0.76;
                    rate = 1.5
                    // let fog = MovieClipCtrl.instance.getMovieClipByName(`fog_${soup.idx}`);
                    // fog.x = -20;
                    // fog.y = -100;
                    // fog.play(-1)
                    // soup.addChildAt(fog, 4)
                    break;
            }
            for (let i = 0; i < eleNum; i++) {
                let ele = soup[`${eleName}${i}`];
                wait(i * rate * 50)
                egret.Tween.removeTweens(ele);
                egret.Tween.get(ele, { loop: true })
                    .set({ scaleX: 1, scaleY: 1 })
                    .to({ scaleX: scale, scaleY: scale }, time)
                    .to({ scaleX: 1, scaleY: 1 }, time)
                    .call(() => {
                        r()
                    })
            }
            this.log(scale)
        })

    }

    // 更新汤底状态
    updateSoupsStatus() {
        this.log(this.soupPool)
        for (let i = 0; i < this.soupPool.length; i++) {
            // 判断锅位有没有汤底
            let soup = this.pots[`pot${i}`].soup;
            let isEmpty = this.pots[`pot${i}`].isEmpty;
            if (isEmpty) {
                return
            }
            // 判断今天是否加热过
            let isHeated = this.pots[`pot${i}`].isHeated;
            if (isHeated) {
                soup.filter.visible = true;
                soup.heatTips.visible = false;
                return
            }
            // 判断温度是否为100度     
            let is100 = this.pots[`pot${i}`].temperature == 100;
            if (is100) {
                //出收获按钮
                soup.filter.visible = true;
                soup.collectTips.visible = true;
                return
            }
            // 如果未加热过  出加热提示
            soup.filter.visible = true;
            this.showTips(soup.heatTips);
        }
    }


    // 加热动效
    heatUp(idx) {
        let soup = this.pots[`pot${idx}`].soup;
        let type = this.pots[`pot${idx}`].type;
        this.enableTap(true);
        if (!soup) {
            return
        }
        if (this.pots[`pot${idx}`].temperature >= 100) {
            return
        }
        if (this.pots[`pot${idx}`].isHeated) {
            return
        }
        this.enableTap(false);
        this.touchMask.visible = true;
        //????
        this.pots[`pot${idx}`].isHeated = true;
        let targetValue = this.pots[`pot${idx}`].temperature + 25;
        this.pots[`pot${idx}`].temperature = targetValue;
        soup.filter.visible = false;
        soup.heatTips.visible = false;

        egret.Tween.get(this[`fire${idx}`])
            .to({ scaleX: 1.05, scaleY: 1.05 }, 100)
            .call(() => {
                egret.Tween.get(this[`fire${idx}`], { loop: true })
                    .to({ scaleX: 0.95, scaleY: 0.95 }, 200)
                    .to({ scaleX: 1.05, scaleY: 1.05 }, 200)
                wait(1000).then(() => {
                    egret.Tween.removeTweens(this[`fire${idx}`])
                    egret.Tween.get(this[`fire${idx}`])
                        .to({ scaleX: 0, scaleY: 0 }, 500)
                    egret.Tween.get(soup[`Thermometer`], { onChange: this.onHeatUp.bind(this) })
                        .to({ value: targetValue }, 500)
                        .call(() => {
                            this.touchMask.visible = false;
                            this.updateCurrTargetPots(idx).then(() => {
                                this.enableTap(true);
                            });
                            this.log("sss：" + targetValue)
                            this.playSoupAni(soup, targetValue)
                            this.log(this.pots)

                        })
                })
            })
    }

    onHeatUp() {
        let soup = this.pots[`pot${this.currTargetPotIdx}`].soup;
        soup[`Thermometer`].temperatureTxt.text = `${Math.floor(soup[`Thermometer`].value)}度`
    }

    showTips(target) {
        return new Promise(r => {
            egret.Tween.removeTweens(target);
            egret.Tween.get(target)
                .set({ y: 146 - 23, alpha: 0 })
                .to({ y: 146, alpha: 1 }, 200)
                .wait(300)
                .call(() => {
                    r();
                })
            target.visible = true;
        })
    }



}