import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import SceneCtrl from "../ctrls/sceneCtrl";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { ToolManager } from "../toolManager/ToolManager";
import { NetName } from "../../libs/tw/enum/NetName";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetPromise } from "../NetPromise";

export default class LoadingScene extends Scene {
	public mainbg:eui.Image;
	public pBar:eui.ProgressBar;
	public percentLb:eui.Label;
	public pIconImg:eui.Image;
	public fly_Ioc:eui.Image;	

	private lastVal:number;

	public get skinKey() { return 'LoadingScene' }
	public get groupName() { return 'loading_scene' }
	constructor(data?) {
		super(data);
		if (data) {
		
		}
		this.percentHeight = 100;

		this.lastVal = 0;
	}

	initEvents() {
		
		GDispatcher.addEvent('progress', this.setProgress, this);//626 117
	}

	removeEvents() {
		
		GDispatcher.removeEvent('progress', this.setProgress, this);
	}

	protected onSkinComplete(): void {
		super.onSkinComplete();
		this.mainbg.texture = this.bgtexture;
		
		this.fly_Ioc.anchorOffsetX = 165;
		this.fly_Ioc.x = 115;
		this.addChild(this.fly_Ioc);

		//this.fly_Ioc.gotoAndPlay(0, -1);
	}

	start(data?) {

	}

	protected onLoad(): void {
		this.initUI();
	}

	private initUI(): void {
		//初始化数据
		this.initData();

	}
	private initData(): void {
	}

	private async setProgress(data){
		let v = data[0];
		let time = 450;
		this.pBar.value = v;
		this.fly_Ioc.x = 115 + 609 * v * 0.01;
		this.lastVal = v;
		this.percentLb.text = v + '%';
		if(v >= 63){
			await ToolManager.ins.sleep(500)
			await NetPromise.ins.getPetInfoKuwo()
			console.log(DataManager.ins.getData(NetName.GET_PET_INFO_KUWO))
			this.beforeScene()
		}
	}
	beforeScene(){

		if(localStorage.duibadev=="1"){
			this.gotoStart()
		}else{
			try {
				window["plat"]=isIOS() ? 'ip' : 'ar';   //平台 ip:ios ar:android
				window["kuwoApi"].getUserInfo({
					callback: (res) => {
					  console.log('getUserInfo', res);
					  window["loginUid"]=res.uid;
					  window["sid"]=res.sid;
					  window["kuwoApi"].getClientInfo({
						callback: (res1) => {
						  console.log('getClientInfo', res1);
						  if(isIOS()){
							 window["appuid"] = res1.uid;
						  }else{
							 window["appuid"] = res1.device_uid;
						  }
						  this.gotoStart()
						}
					})
					}
				})
			} catch (error) {
				this.gotoStart()
			}
		}
	}

	//pets=[]
	petAns = [
        "auto",
        "click",
        "food",
        "play",
        "sick_keep",
        "sick"
	]
	
	url = "//yun.duiba.com.cn/db_games/activity/kwyyyc_20190809/petAn3"

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

	 async gotoStart(){


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

		NetPromise.ins.initKuwo(window["loginUid"],window["sid"])
		.then(()=>{
			SceneCtrl.instance.change(ModuleTypes.START_SCENE);
		})
		.catch(()=>{
			if(localStorage.duibadev=="1"){
				SceneCtrl.instance.change(ModuleTypes.START_SCENE);
			}
		})
	}

	private bgtexture: egret.Texture;
	protected async preLoadRes() {
        //加载背景并设置背景图片
        this.bgtexture = await RES.getResAsync('lodingBg_jpg');
        // console.log('载背景并设置背景图片mainscene');
		//this.iconAct = new egret.MovieClip(mcFactory.generateMovieClipData());

        return new Promise(function (resolve, reject) {
            resolve();
        });
	}

	//循环播放动画
	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();
    }
}

export const isIOS = () => {
    const u = navigator.userAgent;
    return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
}