
import Gamecfg from "../../../common/gameCfg";
import { gameMethod } from "../../../common/gameMethod";
import { xlsPackageInfo } from "../../../common/xlsConfig";
import Config from "../../../Config";
import auto_loading from "../../../data/autoui/scene/auto_loading";
import { GameEvent, LoadEvent, ServerEvent, TimeEvent } from "../../../data/const/EventConst";
import { AudioConst, InGame, NoticeType, PlatformType } from "../../../data/const/TypeConst";
import GameDataCenter from "../../../data/GameDataCenter";
import { eg } from "../../../frameWork/eg";
import FguiMgr from "../../../frameWork/fgui/FguiMgr";
import GameController from "../../../GameController";
import EventMng from "../../../manager/EventMng";
import AssetMgr from "../../../utils/AssetMgr";
import { I18n } from "../../../utils/I18nUtil";
import Load from "../../../utils/Load";
import { uiCommon } from "../../../utils/UICommon";
import UIHelp, { DialogParams } from "../UIHelp";

const { ccclass, menu, property } = cc._decorator;

@ccclass
@menu("UI/scene/UILoading")
export default class UILoading extends cc.Component {
	@property(cc.Prefab)
	clickEft: cc.Prefab = null
	@property(cc.SpriteFrame)
	loadingBg0: cc.SpriteFrame = null

	ui: auto_loading = null;
	togglePolicy: cc.Toggle = null
	progressBar: cc.Sprite

	enterGameSid: string = ""

	loginTipTime: number = 0 // 登录

	isLoginAccountSuccess: boolean = false //账号是否登录成功

	packageInfo: xlsPackageInfo
	protected onLoad(): void {
		eg.init();
		this.ui = this.node.addComponent(auto_loading);
		this.togglePolicy = this.ui.toggle.getComponent(cc.Toggle)
		this.progressBar = this.ui.progress.getComponent(cc.Sprite)
		//初始化fgui
		FguiMgr.Instance.Init();

		this.packageInfo = Gamecfg.packageInfo.getItem(Config.pid)
		Load.loadTexture(this.ui.imgLogo, "platAsset/logo/" + (this.packageInfo.logo || "base"))
		this.ui.btnService.active = Config.kefu == "1"
		if ((Config.showTips == "1")) {
			if (!gameMethod.isEmpty(Config.showTipType)) {
				Load.loadTexture(this.ui.tip, "platAsset/tip" + Config.showTipType)
				Load.loadTexture(this.ui.biaoshi, "platAsset/biaoshi" + Config.showTipType)
				Load.loadTexture(this.ui.TipBtn, "platAsset/kaijuwenzi" + Config.showTipType)
				this.ui.tip.active = true
				this.ui.biaoshi.active = true
				this.ui.TipBtn.active = true
			} else {
				this.ui.tip.active = false
				this.ui.biaoshi.active = false
				this.ui.TipBtn.active = false
			}
			// Load.loadTexture(this.ui.imgLogo, "platAsset/logo/" + (this.packageInfo.logo || "base") + "1")
		} else {
			this.ui.tip.active = false
			this.ui.biaoshi.active = false
			this.ui.TipBtn.active = false
		}
		//动态加载适龄提示图片
		if (!gameMethod.isEmpty(Config.showAgeTip)) {
			Load.loadTexture(this.ui.imgAgeTips, "platAsset/imgTip" + Config.showAgeTip);
		}

		if (!gameMethod.isEmpty(Config.showBgType)) {
			this.ui.background.getComponent(cc.Sprite).spriteFrame = this["loadingBg" + Config.showBgType]
		}

		// 某些渠道不展示版号软著信息
		if (gameMethod.isEmpty(this.packageInfo.loadingTips1) && gameMethod.isEmpty(this.packageInfo.loadingTips2)) {
			this.ui.imgAgeTips.y = 50
			this.ui.txtJiankang.y = 50
			this.ui.txtTips1.active = false
			this.ui.txtTips2.active = false
		} else {
			uiCommon.setLabel(this.ui.txtTips1, this.packageInfo.loadingTips1)
			uiCommon.setLabel(this.ui.txtTips2, this.packageInfo.loadingTips2)
		}
		console.log("初始化游戏配置表")
		let startTime = new Date().getTime()
		this.setProgress(0, "json");
		Gamecfg.init((isSucc: boolean) => {
			console.log("初始化游戏配置表流程结束,消耗时长:" + (new Date().getTime() - startTime) + "ms")
			if (isSucc) {
				this.ui.gProgress.active = false
				console.log("解析成功")
				// 初始化数据模块
				GameDataCenter.initModule();
				// GameDataCenter.adVideo.setAdOpen()
				// //初始化数数
				// ThinkingDataMgr.TDInit();
				GameDataCenter.loading.jsonLoadSucc = true
				this.ui.btnEnter.active = this.isLoginAccountSuccess
				GameDataCenter.loginServer.Init();
				GameDataCenter.loading.checkEnterGame()
			} else {
				console.log("解析失败")
			}
		}, (finish: number, total: number) => {
			this.setProgress(finish / total, "json");
		})
	}

