import { sys, tween, Tween, _decorator } from 'cc';
import { UIHelper } from '../../../framework/common/UIHelper';
import { AudioID } from '../../../framework/config/AudioConf';
import { FrameworkConf } from '../../../framework/config/FrameworkConf';
import { ViewID } from '../../../framework/config/LayerConf';
import { Framework } from '../../../framework/Framework';
import { BaseView } from '../../../framework/layer/BaseView';
import { AsyncQueue, NextFunction } from '../../../framework/queue/AsyncQueue';
import { AppClue } from '../../common/AppClue';
import { BulletlPool, DecoratePool, FloatTextPool, GoodsPool, IconPool, MaterialPool, PopPool, RewardPool, RolePool, TipsPool } from '../../common/Pool';
import { UserData } from '../../data/UserData';
import { LoginMgr } from '../../common/LoginManager';

const { ccclass, property } = _decorator;




export function getParameterByName(name) {
    let url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
	
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
    //return results[2].replace(/\+/g, ' ')
}

@ccclass('LoginUI')
export class LoginUI extends BaseView {
	private _touchLogin = false;
	private scene_back = null;

	protected onLoad() {
		super.onLoad();
		this._initPool();
		LoginMgr.init();
		this.Label.ver.string = "版本:1.0.0";
		Framework.event.addEvent(FrameworkConf.Event.NET_ERROR, () => {
			// if (this.node.active && this._touchLogin) {
			// 	if (UserData.player.uuid != "") {
			// 		this._enterGame(0);
			// 	} else {
			// 		UIHelper.buttonEnable(this.Button.btn_login, true);
			// 		this._touchLogin = false;
			// 	}
			// }
		}, this);
		Framework.event.addEvent(FrameworkConf.Event.NET_CLOSE, () => {
			// if (this.node.active && this._touchLogin) {
			// 	if (UserData.player.uuid != "") {
			// 		this._enterGame(0);
			// 	} else {
			// 		UIHelper.buttonEnable(this.Button.btn_login, true);
			// 		this._touchLogin = false;
			// 	}
			// }
		}, this);
		Framework.audio.playMusic(AudioID.Game);


		AppClue.init();

	}

	protected onDestroy() {
		super.onDestroy();
		Framework.event.removeEvent(this);
		this.scene_back()

	}

	//UI开打时会调用,如果有初始化代码应该放到此函数
	onOpen(SceneBack) {

		this.scene_back = SceneBack
		// console.log(window["App_Clue"]);
		// GuideConf
		//this.EditBox.box.string = UserData.save_locally('UserID', null, '');

	}

	//UI关闭时会调用,该函数在onDestroy前调用
	onClose() {
		// Tween.stopAllByTarget(this.Node.sign);
	}

	//框架管理UI层级时会调用,可根据UI情况修改
	onShow() {
		super.onShow();
	}

	//框架管理UI层级时会调用,可根据UI情况修改
	onHide() {
		super.onHide();
	}
	EditTex(text) {
		let reg = new RegExp("^[A-Za-z0-9]+$");
		let str = "";
		for (let i = 0; i < text.length; i++) {
			if (reg.test(text.charAt(i))) {
				str += text.charAt(i);
			}
		}
		this.EditBox.box.string = str;
		// this.EditBox.box.focus();
	}
	onLogin() {
		Framework.audio.playEffect(AudioID.Click);

		let data = {
			url:getParameterByName("url") ||"http://118.178.135.110/sdk/debug/login.php",
			uid:getParameterByName("uid") ||"ttq3",
			token:getParameterByName("token")
		}

		
		Framework.layer.open(ViewID.LoadingUI, () => {
			UserData.save_locally('UserID', data.uid)
		}, data);
		//
		//登录游戏
		// Framework.layer.close(this);
		// if (this.EditBox.box.string.length > 0) {
		// 	const match = SensitiveWordFilter.getInstance().containsSensitiveWord(this.EditBox.box.string);
		// 	if (match) {
		// 		Framework.tips.setTips(`${match}是敏感词`);
		// 		return;
		// 	}
			
		// } else {
		// 	Framework.tips.setTips('账号只能输入英文和数字并且不可为空！');
		// }
	}



