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';
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 foodBtn:eui.Button;
    public playBtn:eui.Button;
    public musicBtn:eui.Button;
    public cureBtn:eui.Button;
    public harvestListMask:eui.Rect;
    public harvestListGroup:eui.Group;
    public harvestBtn:eui.Button;
    public harvestDwon:eui.Image;
    public harvestUp:eui.Image;
    

    


    // 用于控制全局音乐是否播放和音乐按钮状态
    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.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        // this.musicBtn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_musicBtn, 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.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        // this.musicBtn.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_musicBtn, this);
    }

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

    async onTap_foodBtn(){
        this.enabled=false;
        let isSuccess=false;
        let petInteractionKuwo:any=await NetPromise.ins.petInteractionKuwo(this.petData.petId,11)
        let getPetInfoKuwo=await NetPromise.ins.getPetInfoKuwo()


        petInteractionKuwo.then(()=>{
            petInteractionKuwo()
        })
       
        Promise.all([ petInteractionKuwo, getPetInfoKuwo]).then((results)=>{
            this.enabled=true;
            if(results.some((list)=>{return list!=true})){
                console.log("不成功")
            }else{
                this.setPetFood(this.petData.petLevel)
            }
        })
    }

    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.petGroup.addChild(pet);
                resolev(pet)
            },  (error)=>{
                reject(error);
            })
        })
    }



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


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

   

    petData

    private async initUI() {
        Loading.instace.show()
        for(let i=1;i<=6;i++){
            this["pet_bg_"+i].visible=false;
        }
        this.enabled=false;
        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(`/petAn/pet_lv_${i}/${this.petAns[j]}.svga`);
            }
            if(i==6){
                Loading.instace.hide()
                this.enabled=true;
                console.log("加载完成")
            }
        }

        this.petData=DataManager.ins.getData(NetName.GET_PET_INFO_KUWO).data;
        this.updatePetState()
        //console.log(this.pets)
        //this.setPetAuto(0)
        //this.setPetClick(0)
        //this.setPetPlay(0)
       // this.setPetSick(0)
       // this.setPetFood(0)
        //this.setPetSickKeep(0)

    }

    /**
     * 更新宠物状态
     */
    updatePetState(){
        for(let i=1;i<=6;i++){
            this["pet_bg_"+i].visible=false;
        }
        if(this.petData.petLevel>0){
            this["pet_bg_"+this.petData.petLevel].visible=true;
        }

        if(this.petData.status==1){
            //默认状态
            this.setPetAuto(this.petData.petLevel)
        }else if(this.petData.status==4){
            //外出学习音乐
        }else if(this.petData.status==6){
            //处于生病状态
            this.setPetSickKeep(this.petData.petLevel)
        }else if(this.petData.status==7){
            //处于玩耍状态
            this.setPetPlay(this.petData.petLevel)
        }
    }

    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]["sick_keep"].visible=true;
        let fun
        this.pets[lv]["sick_keep"].gotoAndPlay(0,true)
        await new Promise((resolev)=>{ 
            this.pets[lv]["sick_keep"].addEventListener(egret.Event.COMPLETE, fun=()=>{
                resolev()
            }, this) 
        })
        this.pets[lv]["sick_keep"].removeEventListener(egret.Event.COMPLETE,fun,this)
        this.pets[lv]["sick_keep"].stop()
        this.pets[lv]["sick_keep"].startAniRange(10,14);
    }

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

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

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

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

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



    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 oaId: 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'];
        }

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


}