	protected onEnable(): void {
		if (cc.sys.platform == cc.sys.WECHAT_GAME) {
			this.ui.btnClearCache.active = true
		} else {
			this.ui.btnClearCache.active = false
		}
		// 监听btnLogin点击事件
		uiCommon.onRegisterEvent(this.ui.btnEnter, this.onClickEnterGame, this);
		uiCommon.onRegisterEvent(this.ui.gServer, this.onClickServer, this);
		uiCommon.onRegisterEvent(this.ui.btnGonggao, this.onClickGonggao, this)
		uiCommon.onRegisterEvent(this.ui.btnService, this.onClickService, this)
		uiCommon.onRegisterEvent(this.ui.btnClearCache, this.onClickClearCache, this)
		// uiCommon.onRegisterEvent(this.ui.txtPolicy, this.onClickPolicy, this)
		uiCommon.onRegisterEvent(this.ui.imgAgeTips, this.onClickAgeTips, this)
		uiCommon.onRegisterEvent(this.ui.btnGzh, this.onClickGzh, this)
		uiCommon.onRegisterEvent(this.ui.TipsBtn, this.onClickTipsBtn, this)
		uiCommon.onRegisterEvent(this.ui.txtTips2, this.onClickBeiAnBtn, this)

		// 监听事件
		EventMng.on(GameEvent.LOGIN_ACCOUNT_SUCC, this.onLoginAccountSuccess, this);
		EventMng.on(GameEvent.LOGIN_USER_SUCC, this.onLoginUserSucc, this);
		EventMng.on(GameEvent.LOGIN_USER_FAIL, this.onLoginUserFail, this);
		EventMng.on(LoadEvent.LOAD_PROGRESS, this.setProgress, this)
		EventMng.on(LoadEvent.LOAD_POLICY_AGREE, this.onAgreeEvent, this)
		EventMng.on(LoadEvent.LOAD_POLICY_TIP_AGREE, this.onAgreeTipEvent, this)
		EventMng.on(GameEvent.CLOSE_GZH, this.fixBtnEnterPos, this)
		EventMng.on(ServerEvent.SET_LOGIN_SID, this.setLoginSid, this)
		EventMng.on(TimeEvent.TIME_CD, this.onTimeCd, this)
		EventMng.on(LoadEvent.LOAD_MESSAGE, this.showLbMsg, this)
		EventMng.on(LoadEvent.SHOW_LOGIN_BTN, this.ShowLoginBtn, this)
	}

