import { DataManager } from './../../libs/tw/manager/DataManager';
import { ModuleTypes } from './../types/sceneTypes';

import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import SceneCtrl from '../ctrls/sceneCtrl';
import { NetManager } from '../../libs/tw/manager/NetManager';
import Loading from '../loading/Loading';
import { ToolManager } from '../toolManager/ToolManager';
import { Buried } from '../../libs/tw/util/Buried';
import { GCache } from '../../libs/tc/util/GCache';
import { NetName } from '../../libs/tw/enum/NetName';
import { NetPromise } from '../NetPromise';
import { MConfigs } from '../MConfigs';
import { LotteryType } from '../../libs/tw/enum/LotteryType';
import TopLayerCtrl from '../ctrls/topLayerCtrl';
export default class StartScene1 extends Scene {
    public mainbg: eui.Image;
    public petGroup: eui.Group;
    public pet_bg_1: eui.Image;
    public pet_bg_2: eui.Image;
    public pet_bg_3: eui.Image;
    public pet_bg_4: eui.Image;
    public pet_bg_5: eui.Image;
    public pet_bg_6: eui.Image;
    public petBodyGroup: eui.Group;
    public handGroup: eui.Group;
    public nzGroup: eui.Group;
    public image1: eui.Image;
    public timeNzLable: eui.Label;
    public shengjiAnGroup: eui.Group;
    public giftBtn: eui.Group;
    public image2: eui.Image;
    public expPro: eui.ProgressBar;
    public petExpText: eui.Label;
    public goldText: eui.Label;
    public nowLvName: eui.Label;
    public nextLvName: eui.Label;
    public foodBtn: eui.Button;
    public playBtn: eui.Button;
    public musicBtn: eui.Button;
    public cureBtn: eui.Button;
    public taskBtn: eui.Button;
    public tixianBtn: eui.Button;
    public redTips: eui.Image;
    public harvestListMask: eui.Rect;
    public harvestListGroup: eui.Group;
    public scoreBtn: eui.Button;
    public achievementBtn: eui.Button;
    public prizeBtn: eui.Button;
    public harvestBtn: eui.Button;
    public harvestDwon: eui.Image;
    public harvestUp: eui.Image;
    public image0: eui.Image;
    public image: eui.Image;
    public tipsGroup: eui.Group;
    public tips_step_2: eui.Group;
    public tips_step_3: eui.Group;
    public tips_step_1: eui.Group;
    public foodBtn0: eui.Button;






