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 { Buried } from '../../libs/tw/util/Buried';
import { GCache } from '../../libs/tc/util/GCache';
export default class StartScene1 extends Scene {
    public mainbg:eui.Image;
    public petGroup:eui.Group;
    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.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, 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.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, 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)
        }
    }

    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=[]

    async LoadPetClip(url){
        /*   var parser = new window["SVGA"].Parser();
            parser.load("/petAn/pet_lv_0/auto.svga", (videoItem) => {
                var mv = new window["SVGA"].EgretMovieClip(videoItem)
                mv.gotoAndPlay(1, true)
                this.petGroup.addChild(mv);
                let fun
                mv.addEventListener(egret.Event.COMPLETE, fun = function () {
                    console.log("播放完成")
                    mv.removeEventListener(egret.Event.COMPLETE,fun,this)
                }, this)
            }, function (error) {
                alert(error.message);
            }) */
        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);
            })
        })
       
    }


    async sleep(time){
        return new Promise(resolev=>{
            setTimeout(resolev,time)
        })
    }

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


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

    private async initUI() {
        Loading.instace.show()
        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("加载完成")
            }
        }
        console.log(this.pets)
        //this.setPetAuto(0)
        //this.setPetClick(0)
        //this.setPetPlay(0)
        this.setPetSick(0)
        //this.setPetSickKeep(0)
    }

    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 this.sleep(300);
        this.setPetAuto(lv)
    }

    /**
     * 设置宠物为默认状态
     * @param lv 等级
     */
    async setPetAuto(lv){
        this.clearAllPet()
        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.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.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();
    }


}
