import { _decorator, Button, HorizontalTextAlignment, Label, Sprite, SpriteFrame, Toggle, tween, UIOpacity } from 'cc';
import { BaseView } from '../../../framework/layer/BaseView';
import { ServerItem } from './ServerItem';
import { AudioID } from '../../../framework/config/AudioConf';
import { Framework } from '../../../framework/Framework';
import { UserData } from '../../data/UserData';
import List from '../../../framework/list/List';
import { StringUtil } from '../../../framework/util/StringUtil';
import { GameEvent } from '../../data/GameEvent';
import { LoginMgr } from '../../common/LoginManager';
import { ServergatewaylistConf } from '../../config/ServergatewaylistConf';
import { AccountData } from '../../data/AccountData';
const { ccclass, property } = _decorator;

@ccclass('SelectServer')
export class SelectServer extends BaseView {
	@property({ type: Label, tooltip: "标题" })
	titlteTx: Label = null;

	@property({ type: Label, tooltip: "分区文字1" })
	areaTx1: Label = null;

	@property({ type: Label, tooltip: "分区文字2" })
	areaTx2: Label = null;

	@property({ type: Label, tooltip: "分区文字3" })
	areaTx3: Label = null;

	@property({ type: List, tooltip: "服务器组容器" })
	serverGroupSv: List = null;

	@property({ type: List, tooltip: "服务器容器" })
	serverItemSv: List = null;

	private groupList = []

	private serverList = []
	private Server_data = null;
	private tabulation = 'recently_login';
	private initialized = false;//首次刷新标记
	private areaId = '1';

	protected onLoad() {
		super.onLoad();
		this.titlteTx.string = StringUtil.getLanguageData('选择服务器');

		Framework.event.addEvent(GameEvent.SelectServer, () => {
			AccountData.setAreanId(this.areaId);
			Framework.layer.close(this);
		}, this);

	}

	protected onDestroy() {

	}

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

	// serverTab(event: Event) {
	// 	if (!this.Server_data) {
	// 		Framework.tips.setTips('完蛋，服务器开小差了')
	// 		return;
	// 	}
	// 	let target: any = event.target;
	// 	let choosePic = this.Node.serverTab.getChildByName(this.tabulation).getComponent(Sprite).spriteFrame;
	// 	this.Node.serverTab.getChildByName(this.tabulation).getComponent(Sprite).spriteFrame = target.getComponent(Sprite).spriteFrame;
	// 	target.getComponent(Sprite).spriteFrame = choosePic;
	// 	this.tabulation = target.name;
	// 	if (target.name == 'recently_login') {
	// 		if (Object.keys(UserData.save_locally('choose_server', null, {})).length > 0) {
	// 			this.List.server.numItems = 1
	// 		} else {
	// 			this.List.server.numItems = 0;
	// 		}
	// 	} else {
	// 		this.List.server.numItems = this.server_list[target.name / 10].length
	// 	}
	// }

	//UI关闭时会调用,该函数在onDestroy前调用
	onClose() {

	}

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

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

	//UI事件处理
	private onTouchButton(event: Event, str) {
		Framework.audio.playEffect(AudioID.Click);
		let target: any = event.target;
		if (target.name == 'serverItem') {
			let idx = target.getChildByName('Index').getComponent(Label).string
		} else if (target.name == 'close_btn') {
			Framework.layer.close(this)
		}
	}

	updateUI() {
		this.groupList = [];
		let roles = AccountData.getRoleServers();
		if (roles.length != 0) {
			let roleList = [];
			for (const v of roles) {
				if (v && v.sid) {
					roleList.push(v);
				}
			}
			this.groupList.push({ name: 'lately', data: [roleList[0]] });
			this.groupList.push({ name: 'user', data: roleList });
		} else {
			let recmds = AccountData.getRecmdServers();
			if (recmds.length != 0) {
				let recommendList = [];
				for (const v of recmds) {
					if (v && v.sid) {
						recommendList.push(v);
					}
				}
				this.groupList.push({ name: 'recommend', data: recommendList });
			}
		}

		let allList = AccountData.getAllServers();
		let num = 0;
		let idx = 1;
		let serverList = {};
		for (let list in allList) {
			num++;
			if (!serverList[idx]) {
				serverList[idx] = []
			}
			if (num == 10) {
				idx++
				num = 0;
			}
			serverList[idx].push(allList[list])
		}
		for (const key in serverList) {
			const element = serverList[key];
			this.groupList.push({ name: Number(key) * 10, data: element });
		}

		this.serverGroupSv.numItems = this.groupList.length;
	}