    // 用于控制全局音乐是否播放和音乐按钮状态
    public static isPlayMusic: boolean = true;

    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }

    constructor(data?) {
        super(data);//95fcf3
    }

    initEvents() {
        super.initEvents();
        this.foodBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_foodBtn, this);
        this.harvestBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_harvestBtn, this);
        this.playBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_playBtn, this);
        this.musicBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_musicBtn, this);
        this.cureBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_cureBtn, this);
        this.giftBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_giftBtn, this);
        this.tipsGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_tipsGroup, this);
        this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        this.scoreBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_scoreBtn, this);
        this.achievementBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_achievementBtn, this);
        this.taskBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_taskBtn, this);
        this.tixianBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_tixianBtn, this);

    }

    removeEvents() {
        super.removeEvents();
        this.foodBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_foodBtn, this);
        this.harvestBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_harvestBtn, this);
        this.playBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_playBtn, this);
        this.musicBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_musicBtn, this);
        this.cureBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_cureBtn, this);
        this.giftBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_giftBtn, this);
        this.tipsGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_tipsGroup, this);
        this.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        this.scoreBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_scoreBtn, this);
        this.achievementBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_achievementBtn, this);
        this.taskBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_taskBtn, this);
        this.tixianBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_tixianBtn, this);
        clearInterval(this.clearMusicTime);
    }


    /**
     * 乐谱
     */
    onTap_scoreBtn() {
        NetPromise.ins.getKuwoMusicScoreKuwo(window["eduSignId"], 20, 1).then((succuss) => {
            PanelCtrl.instance.show(ModuleTypes.SCORE_PANEL);
        }).catch(() => {

        })
    }

    /**
    * 成就
    */
    onTap_achievementBtn() {
        NetPromise.ins.getEvolutionRecordKuwo(window["eduSignId"], window["petId"]).then((succuss) => {
            PanelCtrl.instance.show(ModuleTypes.ACHIEVEMENT_PANEL);
        }).catch(() => {

        })

    }

    /**
     * 任务弹窗
     */
    onTap_taskBtn() {
        NetPromise.ins.getTaskInfoKuwo(window["eduSignId"], window["petId"]).then((succuss) => {
            PanelCtrl.instance.show(ModuleTypes.QUEST_LIST_PANEL);
        }).catch(() => {

        })
    }

    /**
     * 红包提现
     */
    onTap_tixianBtn() {

    }


    isHarvestListGroupShow = false;

    onTap_harvestBtn() {
        this.isHarvestListGroupShow = !this.isHarvestListGroupShow;
        this.harvestUp.visible = false;
        this.harvestDwon.visible = false;
        if (this.isHarvestListGroupShow) {
            this.harvestUp.visible = true;
            this["listShow"].play(0)
        } else {
            this.harvestDwon.visible = true;
            this["listHide"].play(0)
        }
    }

    tipsStep = 1
    /**
     * 点击引导页进行下一步提示
     */
    onTap_tipsGroup() {
        this.tipsStep++;
        this.tips_step_1.visible = false;
        this.tips_step_2.visible = false;
        this.tips_step_3.visible = false;
        if (this.tipsStep > 3) {
            this.tipsGroup.visible = false;
            this.tips_step_1.visible = false;
            this.tips_step_2.visible = false;
            this.tips_step_3.visible = false;
            //引导完成执行签到
            NetPromise.ins.doSign(window["signActivityId"])
                .then((success) => {
                    console.log("首次签到成功")
                    if (DataManager.ins.signInfoData.signInfoVO.rewardMap) {
                        if (DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE) {
                            if (DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId) {
                                return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId,
                                    `首次到访`,
                                    window["signPrizes"][0]);
                            }
                        }
                    }
                })
                .then((success) => {
                    console.log("首次签到奖励发放成功")
                })
                .catch((data) => {
                    console.error(data)
                })
        } else {
            this["tips_step_" + this.tipsStep].visible = true;
        }
    }

    /**
     * 展示引导
     * @param tipsStep 步骤
     */
    showTips(tipsStep) {
        this.tips_step_1.visible = false;
        this.tips_step_2.visible = false;
        this.tips_step_3.visible = false;
        this.tipsGroup.visible = true;
        this["tips_step_" + tipsStep].visible = true;
    }

    async onTap_foodBtn() {
        this.enabled = false;
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 11)
            .then((data) => {
                //petInteractionKuwo成功
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then((data) => {
                //getPetInfoKuwo成功
                return this.setPetFood(this.petData.petLevel)
            })
            .then(() => {
                //setPetFood执行成功
                this.enabled = true;
                this.updatePetState()
            })
            .catch((error) => {
                console.error(error)
                this.enabled = true;
            })
    }

    onTap_giftBtn() {
        this["giftHide"].play(0)
        NetPromise.ins.getPlugOrderStatus(DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.response.orderNum)
            .then(() => {
                if (DataManager.ins.getPlugOrderStatusData.lottery.type == LotteryType.COUPON) {
                    PanelCtrl.instance.show(ModuleTypes.GET_TICKET_PANEL)
                } else {
                    this.showToast("未中奖，请下次再来")
                }
            })
            .catch(() => {

            })
    }

    showToast(val) {
        //console.log(val)
        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: val });
    }

    async onTap_playBtn() {
        this.enabled = false;
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 12)
            .then((data) => {
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then((data) => {
                return this.setPetPlay(this.petData.petLevel)
            })
            .then(() => {
                this.enabled = true;
                this.updatePetState()
            })
            .catch((error) => {
                console.error(error)
                this.enabled = true;
            })
    }

    async onTap_musicBtn() {
        this.enabled = false;
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 13)
            .then((data) => {
                return NetPromise.ins.getPetInfoKuwo();
            })
            .then((data) => {
                return this.setPetMusic(this.petData.petLevel);
            })
            .then(() => {
                this.enabled = true;
                this.updatePetState()
            })
            .catch((error) => {
                console.error(error)
                this.enabled = true;
            })
    }

    async onTap_cureBtn() {
        this.enabled = false;
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 14)
            .then((data) => {
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then((data) => {
                return this.setPetSick(this.petData.petLevel)
            })
            .then(() => {
                this.enabled = true;
                this.updatePetState()
            })
            .catch((error) => {
                console.error(error)
                this.enabled = true;
            })
    }

    start(data?) {
        super.start(data);
        this.percentHeight = 100;
    }

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        this.bgtexture = await RES.getResAsync('startBg_jpg');

        //   await this.sleep(10000)
        // console.log('载背景并设置背景图片mainscene');
        return new Promise(function (resolve, reject) {
            resolve();
        });


    }

    protected onSkinComplete(): void {
        super.onSkinComplete();

        this.mainbg.texture = this.bgtexture;

        this.isHarvestListGroupShow = false;
        this.harvestUp.visible = false;

        this.harvestListGroup.mask = this.harvestListMask;

        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
        console.log("test")


    }

    pets = []

    LoadPetClip(url) {
        return new Promise((resolev, reject) => {
            var parser = new window["SVGA"].Parser();
            parser.load(url, (videoItem) => {
                let pet = new window["SVGA"].EgretMovieClip(videoItem);
                pet.visible = false;
                this.petBodyGroup.addChild(pet);
                resolev(pet)
            }, (error) => {
                reject(error);
            })
        })
    }



    private async onLoad() {
        await this.initUI();
    }


    petAns = [
        "auto",
        "click",
        "food",
        "play",
        "sick_keep",
        "sick"
    ]



    petData

    url = "/petAn"

    handAn

    shengjiAn

    private async initUI() {
        Loading.instace.show()
        for (let i = 1; i <= 6; i++) {
            this["pet_bg_" + i].visible = false;
        }
        this.enabled = false;
        this.nzGroup.visible = false;



        var mcJson = await RES.getResAsync('shengjiAn_json');
        var mcImg = await RES.getResAsync('shengjiAn_png');
        var mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);
        this.shengjiAn = new egret.MovieClip(mcFactory.generateMovieClipData());

        this.shengjiAnGroup.addChild(this.shengjiAn)

        this.handAn = await this.LoadPetClip(`${this.url}/handAn/hand.svga`);
        this.handGroup.addChild(this.handAn)
        this.handAn.stop()

        for (let i = 0; i < 7; i++) {
            console.log(`加载进度:${i}/6`);
            this.pets[i] = []
            for (let j = 0; j < this.petAns.length; j++) {
                // console.log(`正在加载：等级为lv${i}的${this.petAns[j]}宠物`);
                this.pets[i][this.petAns[j]] = await this.LoadPetClip(`${this.url}/pet_lv_${i}/${this.petAns[j]}.svga`);
            }
            if (i == 6) {
                Loading.instace.hide()
                this.enabled = true;
                console.log("加载完成")
            }
        }


        this.updatePetState();


        await this.updateWin()



        this["nzLoop"].play(0)
        this["nzLoop"].items.forEach((item) => {
            item.tween.loop = true;
        })

        await NetPromise.ins.getSignInfoKuwo(window["signActivityId"])
            .then((data) => {
                console.log("NetName.SIGN_DO_SIGN")
                console.log(DataManager.ins.signInfoData)
                if (DataManager.ins.getData(NetName.SIGN_INFO_KUWO).signInfoVO.acmDay) {
                    //如果acmDay大于0，则说明已经签到过了
                    console.log("已经签到过了")
                    if (DataManager.ins.getData(NetName.SIGN_INFO_KUWO).signInfoVO.todaySigned == false) {
                        //如果今天还没有签过到，则执行签到
                        return NetPromise.ins.doSign(window["signActivityId"])
                    }
                } else {
                    console.log("新人")
                    //如果acmDay不存在或者等于0，则说明没有签过到，执行新手引导
                    this.showTips(1)
                }
            })
            .then((success) => {
                console.log(success)
                if (success) {
                    console.log("签到成功")
                    let continueDay = DataManager.ins.getData(NetName.SIGN_INFO_KUWO).signInfoVO.continueDay
                    if (DataManager.ins.signInfoData.signInfoVO.rewardMap) {
                        if (DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE) {
                            if (DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId) {
                                if (continueDay == 3) {
                                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId,
                                        `连续访问活动${continueDay}天`,
                                        window["signPrizes"][1]);
                                } else if (continueDay == 7) {
                                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId,
                                        `连续访问活动${continueDay}天`,
                                        window["signPrizes"][2]);
                                } else if (continueDay == 15) {
                                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap.CIRCLE.plActId,
                                        `连续访问活动${continueDay}天`,
                                        window["signPrizes"][3]);
                                }
                            }
                        }
                    }
                }
            })
            .then((success) => {
                console.log(success)
                //if (success) {
                console.log("签到成功")
                //}
            })
            .catch((data) => {
                console.error(data)
            })

        //console.log(this.pets)
        //this.setPetAuto(0)
        //this.setPetClick(0)
        //this.setPetPlay(0)
        // this.setPetSick(0)
        // this.setPetFood(0)
        //this.setPetSickKeep(0)

    }


    LastPetLevel = 0

    /**
     * 更新宠物状态
     */
    async updatePetState() {
        this.petData = DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data;
        this.petGroup.visible = true;
        this.updateTop()
        this.updateRedInfo()
        for (let i = 1; i <= 6; i++) {
            this["pet_bg_" + i].visible = false;
        }
        if (this.petData.petLevel > 1) {
            console.log("pet_bg_" + (this.petData.petLevel - 1))
            this["pet_bg_" + (this.petData.petLevel - 1)].visible = true;
        }



        await new Promise((success) => {


            this.nzGroup.visible = false;

            this.cureBtn.enabled = true;
            this.foodBtn.enabled = true;
            this.playBtn.enabled = true;
            this.musicBtn.enabled = true;

            if (this.petData.status == 1) {
                //默认状态
                this.setPetAuto(this.petData.petLevel)
                this.cureBtn.enabled = false;
            } else if (this.petData.status == 4) {
                //外出学习音乐
                this.petGroup.visible = false;
                this.nzGroup.visible = true;

                this.cureBtn.enabled = false;
                this.foodBtn.enabled = false;
                this.playBtn.enabled = false;
                this.musicBtn.enabled = false;
                this.updateMusicTime()
            } else if (this.petData.status == 6) {
                //处于生病状态
                this.setPetSickKeep(this.petData.petLevel)
                this.foodBtn.enabled = false;
                this.playBtn.enabled = false;
                this.musicBtn.enabled = false;
            } else if (this.petData.status == 7) {
                //处于玩耍状态
                this.setPetPlay(this.petData.petLevel)
                this.cureBtn.enabled = false;
            }
            success()
        })


        await new Promise((success) => {
            if (this.LastPetLevel != 0 && this.LastPetLevel != this.petData.petLevel) {
                this.shengjiAn.gotoAndPlay(0, 1)
                this["shengjiDou"].play(0)
                this.pets[this.LastPetLevel - 1]["auto"].stop(0)
                this["shengjiDou"].items.forEach((item) => {
                    item.tween.loop = true;
                })
                let fun
                this.shengjiAn.addEventListener(egret.Event.COMPLETE, fun = () => {
                    this.shengjiAn.removeEventListener(egret.Event.COMPLETE, fun, this)
                    this["shengjiDou"].stop()
                    this.pets[this.LastPetLevel - 1]["auto"].play()
                    PanelCtrl.instance.show(ModuleTypes.UPGRADE_REWARD_PANEL1, {
                        achievement: this.petData.petLevel, redPacket: 12.89, callback: () => {
                            success()
                        }
                    });
                }, this)
                console.log("宠物升级啦")
            } else {
                success()
            }
            this.LastPetLevel = this.petData.petLevel;
        })
    }


    /**
     * 更新红包红点提醒
     */
    updateRedInfo() {
        NetPromise.ins.detailKuwo()
        .then(() => {
            let data = DataManager.ins.getData(NetName.DETAIL_KUWO).data;
            if (data.withdrawTimes > 0 || data.balance >= data.withdrawThreshold) {
                this.redTips.visible=true
            }else{
                this.redTips.visible=false;
            }
        })
        .catch(() => {
            this.redTips.visible=false;
        })
}

    /**
     * 判断是否为打开完成音乐学习
     */
    async MusicHarvest() {
        return NetPromise.ins.getTaskInfoKuwo(window["eduSignId"], window["petId"])
            .then((succuss) => {
                let data = DataManager.ins.getData(NetName.TASK_INFO_KUWO).data
                if (data.hasMusicHarvest) {
                    return NetPromise.ins.getLearnMusicHarvestKuwo(window["petId"], window["eduSignId"], window["loginUid"], window["sid"])
                }
            })
            .then(() => {
                return new Promise((resolev) => {
                    PanelCtrl.instance.show(ModuleTypes.LEARNED_MUSIC_PANEL, {
                        "musicName": DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.song.name,
                        "singerName": DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.song.artist,
                        "pic": DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.song.pic,
                        "callback": () => {
                            resolev()
                        }
                    })
                })
            })
            .then(() => {
                this["giftShow"].play(0)
            })
            .catch(() => {

            })
    }

    clearMusicTime;

    updateMusicTime() {
        let time = DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data.statusRemainingTime;
        let timeWill = time * 1000 + Date.now()
        let nowTime
        this.clearMusicTime = setInterval(() => {
            nowTime = timeWill - Date.now();
            if (nowTime >= 0) {
                let d: any = Math.floor(nowTime / 1000 / 60 / 60 / 24);
                let h: any = Math.floor(nowTime / 1000 / 60 / 60 % 24);
                let m: any = Math.floor(nowTime / 1000 / 60 % 60);
                let s: any = Math.floor(nowTime / 1000 % 60);
                let ms: any = Math.floor(nowTime % 1000);
                if (ms < 100) {
                    ms = "0" + ms;
                }
                if (ms < 10) {
                    ms = "0" + ms;
                }
                if (s < 10) {
                    s = "0" + s;
                }
                if (m < 10) {
                    m = "0" + m;
                }
                if (h < 10) {
                    h = "0" + h;
                }
                this.timeNzLable.text = `${m}:${s}:${ms.toString().substr(1, 2)}`
                console.log(`${m}:${s}:${ms.toString().substr(1, 2)}`)
            } else {
                clearInterval(this.clearMusicTime);
                NetPromise.ins.getPetInfoKuwo()
                    .then(async () => {
                        //setPetFood执行成功
                        this.enabled = true;
                        await this.MusicHarvest()
                        await this.updatePetState()

                    })
                    .catch((error) => {
                        console.error(error)
                        this.enabled = true;
                    })
            }
        }, 60)
    }


    updateTop() {
        if (!this.petData) {
            return
        }
        //更新进度条
        this.expPro["valueLabel"].text = (this.petData.petExp - this.petData.currentLevelExp) / (this.petData.nextLevelExp - this.petData.currentLevelExp) * 100 + "%";
        this.expPro.value = (this.petData.petExp - this.petData.currentLevelExp) / (this.petData.nextLevelExp - this.petData.currentLevelExp) * 100;
        //更新经验值
        this.petExpText.text = this.petData.petExp;
        //更新金币
        this.goldText.text = this.petData.foodNum;
        //更新当前称呼和下一等级的称呼
        this.nowLvName.text = MConfigs.achievement[this.petData.petLevel].name;
        if (this.petData.petLevel >= 7) {
            this.nextLvName.text = "敬请期待";
        } else {
            this.nextLvName.text = MConfigs.achievement[this.petData.petLevel + 1].name;
        }

    }

    clearAllPet() {
        for (let i = 0; i < 7; i++) {
            for (let j = 0; j < this.petAns.length; j++) {
                this.pets[i][this.petAns[j]].visible = false;
            }
        }
    }
    /**
     * 设置宠物为生病状态
     * @param lv 等级
     */
    async setPetSickKeep(lv) {
        this.clearAllPet()
        this.pets[lv - 1]["sick_keep"].visible = true;
        let fun
        this.pets[lv - 1]["sick_keep"].gotoAndPlay(0, true)
        await new Promise((resolev) => {
            this.pets[lv - 1]["sick_keep"].addEventListener(egret.Event.COMPLETE, fun = () => {
                resolev()
            }, this)
        })
        this.pets[lv - 1]["sick_keep"].removeEventListener(egret.Event.COMPLETE, fun, this)
        this.pets[lv - 1]["sick_keep"].stop()
        this.pets[lv - 1]["sick_keep"].startAniRange(10, 14);
    }

    /**
    * 设置宠物为治疗状态
    * @param lv 等级
    */
    async setPetSick(lv) {
        this.handAn.stop()
        this.handAn.gotoAndPlay(0, true)
        this.handAn.visible = true;
        await ToolManager.ins.sleep(300);
        await this.clearAllPet()
        this.pets[lv - 1]["sick"].visible = true;
        let fun
        this.pets[lv - 1]["sick"].gotoAndPlay(46, false)
        await new Promise((resolev) => {
            this.pets[lv - 1]["sick"].addEventListener(egret.Event.COMPLETE, fun = () => {
                resolev()
            }, this)
        })
        this.handAn.stop()
        this.pets[lv - 1]["sick"].removeEventListener(egret.Event.COMPLETE, fun, this)
        this.pets[lv - 1]["sick"].stop()
        this.handAn.visible = false;
        await ToolManager.ins.sleep(300);
        this.setPetAuto(lv)
    }

    /**
     * 设置宠物为默认状态
     * @param lv 等级
     */
    async setPetAuto(lv) {
        this.clearAllPet()
        this.pets[lv - 1]["auto"].gotoAndPlay(0, true)
        this.pets[lv - 1]["auto"].visible = true;
        this.pets[lv - 1]["auto"].gotoAndPlay(0, true)
    }

    /**
     * 设置宠物为点击状态
     * @param lv 等级
     */
    async setPetClick(lv) {
        this.clearAllPet()
        this.pets[lv - 1]["click"].visible = true;
        this.pets[lv - 1]["click"].gotoAndPlay(0, true)
        let fun
        await new Promise((resolev) => {
            this.pets[lv - 1]["click"].addEventListener(egret.Event.COMPLETE, fun = () => {
                resolev()
            }, this)
        })
        this.pets[lv - 1]["click"].removeEventListener(egret.Event.COMPLETE, fun, this)
        this.pets[lv - 1]["click"].stop()
        await ToolManager.ins.sleep(300);
        //点击完成后恢复到默认状态
        this.setPetAuto(lv)
    }

    /**
     * 设置宠物为玩耍状态
     * @param lv 等级
     */
    async setPetPlay(lv) {
        return new Promise(async (success) => {
            this.clearAllPet()
            this.pets[lv - 1]["play"].visible = true;
            this.pets[lv - 1]["play"].gotoAndPlay(0, true)
            let fun
            await new Promise((resolev) => {
                this.pets[lv - 1]["play"].addEventListener(egret.Event.COMPLETE, fun = () => {
                    resolev()
                }, this)
            })
            this.pets[lv - 1]["play"].removeEventListener(egret.Event.COMPLETE, fun, this)
            this.pets[lv - 1]["play"].stop()
            await ToolManager.ins.sleep(300);
            //完成后恢复到默认状态
            this.setPetAuto(lv)
            success()
        })
    }

    /**
     * 设置宠物为学习音乐状态
     * @param lv 等级
     */
    async setPetMusic(lv) {
        return new Promise(async (success) => {
            this["yunAn"].play(0)
            let fun;
            setTimeout(() => {
                this.clearAllPet()
                this.petGroup.visible = false;
                this.nzGroup.visible = true;
            }, 1000)
            await new Promise((resolev) => {
                this["yunAn"].addEventListener(egret.Event.COMPLETE, fun = () => {
                    resolev()
                }, this)
            })
            this["yunAn"].removeEventListener(egret.Event.COMPLETE, fun, this)
            await ToolManager.ins.sleep(300);
            //完成后恢复到默认状态
            // this.setPetAuto(lv)
            success()
        })
    }

    /**
     * 设置宠物为喂食状态
     * @param lv 等级
     */
    async setPetFood(lv) {
        return new Promise(async (succuss) => {
            this.clearAllPet()
            this.pets[lv - 1]["food"].visible = true;
            this.pets[lv - 1]["food"].gotoAndPlay(0, true)
            let fun
            await new Promise((resolev) => {
                this.pets[lv - 1]["food"].addEventListener(egret.Event.COMPLETE, fun = () => {
                    resolev()
                }, this)
            })
            this.pets[lv - 1]["food"].removeEventListener(egret.Event.COMPLETE, fun, this)
            this.pets[lv - 1]["food"].stop()
            await ToolManager.ins.sleep(300);
            //完成后恢复到默认状态
            this.setPetAuto(lv)
            succuss()
        })
    }


    async updateWin() {

        //判断签到成功
        if (localStorage.getItem("signGold")) {
            await this.rewardWin("签到成功", localStorage.getItem("signGold"));
            localStorage.removeItem("signGold");
        }

        await this.MusicHarvest();

        //首次到访
        // await this.rewardWin("首次到访","2");

        //首次到访
        // await this.rewardWin("连续签到","2");
    }

    //签到弹窗
    async signWin(plActId, title, rewardNum) {
        NetPromise.ins.doJoinPlugDraw(plActId)
            .then(() => {
                return NetPromise.ins.getPlugOrderStatus(DataManager.ins.doJoinPlugDrawData.orderId)
            })
            .then(() => {
                return this.rewardWin(title, rewardNum)
            })
            .catch(() => {
                console.log("异常")
            })
    }

    rewardWin(title, rewardNum) {
        return new Promise((resolve, reject) => {
            PanelCtrl.instance.show(ModuleTypes.REWARD_PANEL, {
                title: title,
                rewardNum: rewardNum,
                callback: () => {
                    resolve()
                }
            });
        })
    }

    private onTap_ruleBtn(): void {
        console.log('点击rule');
        // PanelCtrl.instance.btnDelay(this.ruleBtn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    private onTap_startBtn(): void {
        // PanelCtrl.instance.btnDelay(this.startBtn);
        NetManager.ins.getHome((succuss) => {
            if (!succuss) {
                return;
            }

            this.showMainScene();
        }, this.getQueryString("dailyMark"), window["CFG"].activityId)
    }

    private async showMainScene() {
        await RES.loadGroup('msg_panel');
        await RES.getResAsync('msgBg0_png');
        await RES.getResAsync('msgBg1_png');
        await RES.getResAsync('msgBg2_png');
        await RES.getResAsync('msgBg3_png');

        SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);

    }

    getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };





    private onTap_prizeBtn(): void {
        console.log('点击prizeBtn');
        // PanelCtrl.instance.btnDelay(this.prizeBtn);
        window.location.href = this.gotoRecord();//window["recordUrl"];

    }

    //获取我的奖品
    private gotoRecord(): string {
        let recordUrl: string;
        let activityId: number;
        // if (DataManager.ins.customCfgData) {
        // 	oaId = DataManager.ins.customCfgData.oaId;
        // 	recordUrl = DataManager.ins.customCfgData.recordUrl;
        // } else {
        // 	oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
        // 	recordUrl = window['recordUrl'];
        // }

        activityId = window['CFG'].activityId;
        recordUrl = window['recordUrl'];

        if (recordUrl.indexOf('?') != -1) {
            recordUrl += '&origins=' + activityId + '00';
        } else {
            recordUrl += '?origins=' + activityId + '00';
        }
        // recordUrl += ',' + (window['plugId'] ? window['plugId'] : 4500) + '01';

        // for(let i = 0; i < window['plugIdArr'].length; i++){
        //     recordUrl += ',' + window['plugIdArr'][i] + '01';
        // }

        return recordUrl;
    }

    //循环播放动画
    private playAnimation(target: egret.tween.TweenGroup, isLoop: boolean = true): void {
        if (isLoop) {
            for (var key in target.items) {
                target.items[key].props = { loop: true };
            }
        }
        target.play();
    }


}