	protected onDisable(): void {
		// 取消监听btnLogin点击事件
		uiCommon.unRegisterEvent(this.ui.btnEnter);
		uiCommon.unRegisterEvent(this.ui.gServer);
		uiCommon.unRegisterEvent(this.ui.btnGonggao);
		uiCommon.unRegisterEvent(this.ui.btnService);
		// uiCommon.unRegisterEvent(this.ui.txtPolicy)
		uiCommon.unRegisterEvent(this.ui.imgAgeTips)
		uiCommon.unRegisterEvent(this.ui.btnGzh)
		uiCommon.unRegisterEvent(this.ui.txtTips2)
		// 取消监听事件
		EventMng.off(GameEvent.LOGIN_ACCOUNT_SUCC, this.onLoginAccountSuccess, this);
		EventMng.off(GameEvent.LOGIN_USER_SUCC, this.onLoginUserSucc, this);
		EventMng.off(GameEvent.LOGIN_USER_FAIL, this.onLoginUserFail, this);
		EventMng.off(LoadEvent.LOAD_PROGRESS, this.setProgress, this)
		EventMng.off(LoadEvent.LOAD_POLICY_AGREE, this.onAgreeEvent, this)
		EventMng.off(LoadEvent.LOAD_POLICY_TIP_AGREE, this.onAgreeTipEvent, this)
		EventMng.off(GameEvent.CLOSE_GZH, this.fixBtnEnterPos, this)
		EventMng.off(ServerEvent.SET_LOGIN_SID, this.setLoginSid, this)
		EventMng.off(TimeEvent.TIME_CD, this.onTimeCd, this)
		EventMng.off(LoadEvent.LOAD_MESSAGE, this.showLbMsg, this)
		EventMng.off(LoadEvent.SHOW_LOGIN_BTN, this.ShowLoginBtn, this)
	}
	// 账号登录成功
	onLoginAccountSuccess() {
		this.ui.gProgress.active = false
		this.isLoginAccountSuccess = true
		//不管老玩家还是新玩家直接进游戏
		// this.ui.btnGonggao.active = true
		// this.enterGameSid = GameDataCenter.sevBack.playerInfo.sid
		// this.onClickEnterGame()
		// 检测是否为新玩家并且后台配置默认勾选隐私协议的,直接进入游戏
		//quickh5的，新玩家不能直接进入游
		if (GameDataCenter.plat.type != PlatformType.bth5 && gameMethod.isEmpty(GameDataCenter.login.playerInfo?.list) && Config.policy != "0") {
			// 新玩家,直接进入游戏
			this.enterGameSid = GameDataCenter.login.playerInfo.sid
			this.onClickEnterGame()
		} else {
			// 老玩家,展示登录按钮
			this.ui.btnEnter.active = GameDataCenter.loading.jsonLoadSucc
			this.ui.gServer.active = true
			this.ui.btnGonggao.active = true
			//quick渠道包隐藏
			this.ui.gToggle.active = GameDataCenter.plat.type == PlatformType.bth5 || GameDataCenter.plat.type == PlatformType.XXGame ? false : true
			// this.checkCreateUserBtn()
			this.setLoginSid(GameDataCenter.login.playerInfo.sid)
		}

		let showPolicy = GameDataCenter.login.playerInfo?.switch?.["showPolicy"]?.[Config.pid] ?? 0;
		if (this.togglePolicy.isChecked == false && showPolicy == 1) {
			this.onClickPolicy();
		}

	}
	// 角色登录成功
	onLoginUserSucc() {
		// 登录成功,隐藏提示
		this.loginTipTime = 0
		this.ui.txtLoginTips.active = false
		Config.inGame = InGame.loginUser
		GameDataCenter.loading.loginSucc = true
		GameDataCenter.loading.checkEnterGame()
	}
	// 角色登录失败
	onLoginUserFail() {
		// 重置为登录角色前状态,即直接调用账号登录成功方法
		this.onLoginAccountSuccess()
	}

