import GameController from "../script/GameController";
import AssetMgr from "../script/utils/AssetMgr";

// 不允许在这个脚本中引用其他文件
const { ccclass, menu, property } = cc._decorator;

@ccclass
@menu("UI/scene/UISplash")
export default class UISplash extends cc.Component {
	@property(cc.Label)
	txtVersion: cc.Label = null
	@property(cc.Label)
	txtTips: cc.Label = null
	@property(cc.Node)
	bg1: cc.Node = null
	@property(cc.Node)
	bg2: cc.Node = null
	onLoad() {
		cc.game.clear()

		cc.debug.setDisplayStats(false)
		//开启强制合批
		cc.macro.CLEANUP_IMAGE_CACHE = true;
		cc.dynamicAtlasManager.enabled = false;

		window["fps"] = () => {
			cc.debug.setDisplayStats(!cc.debug.isDisplayStats())
			if (cc.debug.isDisplayStats()) {
				setTimeout(() => {
					if (cc.find('PROFILER-NODE')) {
						cc.find('PROFILER-NODE').scale = 2;
					}
				}, 200);
			}
		}
		//更新新版本，删除旧缓存
		if (cc.sys.platform == cc.sys.WECHAT_GAME) {
			//小游戏平台删除过期缓存，防止缓存超过50M
			// cc.assetManager.cacheManager.clearLRU()
			cc.assetManager.cacheManager.autoClear = true
		}
	}