	//UI事件处理
	private onTouchButton(event: Event) {

		let target: any = event.target;

		// LoginMgr.getServerList(1, (data) => {
		// 	// Framework.layer.close(this);
		// 	Framework.layer.open(ViewID.ServerList,null,data)
		// })
		return;
	}
	private _enterGame(state: number) {
		// if (UserData.player.uuid == "") {
		// 	UIHelper.buttonEnable(this.Button.btn_login, true);
		// 	this._touchLogin = false;
		// 	Framework.tips.setTips("网络错误,请查看网络是否正常!");
		// 	this.Button.btn_loginex.node.active = true;
		// 	return;
		// }
		// if (UserData.player.area == GameConf.AreaType.error) {
		// 	Framework.layer.open(ViewID.HometownUI, () => {
		// 		Framework.layer.close(this);
		// 	});
		// } else {
		//载入界面


		// }
	}

	private _loginEx() {
		//开始登陆
		if (sys.platform == sys.Platform.WECHAT_GAME) {
			//微信
			// @ts-ignore
			wx.login({
				success: (result) => {
					//console.log(result);
					LoginMgr.check(result.code, (token: string | null) => {
						if (token) {
							// LoginMgr.login(1, token, this._enterGame.bind(this));
							AppClue.open_id = token;
						} else {
							//登录失败
							this.Button.btn_loginex.node.active = true;
							Framework.tips.setTips("登录失败");
						}
					});
				},
				fail: (result) => {
					console.log(result);
					this.Button.btn_loginex.node.active = true;
				}
			});
		} else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
			//字节
			// @ts-ignore
			tt.login({
				force: false,
				success: (result) => {
					console.log(`login 调用成功${result.code} ------ ${result.anonymousCode}`);
					LoginMgr.check(result.code, (token: string | null) => {
						if (token) {
							// LoginMgr.login(2, token, this._enterGame.bind(this));
						} else {
							//登录失败
							this.Button.btn_loginex.node.active = true;
							Framework.tips.setTips("登录失败");
						}
					});
				},
				fail: (result) => {
					console.log(`login 调用失败`);
					this.Button.btn_loginex.node.active = true;
					Framework.tips.setTips("登录失败");
				},
			});
		} else {
			this.Button.btn_loginex.node.active = true;
		}
	}

	private _initPool() {
		//初始化池
		// let queue = new AsyncQueue();

		// queue.pushMulti("InitPool", async (next: NextFunction, params: any, args: any) => {
		// 	//加载道具池
		// 	MaterialPool.init("package", "prefab/pool/MaterialItem", 15, 120, () => {
		// 		next && next();
		// 		console.log("道具池加载成功!");
		// 	});
		// }, async (next: NextFunction, params: any, args: any) => {
		// 	Framework.tips.setTipsNode("package", "prefab/other/TipsNode", "Label", () => {
		// 		next && next();
		// 	});
		// }, async (next: NextFunction, params: any, args: any) => {
		// 	RewardPool.init("package", "prefab/other/RewardEffect", 3, 120, () => {
		// 		next && next();
		// 	});
		// }, async (next: NextFunction, params: any, args: any) => {
		// 	BulletlPool.init("package", "prefab/other/Bullet", 6, 120, () => {
		// 		next && next();
		// 	});
		// }, async (next: NextFunction, params: any, args: any) => {
		// 	FloatTextPool.init("package", "prefab/other/FloatText", 10, 120, () => {
		// 		next && next();
		// 	});
		// });

		// queue.complete = () => {
		// };
		
		// queue.play();
		this._loginEx();
	}
}