	protected start(): void {
		uiCommon.setI18nTextLabel(this.ui.txtVersion, 'loading_txtVersion', Config.appVersion);
		// 加载一些常驻节点
		AssetMgr.instantiate(cc.director.getScene(), this.clickEft);

		this.isLoginAccountSuccess = false;
		this.ui.btnEnter.active = false;
		this.ui.gServer.active = false;
		this.ui.gToggle.active = false;
		this.ui.gProgress.active = false;
		// this.ui.gInfo.active = false;
		this.ui.btnGonggao.active = false;
		// 根据平台展示登录窗口
		GameDataCenter.plat.instance.showLoginView();
		if (GameDataCenter.plat.type == PlatformType.bth5) {
			//quick隐私在启动页处理了
			GameDataCenter.login.savePolicy(true);
		}

		this.togglePolicy.isChecked = GameDataCenter.login.getPolicy()
		// GameDataCenter.audio.playMusic(AudioConst.bgm_base)

		// 加载资源
		GameDataCenter.loading.loadMainAssets()
	}
	onClickEnterGame() {
		if (this.togglePolicy.isChecked == false) {
			UIHelp.ShowI18nTips("loading_showtips_1");
			this.onClickPolicy();
			return
		}
		if (this.enterGameSid == "" && GameDataCenter.login?.playerInfo) {
			this.enterGameSid = GameDataCenter.login?.playerInfo?.sid
		}
		if (GameDataCenter.login.playerInfo?.qufuList[this.enterGameSid]?.status == "4") {
			UIHelp.ShowI18nTips("loading_showtips_2")
			return
		}
		// 此区无号,且是锁服状态
		if (GameDataCenter.login?.playerInfo?.list[this.enterGameSid] == null && GameDataCenter.login.playerInfo?.qufuList[this.enterGameSid]?.suofu != '1') {
			UIHelp.ShowI18nTips("loading_showtips_3")
			return
		}

		this.ui.btnEnter.active = false
		this.ui.gServer.active = false
		// this.ui.gInfo.active = false
		this.ui.gToggle.active = false
		GameDataCenter.login.sendEnterGame(this.enterGameSid)

		this.loginTipTime = 16
		this.onTimeCd()
	}

