import { asyncDelay, randomSortByArr } from "./util";

export abstract class middleLayerBase extends cc.Component {

	abstract reWriteAir(): void;
	abstract showMask(): void;
	abstract hideMask(): void;
	abstract hideWaitingLetters(): void;
	abstract showWaitingLetters(): void;

	oldSceneName = null;
	IS_BUNDLE_LOADING = false;

	onMiddleLayerLoadingFinish() {
		if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
			jsb.reflection.callStaticMethod(
				"RootViewController",
				"getMiddleLayerInfoFinish:",
				""
			);
		}
		if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
			jsb.reflection.callStaticMethod(
				"com/iplayabc/cocos/AppActivity",
				"getMiddleLayerInfoFinish",
				"(Ljava/lang/String;)Ljava/lang/String;",
				""
			);
		}
	}

	callNetworkApiPost(uri, _data, callBack) {
		const data = {..._data, org_id: this.ORG_ID};
		uri = uri.replace("/oxford/", "/oxfordlite/");
		this.getBaseUrl((baseUrl) => {
			const xhr = new XMLHttpRequest();
			const url = `${baseUrl}${uri}`;
			xhr.open("POST", url, true);
			xhr.setRequestHeader('content-type', 'application/json');
			xhr.onreadystatechange = () => {
				if (xhr.readyState == 4) {
					callBack(JSON.parse(xhr.responseText));
				}
			}
			xhr.send(JSON.stringify(data));
		});
	}

	callNetworkApiGet(uri, _data, callBack) {
		const data = {..._data, org_id: this.ORG_ID};
		uri = uri.replace("/oxford/", "/oxfordlite/");
		this.getBaseUrl((baseUrl) => {
			let queryStr = '?';
			const params = [];
			for (const key in data) {
				if (Object.hasOwnProperty.call(data, key)) {
					params.push(`${key}=${data[key]}`);
				}
			}
			queryStr += params.join("&");
			const xhr = new XMLHttpRequest();
			xhr.onreadystatechange = () => {
				if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
					callBack(xhr.responseText);
				}
			};
			const url = `${baseUrl}${uri}${queryStr}`;
			console.warn('url = ' + url);
			xhr.open('GET', url, true);
			xhr.send();
		});
	}

	getConfigInfo(url, callback) {
		const xhr = new XMLHttpRequest();
		xhr.onreadystatechange = () => {
			if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
				callback(JSON.parse(xhr.responseText));
			}
		};
		console.warn('url = ' + `${url}/config.json`);
		xhr.open('GET', `${url}/config.json`, true);
		xhr.send();
	}

	ORG_ID;
	DOMAIN;
	async getBaseUrl(callback = null) {
		const engineInfo = await this.getEngineInfo();
		const { isDev } = JSON.parse(engineInfo);
		if (isDev == 1) {
			this.ORG_ID = 513;
			this.DOMAIN = "https://staging-teach.cdn.ireadabc.com/";
			callback && callback('https://staging-openapi.iteachabc.com');
			return 'https://staging-openapi.iteachabc.com';
		} else {
			this.ORG_ID = 512;
			this.DOMAIN = "https://teach.cdn.ireadabc.com/";
			callback && callback('https://openapi.iteachabc.com');
			return 'https://openapi.iteachabc.com';
		}
	}

	getEngineInfo() {
		if ((<any>window).air.engineInfo) {
			return (<any>window).air.engineInfo;
		} else {
			return new Promise((resolve, reject) => {
				(<any>window).courseware.getEngineInfo(() => {
					resolve((<any>window).air.engineInfo);
				});
			});
		}
	}
	asyncCallNetworkApiGet(apiName, data): Promise<any> {
		return new Promise((resolve, reject) => {
			this.callNetworkApiGet(apiName, data, (res => {
				resolve(res);
			}));
		});
	}
	asyncCallNetworkApiPost(uri, data): Promise<any> {
		return new Promise((resolve, reject) => {
			this.callNetworkApiPost(uri, data, (res) => {
				resolve(res);
			});
		});
	}

	loadOnlineBundle(bundleName, callback = null) {
		if (this.IS_BUNDLE_LOADING) {
			return;
		}
		this.IS_BUNDLE_LOADING = true;
		console.log(' in loadOnlineBundle')
		cc.find('middleLayer/BtnRight').active = false;
		cc.find('middleLayer/BtnLeft').active = false;
		cc.find('middleLayer/ExitBtn').active = false;
		this.callNetworkApiGet(`/api/template/v2/${bundleName}`, {}, (datastr) => {
			const data = JSON.parse(datastr).data;
			let sceneName, version, bondleUrl = "";

			const templateBaseUrl = `${this.DOMAIN}h5template/${data.name}/v${data.last_version}`;
			this.getConfigInfo(templateBaseUrl, (conf) => {

				if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
					sceneName = conf.ios.sceneName;
					version = conf.ios.version;
					bondleUrl = `${templateBaseUrl}/ios/${conf.ios.sceneName}`;
				} else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
					sceneName = conf.android.sceneName;
					version = conf.android.version;
					bondleUrl = `${templateBaseUrl}/android/${conf.ios.sceneName}`;
				} else {
					sceneName = conf.android.sceneName;
					version = "";
					bondleUrl = `${templateBaseUrl}/web_desktop`;
				}
				this.loadBundle(sceneName, version, bondleUrl, callback);
			});
		});
	}

	currentBundleInfo = null;
	loadBundleLock = false; // 未加载完成禁止新的加载
	reloadBundle() {
		if (this.IS_BUNDLE_LOADING) {
			return;
		}
		this.IS_BUNDLE_LOADING = true;
		console.log(' in reloadBundle');
		const { sceneName, version, bondleUrl } = this.currentBundleInfo;
		this.loadBundle(sceneName, version, bondleUrl);
	}

	async loadBundle(sceneName, version, bondleUrl, callback = null) {

		if (this.oldSceneName) {
			await this.checkRotateScreen(this.oldSceneName, sceneName);
		}

		this.assetList = [];
		this.textureList = [];
		this.assetObj = {};
		this.atlasList = [];
		this.nodeList = [];
		this.getDragonDisplayAssetList(cc.find('Canvas'));
		// this.toCleanParent();

		this.loadBundleLock = true; // 加锁
		this.currentBundleInfo = { sceneName, version, bondleUrl };
		this.showWaitingLetters();
		cc.audioEngine.stopAll();

		this.setNodeListVisible();

		// 手机端强制垃圾回收
		if (cc.sys.isNative && (cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_ANDROID)) {
			cc.sys.garbageCollect();
		}

		cc.assetManager.loadBundle(bondleUrl, { version: version }, async (err, bundle) => {
			bundle.loadScene(sceneName, null, null, (err, scene) => {
				this.loadBundleLock = false; // 加载完成 解锁

				this.courseOpenTimeStamp = Date.now();

				cc.director.runScene(scene, null, () => {
					console.log('sceneName = ' + sceneName);
					const canvas = cc.find('Canvas');
					const middleLayer = cc.find('middleLayer');

					cc.find('middleLayer/tipsLayer').active = false;

					canvas.getComponent(cc.Widget).updateAlignment();
					middleLayer.scale = canvas.width / middleLayer.width;

					// 挂载清洁骨骼机制节点
					const destroyer = cc.instantiate(cc.find('middleLayer/Destroyer'));
					destroyer.parent = cc.find('Canvas');
					destroyer.active = true;


					// 手机端强制垃圾回收
					if (cc.sys.isNative && (cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_ANDROID)) {
						cc.sys.garbageCollect();
					}		

					callback && callback();
					this.IS_BUNDLE_LOADING = false;
					this.oldSceneName = sceneName;
				});
			});
		});
	}

	setNodeListVisible() {
		const setParentVisible = (n) => {
			n.active = true;
			if (n.parent) {
				setParentVisible(n.parent);
			}
		}

		this.nodeList.forEach(node => {
			setParentVisible(node);
		});
	}

	getUUID() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}

	checkRotateScreen(oldSceneName: string, newSceneName: string) {
		const sceneNameList = ["cc_mz_link_write_03"];
		if (sceneNameList.includes(oldSceneName) || sceneNameList.includes(newSceneName)) {
			return new Promise((resolve, reject) => {
				if (sceneNameList.includes(newSceneName)) {
					// 如果已经是竖屏了
					if (cc.view.getCanvasSize().width < cc.view.getCanvasSize().height) {
						resolve(null);
						return;
					}
					// 旋转到竖屏
					(<any>window).courseware.onConfigurationPortrait({}, async () => {
						while (cc.view.getCanvasSize().width > cc.view.getCanvasSize().height) {
							await asyncDelay(0.1);
						}
						resolve(null);
					});
				} else {
					// 如果已经是横屏了
					if (cc.view.getCanvasSize().width > cc.view.getCanvasSize().height) {
						resolve(null);
						return;
					}
					// 旋转到横屏
					(<any>window).courseware.onConfigurationLandscape({}, async () => {
						while (cc.view.getCanvasSize().width < cc.view.getCanvasSize().height) {
							await asyncDelay(0.1);
						}
						resolve(null);
					});
				}
			});
		}
	}

	courses = null;
	courseIndex = 0;
	courseItem = null;
	courseOpenTimeStamp = null;
	loadOnlineCourseWare(courseId, linkFlag = false, coursewareId = null) {
		if (this.IS_BUNDLE_LOADING) {
			return;
		}
		this.IS_BUNDLE_LOADING = true;

		this.showWaitingLetters();

		cc.find('middleLayer/ram').active = false;
		cc.find('middleLayer/cross').active = false;
		cc.find('middleLayer/free').active = false;

		let api = `/api/courseware/v2/${courseId}/list`;
		if (linkFlag === true) {
			api = `/api/courseware/v2/${courseId}/eq/level/list`;
		}

		this.callNetworkApiGet(api, {}, (datastr) => {
			const data = JSON.parse(datastr);
			if (data.rows && data.rows.length > 0) {
				this.courses = data.rows;
				if (coursewareId) {
					this.courseIndex = data.rows.findIndex(item => item.id == coursewareId);
				} else {
					this.courseIndex = data.index || 0;
				}
				this.courseItem = data.rows[this.courseIndex];
			} else {
				this.hideWaitingLetters();
				this.showTips(`内容还未制作`);
				this.IS_BUNDLE_LOADING = false;
				return;
			}
			this.loadPageBundle(() => {
				if (this.courses && this.courses.length > 1 && this.courseIndex < this.courses.length - 1) {
					cc.find('middleLayer/BtnRight').active = true;
				} else {
					cc.find('middleLayer/BtnRight').active = false;
				}
				if (this.courseIndex > 0) {
					cc.find('middleLayer/BtnLeft').active = false;
				}
				cc.find('middleLayer/ExitBtn').active = true;
			});
		});
	}

	loadPageBundle(callback = null) {
		console.log(" in loadPageBundle");
		let sceneName, version, bondleUrl = "";
		const templateBaseUrl = `${this.DOMAIN}h5template/${this.courseItem.template_name}/v${this.courseItem.last_version}`;
		this.getConfigInfo(templateBaseUrl, (conf) => {

			if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
				sceneName = conf.ios.sceneName;
				version = conf.ios.version;
				bondleUrl = `${templateBaseUrl}/ios/${conf.ios.sceneName}`;
			} else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
				sceneName = conf.android.sceneName;
				version = conf.android.version;
				bondleUrl = `${templateBaseUrl}/android/${conf.ios.sceneName}`;
			} else {
				sceneName = conf.android.sceneName;
				version = "";
				bondleUrl = `${templateBaseUrl}/web_desktop`;
			}
			this.loadBundle(sceneName, version, bondleUrl, callback);
		});
	}

	goPrePage() {
		this.goTarIndexPage(this.courseIndex - 1);
	}
	goNextPage() {
		console.log("====goNextPage====");
		this.goTarIndexPage(this.courseIndex + 1);
	}
	goTarIndexPage(index) {
		if (this.IS_BUNDLE_LOADING) {
			return;
		}
		this.IS_BUNDLE_LOADING = true;
		if (!this.courses || index == this.courseIndex || index < 0 || index > this.courses.length - 1) {
			this.IS_BUNDLE_LOADING = false;
			return;
		}

		this.showWaitingLetters();
		
		(<any>window).courseware.freeAllOcMethod();

		this.courseIndex = index;
		this.courseItem = this.courses[this.courseIndex];

		if (this.courseIndex < this.courses.length - 1) {
			cc.find('middleLayer/BtnRight').active = true;
		} else {
			cc.find('middleLayer/BtnRight').active = false;
		}
		this.loadPageBundle();
	}

	log(str: string) {
		console.log(str);
	}

	showTips(str: string) {
		const tipsNode = new cc.Node();
		tipsNode.parent = cc.find('Canvas');
		tipsNode.zIndex = 100;

		const bg = cc.instantiate(cc.find('middleLayer/bg'));
		bg.parent = tipsNode;
		bg.active = true;
		bg.color = cc.color(100, 100, 100);

		const labelNode = new cc.Node();
		labelNode.parent = tipsNode;
		const label = labelNode.addComponent(cc.Label);
		label.string = str;

		bg.width = 200;
		bg.height = labelNode.height + 20;

		cc.tween(tipsNode)
			.set({ opacity: 255 })
			.delay(1)
			.to(1, { opacity: 0 })
			.removeSelf()
			.start();
	}

	async clearDragonDisplayAssetList() {
		if (this.atlasList.length == 0) {
			return;
		}

		this.setNodeListVisible();

		for (let i=0; i<this.atlasList.length; i++) {
			const atlas = this.atlasList[i];
			const asset = this.assetList[i];
			const texture = this.textureList[i];
			const node = this.nodeList[i];


			atlas.decRef();
			cc.assetManager.releaseAsset(atlas);
			atlas.destroy();

			asset.decRef();
			cc.assetManager.releaseAsset(asset);
			asset.destroy();


			// node.active = false;
			// node.removeFromParent();

			texture.decRef();

		}

		
	}

	// 原始方法
	clearDragonDisplayAssetList3() {

		[ ...this.atlasList , ...this.assetList].forEach(asset => {
			asset.decRef();
			cc.assetManager.releaseAsset(asset);
			asset.destroy();
		});

		this.nodeList.forEach(node => {
			node.active = false;
			node.removeFromParent();
		});

		this.textureList.forEach(texture => {
			texture.decRef();
		});
		
	}


	assetObj = null;
	nodeList = null;
	atlasList = null;
	assetList = null;
	textureList = null;
	getDragonDisplayAssetList(node) {

		const dragonDisplay = node.getComponent(dragonBones.ArmatureDisplay);
		if (dragonDisplay) {
			const atlas = dragonDisplay.dragonAtlasAsset;
			const asset = dragonDisplay.dragonAsset;

			if (atlas && atlas.texture) {
				if (atlas.texture.nativeUrl.includes('h5template')) {
					node.children.forEach(child => {
						this.getDragonDisplayAssetList(child);
					});
					return;
				}

				this.nodeList.push(node);
				this.atlasList.push(atlas);
				this.assetList.push(asset);
				this.textureList.push(atlas.texture);

				console.log('汪汪汪: atlas.texture.nativeUrl = ' + atlas.texture.nativeUrl);
			}
		}

		node.children.forEach(child => {
			this.getDragonDisplayAssetList(child);
		});
	}

	toCleanParent() {
		const canvas = cc.find("Canvas");

		this.nodeList.forEach(node => {
			node.parent = canvas;
		});
	}

}