import { sys, tween, Tween, _decorator, Label, EditBox, Node, Sprite, SpriteFrame } 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 { BulletlPool, DecoratePool, FloatTextPool, GoodsPool, IconPool, MaterialPool, PopPool, RewardPool, RolePool, TipsPool } from '../../common/Pool';
import { UserData } from '../../data/UserData';
import { AccountData } from '../../data/AccountData';
import { LoginMgr } from '../../common/LoginManager';
import { StringUtil } from '../../../framework/util/StringUtil';
import { GameEvent } from '../../data/GameEvent';
import { ServergatewaylistConf } from '../../config/ServergatewaylistConf';

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 {

	@property(Node)
	loginRoot: Node = null;

	@property({ type: Label, tooltip: "版本" })
	version: Label = null;

	@property({ type: Sprite, tooltip: "logo" })
	logoImg: Sprite = null;

	@property(Node)
	selectServer: Node = null;
	@property({ type: Label, tooltip: "ServerIndex" })
	serverIndex: Label = null;
	@property({ type: Label, tooltip: "ServerName" })
	serverName: Label = null;
	@property({ type: Sprite, tooltip: "服务器状态" })
	serverState: Sprite = null;

	@property({ type: Node, tooltip: "用户协议同意状态" })
	agreementIco: Node = null;
	@property({ type: Label, tooltip: "用户协议文字1" })
	agreementTx1: Label = null;
	@property({ type: Label, tooltip: "用户协议" })
	agreementTx: Label = null;
	@property({ type: Label, tooltip: "用户协议文字2" })
	agreementTx2: Label = null;
	@property({ type: Label, tooltip: "隐私政策" })
	privacyTx: Label = null;

	@property({ type: Label, tooltip: "六字真言" })
	bibleTx: Label = null;

	@property({ type: Label, tooltip: "公告按钮文字" })
	bulletinBtnTx: Label = null;

	@property({ type: EditBox, tooltip: "账号" })
	userName: EditBox = null;

	private scene_back = null;

	//登录数据
	private loginData: any = null
	accountData: any;
	serverData: any;
	//用户协议同意状态
	agreementState: number;

	protected onLoad() {
		super.onLoad();
		this._initPool();
		LoginMgr.init();
		this.version.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.event.addEvent(GameEvent.SelectServer, () => {
			this.updateCurServer(true);
		}, this);
		Framework.audio.playMusic(AudioID.Game);

		let uid = UserData.save_locally('UserID')

		let lastArea = UserData.save_locally('LastArea', null, '1');
		AccountData.setAreanId(lastArea);
		AccountData.setSid(UserData.save_locally('lastsid',null,-1),false)

		this.loginData = {
			url: getParameterByName("url") || ServergatewaylistConf.data.debug['Url' + lastArea],
			uid: getParameterByName("uid") || uid || "ttq3",
			token: getParameterByName("token"),
		}


		// this.server_list.push(choose_server)

		this.userName.string = this.loginData.uid || ""
		// this.serverName.string = "997"

		this.agreementState = UserData.save_locally('AgreementState', null, 0)
	}

	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.userName.string = str;
		// this.EditBox.box.focus();
	}
	onLogin() {
		Framework.audio.playEffect(AudioID.Click);

		this.loginData.uid = this.userName.string
		UserData.save_locally('UserID', this.loginData.uid)
		this.getServerList()
	}

	onEnter() {
		let _gateway_data = {
			openid: this.accountData.openId,    //上面获取到的openid
			openkey: this.accountData.openKey,    //上面获取到的openkey
			sid: this.serverData.sid,        // 选择的服务器列表信息中的id
		}

		LoginMgr.getGateway(_gateway_data, this.serverData.host, () => {
			let lastArea = AccountData.getAreanId();
			UserData.save_locally('LastArea', lastArea);
			if (UserData['mark'].first_login && UserData['mark'].first_login == 1) {

			Framework.layer.open(ViewID.TowerUI, () => {
						Framework.layer.close(ViewID.LoginUI);
						Framework.layer.close(ViewID.SelectServer);
					});
			} else {
				Framework.layer.open(ViewID.TowerUI, () => {
					Framework.layer.close(ViewID.LoginUI);
					Framework.layer.close(ViewID.SelectServer);
				});
			}
		})



		//
		//登录游戏
		// 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;
		if (target.name == 'select_server') {
			Framework.layer.open(ViewID.SelectServer)
		} else if (target.name == 'age_tips') {
			//适龄提示
		} else if (target.name == 'agreement_node') {
			if (this.agreementState) {
				this.agreementState = 0;
				UserData.save_locally('AgreementState', 0)
			} else {
				this.agreementState = 1;
				UserData.save_locally('AgreementState', 1)
			}
			this.agreementIco.active = this.agreementState == 1 ? true : false;
		} else if (target.name == 'agreement_tx') {
			//用户协议
		} else if (target.name == 'privacy_tx') {
			//隐私政策
		} else if (target.name == 'bulletin_btn') {
			Framework.layer.open(ViewID.Bulletin);
		} else if (target.name == 'refresh_tx') {
			//刷新重启游戏大概
		}
	}
	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));
		// 				} 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();
	}

	//获取服务器列表
	private getServerList() {
		LoginMgr.getServerList((data) => {
			if (data) {
				AccountData.parseLoginData(data);
				this.accountData = AccountData.getAccountData()
				this.updateCurServer()
			}
		}, this.loginData)
	}

	updateCurServer(isRefresh?: boolean) {
		let sid = -1;
		if (isRefresh) {
			sid = AccountData.getSid();
		}
		if (sid == -1) {
			const roles = AccountData.getRoleServers();
			if (roles.length === 0) {
				// 无角色,寻找推荐服务器
				const recmds = AccountData.getRecmdServers();
				for (const v of recmds) {
					if (v && v.sid) {
						sid = v.sid;
						break;
					}
				}
			} else {
				// 找最近登录的服务器,roles 已排序,第一个是最近的
				for (const v of roles) {
					if (v && v.sid) {
						sid = v.sid;
						break;
					}
				}
			}

		}
		let serverData = AccountData.getServerBySid(sid)
		if (!serverData) {
			return;
		}

		this.serverData = serverData;

		AccountData.setSid(serverData['sid'], false);
		this.serverIndex.string = `${serverData.sid}${StringUtil.getLanguageData('服')}`;
		this.serverName.string = serverData.name;

		if (serverData.status == 0) {
			this.load('package', 'texture/login/gray_1/spriteFrame', SpriteFrame, (res: SpriteFrame) => {
				this.serverState.getComponent(Sprite).spriteFrame = res;
			})
		} else if (serverData.status == 1) {
			this.load('package', 'texture/login/red_1/spriteFrame', SpriteFrame, (res: SpriteFrame) => {
				this.serverState.getComponent(Sprite).spriteFrame = res;
			})
		} else if (serverData.status == 2) {
			this.load('package', 'texture/login/green_1/spriteFrame', SpriteFrame, (res: SpriteFrame) => {
				this.serverState.getComponent(Sprite).spriteFrame = res;
			})
		}

		this.loginRoot.active = false
		this.selectServer.active = true
	}


}