	onClickServer() {
		// cc.assetManager.loadBundle("commonView", () => {
		// 	FguiMgr.Instance.openUI(ServerViewView, ViewZorder.POP)
		// })
	}
	setProgress(val: number, type: "res" | "login" | "json") {
		if (GameDataCenter.loading.loginSucc == false && type == "res") {
			// 登录流程未走完,不展示资源加载进度条
			return
		}
		this.ui.gProgress.active = true
		this.progressBar.fillRange = val
		this.ui.imgRole.x = -this.ui.progress.width / 2 + val * this.ui.progress.width
		uiCommon.setLabel(this.ui.txtProgress, Math.floor(val * 100) + "%")
		uiCommon.setI18nTextLabel(this.ui.txtProgressTips, type == "login" ? "loading_txtProgressTips_1" : type == "res" ? "loading_txtProgressTips_2" : "loading_txtProgressTips_3")
	}
	onToggle() {
		GameDataCenter.login.savePolicy(this.togglePolicy.isChecked)
	}
	onAgreeEvent(agree: boolean) {
		this.togglePolicy.isChecked = agree
		this.onToggle()
	}
	onAgreeTipEvent(agree: boolean) {
		if ((Config.pid == "1108" || Config.pid == "1107") && agree) {
			GameDataCenter.plat.instance.showLoginView()
		}
	}
	// 公告
	onClickGonggao() {
		// if (gameMethod.isEmpty(GameDataCenter?.sevBack?.noticeWais)) {
		// 	UIHelp.ShowI18nTips("loading_showtips_4")
		// 	return
		// }
		// FguiMgr.Instance.openUI(GongGaoViewView, ViewZorder.POP, null, NoticeType.outside)
	}
	// 客服
	onClickService() {
		GameDataCenter.plat.instance.openService()
	}
	//清理缓存
	onClickClearCache() {
		//小游戏平台，清理缓存，重启游戏
		let data: DialogParams = {
			content: I18n.getI18nText("ClearCache"),
			cbConfirm: () => {
				cc.assetManager.cacheManager?.clearCache()
				GameController.clear()
				// cc.game.restart()
				if (GameDataCenter.plat.canRestartApp()) {
					wx.restartMiniProgram()
				} else {
					cc.game.end()
				}

			}
		};
		UIHelp.ShowDialog(data)

	}
	// 隐私政策
	onClickPolicy() {
		// if (GameDataCenter.plat.type == PlatformType.bth5) {
		// 	QuickSDK.showPrivace(function (retMsg) {
		// 		if (retMsg) {

		// 		} else {
		// 			QuickSDK.callExtFunction("exit", {});
		// 		}
		// 	});
		// } else {
		// 	FguiMgr.Instance.openUI(PolicyView, ViewZorder.POP, () => { }, { type: 0, isHideBtn: false });
		// }
	}
	//适龄提示
	onClickAgeTips() {
		// FguiMgr.Instance.openUI(AgeTipsView, ViewZorder.POP, null);
	}
	// 公众号
	onClickGzh() {
		this.fixBtnEnterPos(false)
		// UIHelp.ShowUI(UIGzhView)
	}
	//跳转备案号
	onClickTipsBtn() {
		if (GameDataCenter.plat.instance.isMiniClient()) {
			GameDataCenter.plat.instance.openUrl("https://beian.miit.gov.cn/");
		} else {
			cc.sys.openURL("https://beian.miit.gov.cn/");
		}

	}
	setLoginSid(sid: string) {
		this.enterGameSid = sid
		let qufuInfo = GameDataCenter.login.playerInfo.qufuList[sid]
		uiCommon.setLabel(this.ui.txtServer, GameDataCenter.login.playerInfo.qufuList[sid].name)
		let iconUrl = "resources/server/img_server_"
		if (qufuInfo.status == "1") {
			iconUrl += "new"
			// 1新服 2拥挤 3爆满 4维护
		} else if (qufuInfo.status == "4") {
			iconUrl += "weihu"
		} else {
			iconUrl += "hot"
		}
		Load.loadTexture(this.ui.imgServerState, iconUrl)
	}
	// 打开公众号时隐藏进入游戏按钮
	fixBtnEnterPos(show: boolean) {
		if (show) {
			this.ui.btnEnter.x = 0
			this.ui.gToggle.x = 0
		} else {
			this.ui.btnEnter.x = 2000
			this.ui.gToggle.x = 2000
		}
	}

	onTimeCd() {
		if (this.loginTipTime <= 0) {
			return
		}
		this.loginTipTime -= 1
		if (this.loginTipTime == 0) {
			// 此时已超时,由超时模块弹出提示弹窗
			this.ui.txtLoginTips.active = false
		} else {
			uiCommon.setI18nTextLabel(this.ui.txtLoginTips, 'loading_txtLoginTips', this.loginTipTime)
			this.ui.txtLoginTips.active = this.loginTipTime <= 14
		}
	}
	showLbMsg(str: string) {
		this.ui.lb_msg.getComponent(cc.Label).string = str;
	}

	onClickBeiAnBtn() {
		if (GameDataCenter.plat.type == PlatformType.wan17 || GameDataCenter.plat.type == PlatformType.wan17H5) {
			GameDataCenter.plat.instance.openUrl(Config.beianUrl);
		}
	}

	ShowLoginBtn() {
		this.ui.btnLogin.active = true
	}

	//拉取登录
	onClickLogin() {
		this.ui.btnLogin.active = false
		GameDataCenter.plat.instance.reShowLogInView();
	}

	protected onDestroy(): void {
		FguiMgr.Instance.Dispose()
	}

	protected update(dt: number): void {
		FguiMgr.Instance.OnUpdate(dt)
	}

	protected lateUpdate(dt: number): void {
		FguiMgr.Instance.OnLateUpdate(dt)
	}

}