	protected start(): void {
		//电魂sdk漏斗打点
		if (window['dhSDK']) {
			// 事件ID
			let eventId = "110001::GAME_CLIENT_SDK_ACTIVATE"; // 表示SDK客户端上报的启动事件
			// 事件参数
			let eventParams = {};
			// 必填参数
			eventParams["logLevel"] = "d";
			eventParams["logContent"] = "游戏首包加载结束";
			// 执行上报
			window['dhSDK'].trackEvent(eventId, eventParams);
		}
		//电魂sdk漏斗打点
		if (window['dhSDK']) {
			// 事件ID
			let eventId = "110000::GAME_CLIENT_LAUNCH"; // 表示SDK客户端上报的启动事件
			// 事件参数
			let eventParams = {};
			// 必填参数
			eventParams["logLevel"] = "d";
			eventParams["logContent"] = "SDK启动";
			// 执行上报
			window['dhSDK'].trackEvent(eventId, eventParams);
		}
		if (!cc.Node.prototype["clickChange"]) {
			let prototype = cc.Node.prototype;
			let dispatchEvent = prototype.dispatchEvent;
			prototype.dispatchEvent = function (event) {
				try {
					if (event.type == cc.Node.EventType.TOUCH_END) {
						cc.game.emit("GameEvent.ON_CLICK", event)
					}
					dispatchEvent.bind(this)(event);
				} catch (error) {
					console.error("按钮报错", "", "", error.message, error.stack)
					if (window["sendClientErr"]) {
						window["sendClientErr"]([error.message.substring(0, 200), error.stack.substring(0, 400)])
					}
				}
			}
			cc.Node.prototype["clickChange"] = true;
		}
		// 游戏速率变量
		cc.director["_kSpeed"] = 1;

		var _originCalculateDeltaTime = cc.Director.prototype["calculateDeltaTime"];
		cc.director["calculateDeltaTime"] = function (now) {
			_originCalculateDeltaTime.call(this, now);
			this._deltaTime *= this._kSpeed;
		}

		//设置速率
		// cc.director.setSpeed = function (speed) {
		// 	cc.director["_kSpeed"] = speed;
		// }
		console.log("===脚本分包加载开始")
		let time = new Date().getTime()
		// cc.assetManager
		this.txtTips.string = "正在加载本地资源..."
		cc.assetManager.loadBundle("scriptAsset", (err, bundle) => {
			if (err) {
				console.error(`load scriptAsset ${0} err:${1}`, bundle, err)
				return
			}
			console.log("===脚本分包加载完成", new Date().getTime() - time)
			this.txtTips.string = "正在加载配置..."
			import("RemoteConfig" as any).then((remoteParam) => {
				let remoteConfig = remoteParam.default
				import("GameController" as any).then((gameCtrlParam) => {
					let gameController = gameCtrlParam.default
					import("Config" as any).then((cfgParam) => {
						let config = cfgParam.default
						// pad
						config.isPad = cc.winSize.width / cc.winSize.height > (750 / 1334)
						// 显示版本号
						this.txtVersion.node.active = true
						this.txtVersion.string = "版本号:" + config.appVersion
						this.txtTips.string = "游戏初始化中(50%)..."
						remoteConfig.init(() => {
							this.txtTips.string = "游戏初始化中(80%)..."
							//电魂sdk漏斗打点
							if (window['dhSDK']) {
								// 事件ID
								let eventId = "100102::GAME_CREATE_VERSION_SUCCESS"; // 表示SDK客户端上报的启动事件
								// 事件参数
								let eventParams = {};
								// 必填参数
								eventParams["logLevel"] = "d";
								eventParams["logContent"] = "检查版本结束";
								// 执行上报
								window['dhSDK'].trackEvent(eventId, eventParams);
							}
							//电魂sdk漏斗打点
							if (window['dhSDK']) {
								// 事件ID
								let eventId = "211000::GAME_CLIENT_INIT_START"; // 表示SDK客户端上报的启动事件
								// 事件参数
								let eventParams = {};
								// 必填参数
								eventParams["logLevel"] = "d";
								eventParams["logContent"] = "游戏资源包加载进度条开始";
								// 执行上报
								window['dhSDK'].trackEvent(eventId, eventParams);
							}
							gameController.init((isSucc: boolean) => {
								if (isSucc) {
									//电魂sdk漏斗打点
									if (window['dhSDK']) {
										// 事件ID
										let eventId = "211001::GAME_CLIENT_INIT_END"; // 表示SDK客户端上报的启动事件
										// 事件参数
										let eventParams = {};
										// 必填参数
										eventParams["logLevel"] = "d";
										eventParams["logContent"] = "游戏资源包加载进度条结束";
										// 执行上报
										window['dhSDK'].trackEvent(eventId, eventParams);
									}
									this.txtTips.string = "游戏初始化中(100%)..."
									// 计算屏幕宽度, 考虑刘海屏
									config.safeAreaRect = cc.sys.getSafeAreaRect()
									// //是否是电脑端微信
									// let isWinByWx = false
									// if (cc.sys.platform == cc.sys.WECHAT_GAME) {
									// 	let sysInfo = wx.getSystemInfoSync();
									// 	if (sysInfo?.platform == "windows" || sysInfo?.platform == "mac") {
									// 		isWinByWx = true
									// 	}
									// }
									if (config.safeAreaRect.y == 0 && cc.winSize.width / cc.winSize.height < 0.5) {
										//识别不到安全区域的设备，强制预留
										config.safeAreaRect.y = 50
									}
									console.log("安全区域:", config.safeAreaRect.x, config.safeAreaRect.y, config.safeAreaRect.width, config.safeAreaRect.height)
									let perY = config.safeAreaRect.y / (config.safeAreaRect.height)
									console.log("屏幕宽高:", cc.winSize.width, cc.winSize.height)
									let realSafeY = config.safeAreaRect.y;//perY * cc.winSize.height  //config.safeAreaRect.y
									console.log("占用百分比:", perY, "真实安全区域像素x:", realSafeY)
									config.realHeight = cc.winSize.height - Math.abs(realSafeY) * 1.5
									console.log("最终高度:", config.realHeight)

									if (cc.sys.isNative && (cc.sys.platform == cc.sys.ANDROID || cc.sys.platform == cc.sys.IPHONE || cc.sys.platform == cc.sys.IPAD)) {
										//等待检测更新后再切换场景
										let hotUpdateCom = this.node.getComponent("HotUpdate")
										hotUpdateCom.checkUpdate()
									} else {
										// 加载资源
										cc.director.loadScene("loading")
									}
								}
							});
						})

						// 设置游戏主循环刷新帧率
						cc.game.setFrameRate(config.GAME_FRAME)
						// 设置动画间隔
						// cc.director.setAnimationInterval(1000 / config.GAME_FRAME)

					})
				})
			})

		})
	}
}