	onEventSelectArea(target: Toggle, customEventData: string) {
		if (target.isChecked) {
			console.log('============== 大区id', customEventData)
			let url = ServergatewaylistConf.data.debug['Url' + customEventData];

			let loginData = {
				url: url,
				uid: UserData.save_locally('UserID'),
			}
			AccountData.setAreanId(this.areaId);
			LoginMgr.getServerList((data) => {
				if (data) {
					AccountData.parseLoginData(data);
					this.updateUI();
				}
			}, loginData)

		}
	}

	onEventSelectGroup(target: Toggle) {
		let selectPoint = target.node.getChildByName('select_point').getComponent(Sprite);
		if (target.isChecked) {
			let idx = Number(target.node.name);
			this.serverList = this.groupList[idx].data;
			this.serverItemSv.numItems = this.groupList[idx].data.length;
			this.load('package', 'texture/login/area_select_point/spriteFrame', SpriteFrame, (res: SpriteFrame) => {
				selectPoint.getComponent(Sprite).spriteFrame = res;
			})
		}else{
			this.load('package', 'texture/login/area_bg_point/spriteFrame', SpriteFrame, (res: SpriteFrame) => {
				selectPoint.getComponent(Sprite).spriteFrame = res;
			})
		}
	}

	// 列表渲染 
	onServerListEvent(item, idx) {
		item.name = String(idx);
		let nameTx = item.getChildByName('name_tx').getComponent(Label);
		let selectPoint = item.getChildByName('select_point');
		let gData = this.groupList[idx]
		if (gData.name == 'lately') {
			selectPoint.active = false;
			nameTx.node.setPosition(0, 6);
			nameTx.horizontalAlign = HorizontalTextAlignment.CENTER;
			nameTx.fontSize = 26;
			nameTx.string = StringUtil.getLanguageData('最近登录');
			this.initialized = true;
			item.getComponent(Toggle).isChecked = false;
			item.getComponent(Toggle).isChecked = true;
		} else if (gData.name == 'user') {
			selectPoint.active = false;
			nameTx.node.setPosition(0, 6);
			nameTx.horizontalAlign = HorizontalTextAlignment.CENTER;
			nameTx.fontSize = 26;
			nameTx.string = StringUtil.getLanguageData('拥有角色');
		} else if (gData.name == 'recommend') {
			selectPoint.active = false;
			nameTx.node.setPosition(0, 6);
			nameTx.horizontalAlign = HorizontalTextAlignment.CENTER;
			nameTx.fontSize = 26;
			nameTx.string = StringUtil.getLanguageData('推荐服务器');
			if (!this.initialized) {
				this.initialized = true
				item.getComponent(Toggle).isChecked = false;
				item.getComponent(Toggle).isChecked = true;
			}
		} else {
			selectPoint.active = true;
			nameTx.node.setPosition(10, 6);
			nameTx.horizontalAlign = HorizontalTextAlignment.LEFT;
			nameTx.fontSize = 22;
			if (gData.name > 10) {
				nameTx.string = `${(gData.name + 1) + "_" + (gData.name + 10)}${StringUtil.getLanguageData('区')}`
			} else {
				nameTx.string = `1-10${StringUtil.getLanguageData('区')}`;
				if (!this.initialized) {
					this.initialized = true
					item.getComponent(Toggle).isChecked = false;
					item.getComponent(Toggle).isChecked = true;
				}
			}
		}
	}

	// 列表渲染 
	onServerEvent(item, idx) {
		item.getComponent(ServerItem).init(this.serverList[idx]);
	}
}