import { asyncDelay, asyncTweenTo, getSpriteFrimeByUrl, nextTick, jelly, onHomeworkFinish, playAudio, playAudioByUrl, RandomInt } from "../script/util_TXZS_G_003";
import { defaultData } from "../script/defaultData_TXZS_G_003";

cc.Class({

	extends: cc.Component,

	properties: {
	},

	// 生命周期 onLoad
	onLoad() {
		this.initSceneData();
		this.initSize();
	},

	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	initSceneData() {
		this._imageResList = [];
		this._audioResList = [];
		this._animaResList = [];
	},

	_designSize: null,  // 设计分辨率
	_frameSize: null,  // 屏幕分辨率
	_mapScaleMin: null,  // 场景中常用缩放（取大值）
	_mapScaleMax: null,  // 场景中常用缩放（取小值）
	_cocosScale: null,  // cocos 自缩放 （较少用到）
	initSize() {
		// 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
		let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
		let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
		let f = screen_size >= design_size
		cc.Canvas.instance.fitHeight = f
		cc.Canvas.instance.fitWidth = !f

		const frameSize = cc.view.getFrameSize();
		this._frameSize = frameSize;

		this._designSize = cc.view.getDesignResolutionSize();

		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		this._cocosScale = Math.min(sx, sy);

		sx = frameSize.width / this._designSize.width;
		sy = frameSize.height / this._designSize.height;
		this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
		this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;
	},


	// 生命周期 start
	start() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}

		getData((data) => {
			this.data = this.translateData(data.rows) || this.getDefaultData();
			console.log('data:', data);
			this.preloadItem()
		})
	},

	getData(func) {
		if (window && window.courseware) {
			window.courseware.getData(func, 'scene');
			return;
		}

		const middleLayer = cc.find('middleLayer');
		if (middleLayer) {
			const middleLayerComponent = middleLayer.getComponent('middleLayer');
			middleLayerComponent.getData(func);
			return;
		}

		func(this.getDefaultData());
	},

	getDefaultData() {
		return defaultData;
	},

	// 数据转换 - 把听写助手传进来的数据转换成这个模板需要的游戏数据
    translateData(data) {
		// 组装题目数据
		function getQuestionData(itemData, index) {
			const qItems = [];
			const letters = itemData.text_en.split("");
			const arrText = [];
			letters.forEach(item=>{
				arrText.push(item)
				qItems.push({
					"audio": "",
					"word": item
				})
			})
            return {
			  "auido": itemData.audio_url,
			  "image": "",
			  "showText": itemData.text_cn,
			  "text": arrText.join(" "),
			  "words": qItems
			}
		}

		// data = [ { "id": 20, "pid": 19, "text_en": "what", "text_cn": "什么", "audio_url": "http://teach.cdn.ireadabc.com/36b5e5d9a5240bff453e95e2d74cece0.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/27a5b4d9525a299e3806ccd991a8e5f9.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/b9b759a25cafbadc3130201e50cf4f85.jpeg\"]", "phonetic": "[wɒt]", "description": null, "mlk": null, "data": null, "seq": 1, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 21, "pid": 19, "text_en": "is", "text_cn": "是", "audio_url": "http://teach.cdn.ireadabc.com/d7f9276c7ff13b734c74358d7580a193.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/45100afa502326955d0f03cac87f1a5b.mp3", "image_url": null, "phonetic": "[ɪz]", "description": null, "mlk": null, "data": null, "seq": 2, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 22, "pid": 19, "text_en": "what’s", "text_cn": "是什么", "audio_url": "http://teach.cdn.ireadabc.com/383082bc329464ae1580fffcd5e85d54.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/244d88fbd98972865959d1c0fe50bdac.mp3", "image_url": null, "phonetic": "[wɒts]", "description": null, "mlk": null, "data": null, "seq": 3, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 23, "pid": 19, "text_en": "your", "text_cn": "你的", "audio_url": "http://teach.cdn.ireadabc.com/09b268cd4e201e12f4f8af377308689b.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/f723a8c809b4c910b416a9a6c9e34eb8.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/808504438919f5d2849dff97f7fb0ffd.jpg\",\"http://teach.cdn.ireadabc.com/fc9d5a0d4eba960aecae0d88b0c39acd.jpg\"]", "phonetic": "[jɔː(r)]", "description": null, "mlk": null, "data": null, "seq": 4, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:48:59.000Z", "del": 0 }, { "id": 24, "pid": 19, "text_en": "name", "text_cn": "名字", "audio_url": "http://teach.cdn.ireadabc.com/60bf983a10741a0796a3a71d1c0b5907.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/0fa9f2cc4c971d870889d7b80976654f.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a0d9907a44d617784b533dc920647dee.jpg\"]", "phonetic": "[neɪm]", "description": null, "mlk": null, "data": null, "seq": 5, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 25, "pid": 19, "text_en": "please", "text_cn": "请", "audio_url": "http://teach.cdn.ireadabc.com/ee1c7821c46b49ba850ebefc598cdb5b.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/ac372008acb6236b6a1428a334c7f0a5.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a42594ef6c4fc5b1987d2b073ae675dd.webp\",\"http://teach.cdn.ireadabc.com/7fc1972331756f74dbcf7ae0215a809b.png\"]", "phonetic": "[pliːz]", "description": null, "mlk": null, "data": null, "seq": 6, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 26, "pid": 19, "text_en": "good", "text_cn": "好的", "audio_url": "http://teach.cdn.ireadabc.com/3aeaf5c3884ad3f00a92900ed478c77e.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/403ba0be9e118b5325e3ae8acbdd3743.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/42946cef3972cc2ddaded63ba0fc20c1.webp\"]", "phonetic": "[ɡʊd]", "description": null, "mlk": null, "data": null, "seq": 7, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:49:00.000Z", "del": 0 }, { "id": 27, "pid": 19, "text_en": "morning", "text_cn": "早晨,上午", "audio_url": "http://teach.cdn.ireadabc.com/382d219f6339f5e0980cb9b716dbac8d.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/2c9c57ed86a6ca438c486543bc8bcb88.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/ffbf1f05334754e42deff6f8f2f96d3e.jpg\",\"http://teach.cdn.ireadabc.com/b8e68519a23841f248a09293a879ffe9.jpg\",\"http://teach.cdn.ireadabc.com/d72d4b2d838e91570a3e777eaa5f9420.jpg\"]", "phonetic": "['mɔːnɪŋ]", "description": null, "mlk": null, "data": null, "seq": 8, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:49:00.000Z", "del": 0 }, { "id": 28, "pid": 19, "text_en": "Ms.", "text_cn": "女士", "audio_url": "http://teach.cdn.ireadabc.com/81c51b5b602e3687c6b220727c5e5f55.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/5476bff8440fc49bebad504a0bd86eba.mp3", "image_url": null, "phonetic": "[miz]", "description": null, "mlk": "Ms", "data": null, "seq": 9, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T07:46:34.000Z", "del": 0 }, { "id": 29, "pid": 19, "text_en": "my", "text_cn": "我的", "audio_url": "http://teach.cdn.ireadabc.com/d4463b448d966353c3c19ae9b9e6ca71.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/cfbc278fb514c0bc9ca690f1c4df0950.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a2c2888111d4c18015a7d01d55fe93fb.jpg\",\"http://teach.cdn.ireadabc.com/98aa7a0d3243e8a361fd2973e4563f93.jpg\",\"http://teach.cdn.ireadabc.com/8a8b042372a3304b66495039eb7a92ff.jpg\",\"http://teach.cdn.ireadabc.com/da793b5cf93ae8915574f42d837dbae3.jpg\",\"http://teach.cdn.ireadabc.com/56857caeabb7b5bd49fa3054b2e45a52.webp\"]", "phonetic": "[maɪ]", "description": null, "mlk": null, "data": null, "seq": 10, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 30, "pid": 19, "text_en": "bird", "text_cn": "鸟", "audio_url": "http://teach.cdn.ireadabc.com/1ef04de98ddc59957edbc709901c60c7.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/fae76ae6e1bcb53d63d6f38838587ae0.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/7cf3efe3d56e7fe69d6a1809b567d1ae.jpeg\",\"http://teach.cdn.ireadabc.com/64b0eb3286053f0bf7672f61f9e5565a.jpeg\",\"http://teach.cdn.ireadabc.com/deb296c3696ee0940dc91ee18eb68d27.webp\"]", "phonetic": "[bɜːd]", "description": null, "mlk": null, "data": null, "seq": 11, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 31, "pid": 19, "text_en": "tweet", "text_cn": "小鸟啼叫", "audio_url": "http://teach.cdn.ireadabc.com/db4b0511e318b0725532aeba6181bd51.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/867865f1650f3512adba56c83bcb9f3e.mp3", "image_url": null, "phonetic": "[twi:t]", "description": null, "mlk": null, "data": null, "seq": 12, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 32, "pid": 19, "text_en": "a(n)", "text_cn": "一个", "audio_url": "http://teach.cdn.ireadabc.com/81eec7df521de5f8b0704fa114bc0aff.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/618b7d333097f2e96b35bb9135231918.mp3", "image_url": null, "phonetic": "[ə][ən]", "description": null, "mlk": null, "data": null, "seq": 13, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 33, "pid": 19, "text_en": "boy", "text_cn": "男孩", "audio_url": "http://teach.cdn.ireadabc.com/6c60ff7775afbb0b454f23151719e9d0.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/e27330597469d5e81f0037c5846aca48.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/1f042535eef57f88054d46f903d87e80.jpeg\"]", "phonetic": "[bɔɪ]", "description": null, "mlk": null, "data": null, "seq": 14, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 34, "pid": 19, "text_en": "girl", "text_cn": "女孩", "audio_url": "http://teach.cdn.ireadabc.com/d038b562b0c7781e718eb08550849143.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/9ad553f6e10ddc1bfeb851082f9f1d25.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/896d19830863cfc1561553ebf3b6ecbe.webp\",\"http://teach.cdn.ireadabc.com/92354ec729582b3bb2ea05851e9d0806.webp\"]", "phonetic": "[ɡɜːl]", "description": null, "mlk": null, "data": null, "seq": 15, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 35, "pid": 19, "text_en": "afternoon", "text_cn": "下午", "audio_url": "http://teach.cdn.ireadabc.com/1f70fe441cdca82832cdf7bc286796f7.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/0ab162e708e2ba9991398f10107504ab.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/e4b9c73c31c47a7441bb6ac04d558c02.jpg\",\"http://teach.cdn.ireadabc.com/d2914aad9ce834ebb057b04400609a17.jpg\",\"http://teach.cdn.ireadabc.com/0ad04d2a371a51af723a2fae92ebbf10.jpg\"]", "phonetic": "[ˌɑːftə'nuːn]", "description": null, "mlk": null, "data": null, "seq": 16, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 36, "pid": 19, "text_en": "panda", "text_cn": "熊猫", "audio_url": "http://teach.cdn.ireadabc.com/99b59a21ea78955c7e593c2f38ef31de.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/a30d8dc936cbe5e1324b293faaa6e3ce.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/e32c4771a53e118e25fc0c16de7deccb.jpg\",\"http://teach.cdn.ireadabc.com/e79e9d8a7b391b55aabeb54281ccf5a7.jpg\"]", "phonetic": "['pændə]", "description": null, "mlk": null, "data": null, "seq": 17, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 } ];

		// 按照需要的结构进行组装
		const tData = {
			"title": "Let''s Match",
			"titleAudio": "",
			"questionList": []
		}

		data.forEach((item, gIndex)=>{
			tData.questionList.push(getQuestionData(item));
		})
		return tData;
	},

	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},

	addPreloadImage() {

		this._imageResList.push({ url: this.data.pic_url });
		this._imageResList.push({ url: this.data.pic_url_2 });
	},

	addPreloadAudio() {

		this._audioResList.push({ url: this.data.audio_url });
	},

	addPreloadAnima() {

	},

	preload() {
		const preloadArr = this._imageResList.concat(this._audioResList).concat(this._animaResList);
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			this.loadEnd();
			if (window && window["air"]) {
				window["air"].hideAirClassLoading();
			}

			cc.debug.setDisplayStats(false);
		});
	},

	loadEnd() {
		this.initData();
		this.initAudio();
		this.initView();
		this.initListener();
	},

	initData() {
		this._status = {
			currentQuestionIdx: 0,
			currentSelectOption: null,
			rightOptionList: []
		}
	},

	initAudio() {

	},

	initListener() {
		const titleBtn = cc.find('Canvas/bg/title/titleLabelBg');
		titleBtn.on('click', () => {
			playAudioByUrl(this.data.titleAudio);
		});
		if (this.data.titleAudio == '') {
			titleBtn.active = false;
		}

		const btnNext = cc.find('Canvas/bg/BtnNext');
		btnNext.on('click', async () => {
			if (btnNext.canNotClick) {
				return;
			}
			btnNext.canNotClick = true;
			await jelly(btnNext);
			this.playAudioByName('button');
			this._status.currentQuestionIdx = Math.min(this._status.currentQuestionIdx + 1, this.data.questionList.length - 1);
			this.updateCurrentQuestionIdx();
			btnNext.canNotClick = false;
		});

		const btnBefore = cc.find('Canvas/bg/BtnBefore');
		btnBefore.on('click', async () => {
			if (btnBefore.canNotClick) {
				return;
			}
			btnBefore.canNotClick = true;
			await jelly(btnBefore);
			this.playAudioByName('button');
			this._status.currentQuestionIdx = Math.max(this._status.currentQuestionIdx - 1, 0);
			this.updateCurrentQuestionIdx();
			btnBefore.canNotClick = false;
		});

		const btnReplay = cc.find('Canvas/bg/BtnReplay');
		btnReplay.on('click', async () => {
			if (btnReplay.canNotClick) {
				return;
			}
			btnReplay.canNotClick = true;
			await jelly(btnReplay);
			this.shuffleQuestions();
			this.playAudioByName('button');
			this._status.currentQuestionIdx = 0;
			this.updateCurrentQuestionIdx();
			btnReplay.canNotClick = false;
		});
	},

	shuffleQuestions() {
		const oldQuestions = this.data.questionList;
		this.data.questionList = [];
		const length = oldQuestions.length;
		for (let i = 0; i < length; i++) {
			let idx = RandomInt(oldQuestions.length);
			const quesion = oldQuestions.splice(idx, 1)[0];
			this.data.questionList.push(quesion);
		}
	},

	showButtons() {
		const btnNext = cc.find('Canvas/bg/BtnNext');
		const btnBefore = cc.find('Canvas/bg/BtnBefore');
		const btnReplay = cc.find('Canvas/bg/BtnReplay');

		btnNext.active = true;
		btnBefore.active = true;

		const idx = this._status.currentQuestionIdx;
		if (idx == 0) {
			btnBefore.active = false;
		}
		if (idx == this.data.questionList.length - 1) {
			btnBefore.active = false;
			btnNext.active = false;

			btnReplay.active = true;
		}
	},

	updateCurrentQuestionIdx() {
		this.targetList.forEach(target => {
			target.removeFromParent();
		});
		this.targetList = [];
		this.optionList.forEach(option => {
			option.removeFromParent();
		});
		this.optionList = [];

		this._status.currentSelectOption = null;
		this._status.rightOptionList = [];

		this.initView();
	},

	onSizeChanged() {
		cc.director.loadScene(cc.director.getScene().name);
	},

	initView() {
		cc.find('Canvas').on('size-changed', this.onSizeChanged.bind(this));
		this.initBg();
		this.initTitle();
		this.initOptions();
		this.initTargets();
		this.initResult();
		this.initButtons();
		// this.initImage();
		this.initMiddleText();
	},

	initImage() {
		const image = cc.find('Canvas/bg/ImgMiddle/Mask/QuestionImg');
		const idx = this._status.currentQuestionIdx;
		const url = this.data.questionList[idx].image;
		const mask = cc.find('Canvas/bg/ImgMiddle/Mask');
		if (!url || url == '') {
			image.active = false;
		} else {
			image.active = true;
			getSpriteFrimeByUrl(url, (sf) => {
				const width = sf.getTexture().width;
				const height = sf.getTexture().height;
				const scale = Math.min(mask.width / width, mask.height / height);
				image.getComponent(cc.Sprite).spriteFrame = sf;
				image.scale = scale;
			});
		}
	},

	initMiddleText() {
		const textLabel = cc.find("Canvas/bg/textMiddle/Label").getComponent(cc.Label);
		const idx = this._status.currentQuestionIdx;
		const text = this.data.questionList[idx].showText;
		textLabel.string = text;
	},

	initBg() {
		const bgNode = cc.find('Canvas/bg');
		// bgNode.scale = this._mapScaleMax;
	},

	initTitle() {
		const label = cc.find('Canvas/bg/title/titleLabelBg/Label');
		label.getComponent(cc.Label).string = this.data.title;
		nextTick(() => {
			label.scale = Math.min(1, 230 / label.width);
		});
	},

	initOptions() {
		const idx = this._status.currentQuestionIdx;
		const optionList = [];
		this.data.questionList[idx].words.forEach((item, idx) => {
			const option = cc.instantiate(cc.find('OptionWhite'));
			option.x = 0;
			option.y = 0;
			option.idx = item.word;
			optionList.push(option);

			const optionWhite = cc.find('OptionWhite', option);
			optionWhite.on('touchstart', this.onOptionTouchStart.bind(this, item));
			optionWhite.on('touchmove', this.onOptionTouchMove.bind(this));
			optionWhite.on('touchend', this.onOptionTouchEnd.bind(this));
			optionWhite.on('touchcancel', this.onOptionTouchEnd.bind(this));
			optionWhite.on('click', () => {
				optionWhite.removeComponent(cc.Widget);
				this._status.currentSelectOption = optionWhite;
			});

			const label = cc.find('OptionWhite/Label', option);
			label.getComponent(cc.Label).string = item.word;
			nextTick(() => {
				option.width = Math.max(label.width + 30, 70);
			});
		});

		this.optionList = [];
		const length = optionList.length;
		for (let i = 0; i < length; i++) {
			const option = optionList.splice(RandomInt(optionList.length), 1)[0];
			this.optionList.push(option);
		}

		const optionPanel = cc.find('Canvas/bg/OptionPanel');
		this.optionList.forEach(option => {
			option.parent = optionPanel;
		});

		nextTick(() => {
			const totalWidth = this.optionList.reduce((width, option) => width + option.width, 0);
			const scale = Math.min(1, optionPanel.width / totalWidth);
			optionPanel.scale = scale;
		});
	},

	onOptionTouchStart(item, event) {
		const optionWhite = event.target;
		if (optionWhite.over) {
			return;
		}
		optionWhite.startPos = optionWhite.convertToNodeSpaceAR(event.getLocation());
		playAudioByUrl(item.audio);
	},

	onOptionTouchMove(event) {
		const optionWhite = event.target;
		if (optionWhite.over) {
			return;
		}
		optionWhite.removeComponent(cc.Widget);
		let pos = event.getLocation();
		pos = pos.sub(optionWhite.startPos);
		pos = optionWhite.parent.convertToNodeSpaceAR(pos)
		optionWhite.x = pos.x;
		optionWhite.y = pos.y;
	},

	onOptionTouchEnd(event) {
		const optionWhite = event.target;
		if (optionWhite.over) {
			return;
		}
		let rightTarget = null;
		this.targetList.forEach(target => {
			if (this.checkOptionRight(optionWhite, target)) {
				rightTarget = target;
			}
		});
		if (rightTarget) {
			optionWhite.over = true;
			this.optionRight(optionWhite, rightTarget);
		} else {
			this.optionGoBack(optionWhite);
		}
	},

	checkOptionRight(option, target) {
		const pos = option.parent.convertToWorldSpaceAR(option.getPosition());
		const targetPos = target.convertToNodeSpaceAR(pos);
		if (target.idx.toLowerCase() == option.parent.idx.toLowerCase()) {
			if (-target.width / 2 < targetPos.x && targetPos.x < target.width / 2) {
				if (-target.height / 2 < targetPos.y && targetPos.y < target.height / 2) {
					return true;
				}
			}
		}
		return false;
	},

	optionGoBack(node) {
		const time = Math.min(node.getPosition().mag() / 800, 0.3);
		cc.tween(node)
			.to(time, { x: 0, y: 0 }, { easing: 'quadInOut' })
			.start();

		this._status.currentSelectOption = null;
		this.playAudioByName('wrong');
	},

	async optionRight(option, target) {
		const pos = option.parent.convertToNodeSpaceAR(target.convertToWorldSpaceAR(cc.v2(0, 0)));

		this.updateTargetWidths(target, option.width);
		await asyncTweenTo(option, 0.2, { x: pos.x, y: pos.y }, { easing: 'quadInOut' });

		const brownNode = cc.find('OptionBrown', target)
		asyncTweenTo(brownNode, 0.15, { opacity: 0 });

		this.playAudioByName('right');

		const blueNode = cc.find('OptionBlue', target)
		asyncTweenTo(blueNode, 0.15, { opacity: 255 });

		this.createShiningStarsRoundNode(blueNode);

		await asyncTweenTo(option, 0.15, { opacity: 0 });

		this._status.rightOptionList.push(target.idx);

		const idx = this._status.currentQuestionIdx;
		if (this._status.rightOptionList.length == this.data.questionList[idx].words.length) {
			this.showResult();
		}
	},

	async updateTargetWidths(targetNode, width) {
		let otherNodeList = [];
		this.targetList.forEach((target) => {
			if (target == targetNode) {
				return;
			}
			if (this._status.rightOptionList.findIndex(index => index == target.idx) == -1) {
				otherNodeList.push(target);
			}
		});

		const totalWidth = targetNode.width + otherNodeList.reduce((width, node) => width + node.width, 0);

		cc.tween(targetNode)
			.to(0.2, { width: width }, { easing: 'quadInOut' })
			.start();

		otherNodeList.forEach(node => {
			cc.tween(node)
				.to(0.2, { width: (totalWidth - width) / otherNodeList.length }, { easing: 'quadInOut' })
				.start();
		});
	},

	initTargets() {
		const idx = this._status.currentQuestionIdx;
		const targetPanel = cc.find('Canvas/bg/TargetPanel');
		this.targetList = [];
		this.data.questionList[idx].words.forEach((item, idx) => {
			const target = cc.instantiate(cc.find('OptionBrown'));
			target.x = 0;
			target.y = 0;
			target.parent = targetPanel;
			target.idx = item.word;
			this.targetList.push(target);

			const label = cc.find('OptionBlue/Label', target);
			label.getComponent(cc.Label).string = item.word;

			target.on('click', () => {
				const option = this._status.currentSelectOption;
				if (!option) {
					return;
				}
				if (option.parent.idx.toLowerCase() == target.idx.toLowerCase()) {
					option.over = true;
					this.optionRight(option, target);
				} else {
					this.optionGoBack(option);
				}
			});

			nextTick(() => {
				target.width = Math.max(label.width + 30, 70);
			});
		});

		nextTick(() => {
			const totalWidth = this.optionList.reduce((total, option) => total + option.width, 0);
			const scale = Math.min(1, targetPanel.width / totalWidth);
			this.targetList.forEach(target => {
				target.width = totalWidth / this.optionList.length;
			});
			targetPanel.scale = scale;
		});
	},

	initResult() {
		const idx = this._status.currentQuestionIdx;
		const resultLabel = cc.find('Canvas/bg/LabelGreenBg/Label');
		resultLabel.getComponent(cc.Label).string = this.data.questionList[idx].text;

		const bg = cc.find('Canvas/bg');
		const mounton = cc.find('Canvas/bg/mounton_right');
		const labelGreenBg = cc.find('Canvas/bg/LabelGreenBg');
		labelGreenBg.y = mounton.y + mounton.height / 2 - labelGreenBg.height / 2;
		labelGreenBg.width = bg.width - 20;

		nextTick(() => {
			resultLabel.scale = Math.min(1, (labelGreenBg.width - 50) / resultLabel.width);

			resultLabel.parent.active = false;
		});

		const car = cc.find('Canvas/bg/ImgCar');

		car.stopAllActions();
		car.x = bg.width + 300;
		car.y = labelGreenBg.y + labelGreenBg.height / 2 + car.height / 2;
		asyncTweenTo(car, 1, { x: bg.width / 2 - 35 }, { easing: 'quadInOut' });

		const targetPanel = cc.find('Canvas/bg/TargetPanel');
		targetPanel.y = labelGreenBg.y;

		const optionPanel = cc.find('Canvas/bg/OptionPanel');
		optionPanel.y = labelGreenBg.y - mounton.height * (6 / 10);
	},

	initButtons() {
		const btnNext = cc.find('Canvas/bg/BtnNext');
		const btnBefore = cc.find('Canvas/bg/BtnBefore');
		const btnReplay = cc.find('Canvas/bg/BtnReplay');

		btnNext.active = false;
		btnBefore.active = false;
		btnReplay.active = false;
	},

	async showResult() {
		this.targetList.forEach(target => {
			asyncTweenTo(target, 0.2, { opacity: 0 });
		});
		const resultNode = cc.find('Canvas/bg/LabelGreenBg');
		resultNode.active = true;
		resultNode.opacity = 0;
		const starList = this.createShiningStarsRoundNode(resultNode);
		await asyncTweenTo(resultNode, 0.2, { opacity: 255 });

		this.playAudioByName('complete').then(res=>{
			const idx = this._status.currentQuestionIdx;
			const url = this.data.questionList[idx].auido;
			if(url) {
				playAudioByUrl(url, ()=>{
					this.showButtons();
				});
			} else {
				this.showButtons();
			}
		});

		const car = cc.find('Canvas/bg/ImgCar');
		await asyncTweenTo(car, 2, { x: -cc.find('Canvas/bg').width }, { easing: 'quadInOut' });

		starList.forEach(star => {
			cc.tween(star)
				.to(1, { opacity: 0 })
				.removeSelf()
				.start();
		});

		

		if (this._status.currentQuestionIdx == this.data.questionList.length - 1) {
			this.showFlowers();
		}
	},

	createShiningStarsRoundNode(baseNode) {
		const width = baseNode.width;
		const height = baseNode.height;

		const starList = [];

		for (let i = 0; i < width / 20; i++) {
			const pos = cc.v2(RandomInt(-width / 2, width / 2), height * (RandomInt(-1, 1) + 0.5) + RandomInt(-10, 10));
			const star = this.createOneShiningStar(pos, baseNode);
			starList.push(star);
		}
		for (let i = 0; i < height / 20; i++) {
			const pos = cc.v2(width * (RandomInt(-1, 1) + 0.5) + RandomInt(-10, 10), RandomInt(-height / 2, height / 2));
			const star = this.createOneShiningStar(pos, baseNode);
			starList.push(star);
		}
		return starList;
	},

	createOneShiningStar(pos, baseNode) {
		const star = cc.instantiate(cc.find('ImgStar'));
		star.x = pos.x;
		star.y = pos.y;
		star.parent = baseNode;
		star.scale = 0;

		const scale = Math.random() * 0.7 + 0.3;

		const time = 0.5;

		cc.tween(star)
			.delay(Math.random())
			.call(() => {
				cc.tween(star)
					.to(time, { scale: scale })
					.to(time, { scale: 0 })
					.union()
					.repeatForever()
					.start();
			})
			.delay(1)
			.removeSelf()
			.start();

		return star;
	},

	playAudioByName(audioName) {
		return new Promise((resolve, reject) => {
			try {
				const audioNode = cc.find('AudioNode/' + audioName);
				const audioClip = audioNode.getComponent(cc.AudioSource).clip;
				playAudio(audioClip, resolve);
			} catch (e) {
				reject(e);
			}
		});
	},

	showFlowers() {
		this.playAudioByName('flower');
		this.showAllFirework(cc.find('Canvas/bg'), cc.find('PaperBase').children);
	},

	async showAllFirework(parentNode, nodeList) {
		for (let i = 0; i < 6; i++) {
			this.showFirework(cc.v2(0, -parentNode.height / 2), parentNode, nodeList, parentNode.width * 2 / 3, parentNode.height * 1.3);
			await asyncDelay(0.1);
		}
	},

	showFirework(pos, parentNode, nodeList, width = 200, height = 200, number = 30) {
		for (let i = 0; i < number; i++) {
			const quad = this.createQuads(pos, parentNode, nodeList);
			const targetX = RandomInt(width / 2, -width / 2);
			const targetY = RandomInt(height);

			cc.tween(quad)
				.by(0.5, { x: targetX })
				.by(3, { x: targetX * 2 })
				.start();

			cc.tween(quad)
				.by(0.5, { y: targetY }, { easing: 'quadOut' })
				.to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
				.removeSelf()
				.start();

			cc.tween(quad)
				.delay(1)
				.to(1.5, { opacity: 0 })
				.start();
		}
	},

	createQuads(pos, parentNode, nodeList) {
		const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
		quadBase.x = pos.x;
		quadBase.y = pos.y;
		quadBase.z = pos.z;
		quadBase.angle = RandomInt(180);
		quadBase.parent = parentNode;

		const quad = quadBase.getChildByName('quad');
		quad.x = 0;
		quad.y = 0;
		quad.angle = RandomInt(180);

		const paper = quad.getChildByName('paper');
		paper.scaleX = Math.random() * 0.5 + 0.5;
		paper.scaleY = Math.random() * 0.5 + 0.5;

		quadBase.scaleX = Math.random();
		cc.tween(quadBase)
			.to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
			.call(() => {
				const time = Math.random() * 0.2;
				cc.tween(quadBase)
					.to(0.1 + time, { scaleX: -1 })
					.to(0.1 + time, { scaleX: 1 })
					.union()
					.repeatForever()
					.start();
			})
			.start();

		return quadBase;
	},
});
