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';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';
import { NetBuried } from '../NetBuried';
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 group:eui.Group;
    public petMsgText:eui.Label;
    public handIco:eui.Image;
    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 ruleBtn: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.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, 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);
        this.shengjiAnGroup.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_shengjiAnGroup, this);

        GDispatcher.addEvent("updatePetText",this.updateTipsError,this)
        GDispatcher.addEvent("updateTop",this.updatePetState,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.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, 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);
        this.shengjiAnGroup.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_shengjiAnGroup, this);

        GDispatcher.removeEvent("updatePetText",this.updateTipsError,this)
        GDispatcher.removeEvent("updateTop",this.updatePetState,this)
        clearInterval(this.clearMusicTime);
    }


    updateTipsError(code){
        console.log(code)
        if(code=="600033"){
            //次数上限
            if(this.clickType=="food"){
                this.updatePetTips(MConfigs.msgsOther[0])
            }else if(this.clickType=="music"){
                this.updatePetTips(MConfigs.msgsOther[1])
            }else if(this.clickType=="play"){
                this.updatePetTips(MConfigs.msgsOther[2])
            }
        }else if(code=="2002007013"){
            this.updatePetTips(MConfigs.msgsError[0])
        }
    }

    /**
     * 点击宠物
     */
    async onTap_shengjiAnGroup(){
        console.log("点击宠物")
        NetBuried.ins.clickLog(1)
        this.click_mp3.play(0,1)
        this.handIco.visible=false;
        localStorage.handIco="1"
        if(this.petData.status==1){
             this.enabled=false;
             await this.setPetClick(this.petData.petLevel)
             this.enabled=true;
        }
    }

    clearPetTips=[]

    /**
     * 更新宠物顶部消息框
     */
    updatePetTips(val?){
        clearInterval(this.clearPetTips[1])
        clearTimeout(this.clearPetTips[2])
        clearTimeout(this.clearPetTips[3])
        this["petMsgShow"].play(0)
        if(val){
            this.setPetMsgText(val)
        }else{
            this.setPetMsgText()
        }

        if(this.petData.status==1){
            this.clearPetTips[3]=setTimeout(()=>{
                this["petMsgHide"].play(0)
            },5000)
        }

        this.clearPetTips[1]=setInterval(()=>{
            if(this.petData.status==1){
                this["petMsgShow"].play(0)
                this.setPetMsgText()
                this.clearPetTips[2]=setTimeout(()=>{
                    this["petMsgHide"].play(0)
                },5000)
            }else{
                this.setPetMsgText()
                this.group.alpha=1
            }
        },7000)
    }

    setPetMsgText(val?){
        if(val){
            this.petMsgText.text=val
        }else{
            if(this.petData.status==1){
                this.petMsgText.text=MConfigs.msgsAuto[this.randomFrom(0,MConfigs.msgsAuto.length-1)]
            }else if(this.petData.status==6){
                this.petMsgText.text=MConfigs.msgsSickkeep[this.randomFrom(0,MConfigs.msgsSickkeep.length-1)]
            }
        }
    }

    randomFrom(lowerValue,upperValue){
        return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
    }

    /**
     * 乐谱
     */
    onTap_scoreBtn() {
        this.enabled=false;
        this.click_mp3.play(0,1)
        NetBuried.ins.clickLog(9)
        NetPromise.ins.getKuwoMusicScoreKuwo(window["eduSignId"], 20, 1).then((succuss) => {
            this.enabled=true;
            PanelCtrl.instance.show(ModuleTypes.SCORE_PANEL);
        }).catch(() => {
            this.enabled=true;
        })
    }

    /**
    * 成就
    */
    onTap_achievementBtn() {
        this.enabled=false;
        NetBuried.ins.clickLog(10)
        this.click_mp3.play(0,1)
        NetPromise.ins.getEvolutionRecordKuwo(window["eduSignId"],this.petData.petId).then((succuss) => {
            this.enabled=true;
            PanelCtrl.instance.show(ModuleTypes.ACHIEVEMENT_PANEL);
        }).catch(() => {
            this.enabled=true;
        })

    }

    /**
     * 任务弹窗
     */
    onTap_taskBtn() {
        this.enabled=false;
        NetBuried.ins.clickLog(6)
        this.click_mp3.play(0,1)
        NetPromise.ins.getTaskInfoKuwo(window["eduSignId"], this.petData.petId)
        .then((succuss) => {
            return NetPromise.ins.getSignInfoKuwo(window["signActivityId"])
        })
        .then(()=>{
            this.enabled=true;
            PanelCtrl.instance.show(ModuleTypes.QUEST_LIST_PANEL);
        })
        .catch(() => {
            this.enabled=true;
        })
    }

    /**
     * 红包提现
     */
    onTap_tixianBtn() {
        NetBuried.ins.clickLog(7)
        this.click_mp3.play(0,1)
        Loading.instace.show()
        setTimeout(()=>{
            Loading.instace.hide()
            window.location.href=`/aaw/customized/index?relType=${window["relType"]}&&relId=${window["relId"]}`;
        },500)
    }


    isHarvestListGroupShow = false;

    onTap_harvestBtn() {
        NetBuried.ins.clickLog(8)
        this.click_mp3.play(0,1)
        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;
        this.click_mp3.play(0,1)
        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.FIRST_SIGN) {
                            if (DataManager.ins.signInfoData.signInfoVO.rewardMap.FIRST_SIGN.plActId) {
                                return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap.FIRST_SIGN.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;
    }

    clickType

    /**
     * 喂食
     */
    async onTap_foodBtn() {
        this.enabled = false;
        NetBuried.ins.clickLog(2)
        this.click_mp3.play(0,1)
        this.clickType="food"
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 11)
            .then((data) => {
                //petInteractionKuwo成功
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then((data) => {
                //getPetInfoKuwo成功
                this.updatePetTips(MConfigs.msgsFood[this.randomFrom(0,MConfigs.msgsFood.length-1)])
                return this.setPetFood(this.petData.petLevel)
            })
            .then(() => {
                //setPetFood执行成功
                this.enabled = true;
                this.updatePetState()
            })
            .catch((error) => {
                console.error(error)
                this.enabled = true;
            })
    }

    onTap_giftBtn() {
        NetBuried.ins.clickLog(29)
        this["giftHide"].play(0);
        this.click_mp3.play(0,1)
        this.enabled = false;
        NetPromise.ins.getPlugOrderStatus(DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.placeOrderResponse.orderNum)
            .then(() => {
                this.enabled = true;
                if(!DataManager.ins.getPlugOrderStatusData.lottery){
                    this.showToast("啊哦...奖品与你擦肩而过～")
                    NetBuried.ins.showLog(32)
                }else if (DataManager.ins.getPlugOrderStatusData.lottery.type == LotteryType.COUPON) {
                    PanelCtrl.instance.show(ModuleTypes.GET_TICKET_PANEL)
                } else {
                    this.showToast("啊哦...奖品与你擦肩而过～")
                    NetBuried.ins.showLog(32)
                }
            })
            .catch(() => {
                this.enabled = true;
            })
    }

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

    /**
     * 玩耍
     */
    async onTap_playBtn() {
        this.enabled = false;
        NetBuried.ins.clickLog(3)
        this.click_mp3.play(0,1)
        this.clickType="play"
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 12)
            .then((data) => {
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then((data) => {
                this.updatePetTips(MConfigs.msgsPlay[this.randomFrom(0,MConfigs.msgsPlay.length-1)])
                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;
        NetBuried.ins.clickLog(4)
        this.click_mp3.play(0,1)
        this.clickType="music"
        await NetPromise.ins.petInteractionKuwo(this.petData.petId, 13)
            .then((data) => {
                return NetPromise.ins.getPetInfoKuwo();
            })
            .then((data) => {
                this.updatePetTips(MConfigs.msgsMusic[this.randomFrom(0,MConfigs.msgsMusic.length-1)])
                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;
        NetBuried.ins.clickLog(5)



        if(this.petData.status == 1){
            this.enabled = true;
            this.updatePetTips(MConfigs.msgsNoneSick[0])
            
        }else{
            this.click_mp3.play(0,1)
            this.clickType="cure"
            await NetPromise.ins.petInteractionKuwo(this.petData.petId, 14)
                .then((data) => {
                    return NetPromise.ins.getPetInfoKuwo()
                })
                .then((data) => {
                    return this.setPetSick(this.petData.petLevel)
                })
                .then(() => {
                    this.updatePetTips(MConfigs.msgsSick[this.randomFrom(0,MConfigs.msgsSick.length-1)])
                    this.enabled = true;
                    this.updatePetState()
                })
                .catch((error) => {
                    console.error(error)
                    this.enabled = true;
                })
        }

       
    }

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

    food_mp3
    play_mp3
    click_mp3
    music_mp3
    uplv_mp3

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

        this.food_mp3 = await RES.getResAsync("food_mp3");
		this.play_mp3 = await RES.getResAsync("play_wav");
		this.click_mp3 = await RES.getResAsync("click_mp3");
		this.music_mp3 = await RES.getResAsync("music_wav");
		this.uplv_mp3 = await RES.getResAsync("uplv_mp3");

        //   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")

        this.doBuried()
    }

   
	private doBuried() {
		NetBuried.ins.showLog(1)
		NetBuried.ins.showLog(2)
		NetBuried.ins.showLog(3)
		NetBuried.ins.showLog(4)
		NetBuried.ins.showLog(5)
		NetBuried.ins.showLog(6)
		NetBuried.ins.showLog(7)
		NetBuried.ins.showLog(8)
		NetBuried.ins.showLog(9)
		NetBuried.ins.showLog(10)
		NetBuried.ins.showLog(11)
    }
    
  

    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 = "//yun.duiba.com.cn/db_games/activity/kwyyyc_20190809/petAn"
    url = "//yun.duiba.com.cn/db_games/activity/kwyyyc_20190809/petAn3"
   // url = "/petAn3"

    handAn

    shengjiAn

    private async initUI() {
        Loading.instace.show()

       /*  setTimeout(()=>{
            console.log("主动分享1")
            NetPromise.ins.handleShare()
        },2000) */

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

        if(localStorage.handIco){
            this.handIco.visible=false
        }

        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==4&&this.petAns[j]=="play"){
                    this.pets[i][this.petAns[j]].y=20
                }
                if(i==4&&this.petAns[j]=="food"){
                    this.pets[i][this.petAns[j]].y=20
                }
                if(i==4&&this.petAns[j]=="click"){
                    this.pets[i][this.petAns[j]].y=14
                }
            }
            if (i == 6) {
                Loading.instace.hide()
                this.enabled = true;
                console.log("加载完成")
            }
        }
        this.petData = DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data;

       // this.setPetAuto(1)

        await this.updatePetState();

        await this.MusicHarvestFun();

        await this.updatePetState();

        await this.updateWin()

        await NetPromise.ins.getSignInfoKuwo(window["signActivityId"])
        .then( async (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) {
               // let continueDay = DataManager.ins.getData(NetName.SIGN_INFO_KUWO).signInfoVO.continueDay
                let continueDay = DataManager.ins.signInfoData.signInfoVO.continueDay

                let day15="ACCUMULATE"
                let day7="CIRCLE"
                let day3="CONTINUE"

                let typeDay=""

                if(continueDay==3){
                    typeDay=day3
                }else if(continueDay==7){
                    typeDay=day7
                }else if(continueDay==15){
                    typeDay=day15
                }

                if (!DataManager.ins.signInfoData.signInfoVO.rewardMap) {
                    return
                }
                if (!DataManager.ins.signInfoData.signInfoVO.rewardMap[typeDay]) {
                    return
                }
                if (!DataManager.ins.signInfoData.signInfoVO.rewardMap[typeDay].plActId) {
                    return
                }
                if (continueDay == 3) {
                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap[typeDay].plActId,
                        `连续访问活动${continueDay}天`,
                        window["signPrizes"][1]);
                } else if (continueDay == 7) {
                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap[typeDay].plActId,
                        `连续访问活动${continueDay}天`,
                        window["signPrizes"][2]);
                } else if (continueDay == 15) {
                    return this.signWin(DataManager.ins.signInfoData.signInfoVO.rewardMap[typeDay].plActId,
                        `连续访问活动${continueDay}天`,
                        window["signPrizes"][3]);
                }
            }
        })
        .then((success) => {
            console.log(success)
            console.log("签到成功")
        })
        .catch((data) => {
            console.error(data)
        })
      
        this["nzLoop"].play(0)
        this["nzLoop"].items.forEach((item) => {
            item.tween.loop = true;
        })


        this.updatePetTips()

    }


    LastPetLevel = 0

    /**
     * 更新宠物状态
     */
    async updatePetState() {
        this.petData = DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data;
        this.petGroup.visible = true;

        if(this.petData.petLevel<=0){
            return;
        }

        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) => {


            let levelUpgrade;
            let changeMoney;

            console.log("判断是否升级1")

            if (this.LastPetLevel != 0 && this.LastPetLevel != this.petData.petLevel) {

                console.log("等级发生变化")
                if(MConfigs.lastReq=="music"){
                    levelUpgrade=DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.petInfo.levelUpgrade
                    changeMoney=DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.accountModifyResponse.changeMoney
                }else if(MConfigs.lastReq=="pet"){
                    levelUpgrade=DataManager.ins.getData(NetName.PET_INTERACTION_KUWO).data.petInfo.levelUpgrade
                    changeMoney=DataManager.ins.getData(NetName.PET_INTERACTION_KUWO).data.accountModifyResponse.changeMoney
                }else{
                    return
                }

                if(!levelUpgrade){
                    return
                }
                console.log("播放升级动画")

                this.shengjiAn.gotoAndPlay(0, 1)
                this.uplv_mp3.play(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: (changeMoney/100).toFixed(2), 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 MusicHarvestFun() {
        return NetPromise.ins.getTaskInfoKuwo(window["eduSignId"],this.petData.petId)
            .then((succuss) => {
                let data = DataManager.ins.getData(NetName.TASK_INFO_KUWO).data
                if (data.hasMusicHarvest) {
                    return NetPromise.ins.getLearnMusicHarvestKuwo(this.petData.petId, window["eduSignId"], window["loginUid"], window["sid"])
                }
            })
            .then(async () => {
                //await ToolManager.ins.sleep(5000);
                return NetPromise.ins.getPetInfoKuwo()
            })
            .then(() => {
                if(DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.song){
                    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,
                            "data":DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data,
                            "callback": () => {
                                resolev()
                            }
                        })
                    })
                }else{
                    this.showToast("糟糕…本次学习没有带回歌曲，\n继续加油哦～ ")
                    return new Promise((resolev) => {
                        resolev()
                    })
                }
            })
            .then(() => {
                if(DataManager.ins.getData(NetName.LEARN_MUSIC_HARVEST_KUWO).data.placeOrderResponse.orderNum){
                    this["giftShow"].play(0)
                    NetBuried.ins.showLog(29)
                }
            })
            .catch(() => {
               
            })
    }

    clearMusicTime;

    updateMusicTime() {
        clearInterval(this.clearMusicTime);
        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 {
                this.timeNzLable.text = `00:00:00`
                clearInterval(this.clearMusicTime);
                NetPromise.ins.getPetInfoKuwo()
                    .then(async () => {
                        //setPetFood执行成功
                        this.enabled = true;
                        await this.MusicHarvestFun()
                        await this.updatePetState()

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


    updateTop() {

        this.petData = DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data;

        if (!this.petData||this.petData.petLevel<=0) {
            return
        }

        let valueLable:any=((this.petData.petExp - this.petData.currentLevelExp) / (this.petData.nextLevelExp - this.petData.currentLevelExp) * 100).toFixed(0)
        //更新进度条
        if(valueLable){
            this.expPro["valueLabel"].text = "剩余："+(100-valueLable) + "%";
        }
        this.expPro.value = (this.petData.petExp - this.petData.currentLevelExp) / (this.petData.nextLevelExp - this.petData.currentLevelExp) * 100;
        //更新经验值
        if(this.petData.petExp!=undefined||this.petData.petExp!=null){
            this.petExpText.text = this.petData.petExp;
        }
        //更新金币
        if(this.petData.foodNum!=undefined||this.petData.foodNum!=null){
            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)
            this.play_mp3.play(0,1)
            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) => {
            let fun;
            this.setPetClick(lv)
            this.music_mp3.play(0,1)
            await ToolManager.ins.sleep(1500);
            this["yunAn"].play(0)
            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.food_mp3.play(0,1);
            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.rewardWin("首次到访","2");

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

    //签到弹窗
    async signWin(plActId, title, rewardNum) {
        Loading.instace.show()
        NetPromise.ins.doJoinPlugDraw(plActId)
            .then(() => {
                return NetPromise.ins.getPlugOrderStatus(DataManager.ins.doJoinPlugDrawData.orderId)
            })
            .then(()=>{
                Loading.instace.hide()
                return this.rewardWin(title, rewardNum)
            })
            .catch(() => {
                Loading.instace.hide()
                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);
        this.click_mp3.play(0,1)
        NetBuried.ins.clickLog(11)
        Loading.instace.show()
        setTimeout(()=>{
            Loading.instace.hide()
            window.location.href = this.gotoRecord();//window["recordUrl"];
        },500)
    }

    //获取我的奖品
    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['couponId'];
        recordUrl = window['recordUrl'];

        if (recordUrl.indexOf('?') != -1) {
            recordUrl += '&origins=' + activityId + '01';
        } else {
            recordUrl += '?origins=' + activityId + '01';
        }
        // 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();
    }
}
