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()
        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`);
                //this.pets[i][j].gotoAndStop(0);
            }
            if(i==6){
                Loading.instace.hide()
                console.log("加载完成")
            }
        }
        console.log(this.pets)
        this.pets[0]["sick_keep"].visible=true;
    }

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


}
