import { initAir } from './air';

cc.Class({
	extends: cc.Component,
	properties: {
	},

	async callNetworkApiPost(uri, data, baseUrl = null) {
		if (!baseUrl) {
			baseUrl = await this.getBaseUrl();
		}
		const resData = await new Promise((resolve, reject) => {
			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) {
					resolve(JSON.parse(xhr.responseText));
				}
			}
			xhr.send(JSON.stringify(data));
		});
		return resData;
	},

	async callNetworkApiGet(uri, data, baseUrl = null) {
		if (!baseUrl) {
			baseUrl = await this.getBaseUrl();
		}
		const resData = await new Promise((resolve, reject) => {
			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)) {
					resolve(JSON.parse(xhr.responseText));
				}
			};
			const url = `${baseUrl}${uri}${queryStr}`;
			console.warn('url = ' + url);
			xhr.open('GET', url, true);
			xhr.send();
		});
		return resData;
	},

	async getBaseUrl() {
		const engineInfo = await this.getEngineInfo();
		const { isDev, uuid } = JSON.parse(engineInfo);
		this.isDev = isDev;
		this.engineCode = uuid;
		if (isDev == 1) {
			return 'http://api.iplayabc.com';
		} else {
			return 'http://api.iplayabc.com';
		}
	},

	getEngineInfo() {
		if (window.air.engineInfo) {
			return window.air.engineInfo;
		} else {
			return new Promise((resolve, reject) => {
				window.courseware.getEngineInfo(() => {
					resolve(window.air.engineInfo);
				});
			});
		}
	},

	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;",
				""
			);
		}
	}, 
	// 需要预加载的数量
	preloadCount: null,
	// 统计已加载的数量
	loadedCount: null,

	isDev: null,
	engineCode: null, // 机器唯一编码

	currentSceneName: null, // 当前模板名称
	canTouch: null,

	// 统一释放异步资源的方法
	async onLoad() {
		this.preloadCount = 0;
		this.loadedCount = 0;

		
		initAir(this);
		this.reWriteAir();
		await this.getBaseUrl();
		
		this.canTouch = true;
	},

	start() {
		this.node.zIndex = 9999;
		cc.game.addPersistRootNode(this.node);


		this.initListener();
		this.showWaitingLetters();
		// this.onMiddleLayerLoadingFinish();

		const words = cc.sys.localStorage.getItem("wordIds");
		if (words) {
			this.loadOnlineBundle("wordgame_learning");
		} else {
			this.loadOnlineBundle("wordgame_syllabus");
		}
	},

	initListener() {
		cc.find(`middleLayer/book`).on('click', () => {
			if (!this.canTouch) {
				return;
			}
			this.canTouch = false;
			this.showWaitingLetters();
			cc.audioEngine.stopAll();
			this.loadOnlineBundle("wordgame_syllabus");
			setTimeout(() => {
				this.canTouch = true;
			}, 200);
		});
		cc.find(`middleLayer/game`).on('click', () => {
			if (!this.canTouch) {
				return;
			}
			this.canTouch = false;
			this.showWaitingLetters();
			cc.audioEngine.stopAll();
			this.loadOnlineBundle("wordgame_playing");
			setTimeout(() => {
				this.canTouch = true;
			}, 200);
		});
		cc.find(`middleLayer/exit`).on('click', () => {
			if (!this.canTouch) {
				return;
			}
			this.canTouch = false;
			this.showWaitingLetters();
			cc.audioEngine.stopAll();
			this.loadOnlineBundle("wordgame_learning");
			setTimeout(() => {
				this.canTouch = true;
			}, 200);
		});
	},

	async saveAnswer(data) {
		console.log(`saveAnswer==`, data);
		await this.callNetworkApiPost(`/v1/terminal/save/learnresult`, {engine_code: this.engineCode, w_id: data.id, word: data.text_en});
	},

	reWriteAir() {
    window.courseware.getData = async (callback) => {
			const data = await this.callNetworkApiGet("/v1/preference/words", {user_code: this.engineCode});
			callback && callback(data.rows);
    }
    if (!window.air) {
      window.air = {};
    }
    window.air.hideAirClassLoading = () => {
      window.air.onCourseInScreen && window.air.onCourseInScreen(() => {
        console.log("***成功调用onCourseInScreen***");
        window.air.onCourseInScreen = null;
      });
      this.hideWaitingLetters();
    }
  },
  
	async loadOnlineBundle(bundleName) {

		if (bundleName === "wordgame_syllabus") {
			cc.find(`middleLayer/book`).active = false;
			cc.find(`middleLayer/game`).active = false;
			cc.find(`middleLayer/exit`).active = false;
		}
		if (bundleName === "wordgame_learning") {
			cc.find(`middleLayer/book`).active = true;
			cc.find(`middleLayer/game`).active = true;
			cc.find(`middleLayer/exit`).active = false;
		}
		if (bundleName === "wordgame_playing") {
			cc.find(`middleLayer/book`).active = false;
			cc.find(`middleLayer/game`).active = false;
			cc.find(`middleLayer/exit`).active = true;
		}

		cc.audioEngine.stopAll();
		this.currentSceneName = bundleName;

		this.showWaitingLetters();
		const data = await this.callNetworkApiGet(`/api/template/v1/${bundleName}`, {}, `http://openapi.iteachabc.com`);
		let configData = null;
		if (cc.sys.os == cc.sys.OS_IOS) {
			configData = data.data.conf.ios;
		} else if (cc.sys.os == cc.sys.OS_ANDROID) {
			configData = data.data.conf.android;
		} else {
			configData = data.data.conf.web_desktop;
		}
		const sceneName = configData.sceneName;
		const version = configData.version;
		const bondleUrl = configData.bondleUrl;
		this.loadBundle(sceneName, version, bondleUrl);
	},
	loadBundle(sceneName, version, bondleUrl) {
		cc.assetManager.loadBundle(bondleUrl, { version: version }, async (err, bundle) => {
			if (err) {
				console.error(err);
				return;
			}
			bundle.loadScene(sceneName, null, null, (err, scene) => {
				if (err) {
					console.error(err);
				}
				cc.director.runScene(scene, null, () => {
					const Canvas = cc.find('Canvas');
					const middleLayer = cc.find('middleLayer');
					Canvas.getComponent(cc.Widget).updateAlignment();
					middleLayer.scale = Canvas.width / middleLayer.width;
				});
			});
		});
	},

	showWaitingLetters() {
		if (this.isShowWaiting) {
			return;
		}
		this.isShowWaiting = true;
		const animNode = cc.find(`middleLayer/loadingbg`);
		animNode.active = true;
		const anim = cc.find(`loading`, animNode).getComponent(cc.Animation);
		anim.play();
	},

	hideWaitingLetters() {
		const animNode = cc.find(`middleLayer/loadingbg`);
		const anim = cc.find(`loading`, animNode).getComponent(cc.Animation);
		anim.stop();
		animNode.active = false;
		this.isShowWaiting = false;
	},

	getRainbowColorList() {
		return [
			cc.color(255, 255, 0),
			cc.color(128, 255, 0),
			cc.color(0, 255, 0),
			cc.color(0, 0, 0),

			cc.color(0, 255, 128),
			cc.color(0, 255, 255),

			cc.color(0, 128, 255),
			cc.color(0, 0, 255),
			cc.color(128, 0, 255),
			cc.color(255, 0, 255),
			cc.color(255, 0, 128),

			cc.color(255, 0, 0),
			cc.color(255, 128, 0),
			cc.color(255, 255, 0),
		];
	},

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

});
