import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";
import { itemData } from "./data";
import { hyLoader } from "./hyLoader";
import GameManager from "./gameManager";
import pg from "./pg";
import ani from "./ani";
import { asyncDelay, RandomInt, showFireworks } from "../script/utils";

cc.Class({

	extends: cc.Component,

	properties: {
	},

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

	showLog(str) {
		const node = cc.find('middleLayer');
		if (node) {
			node.getComponent('middleLayer').showLog(str);
		} else {
			cc.log(str);
		}
	},

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

	_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) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.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;
	},

	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);
		// });
		const preloadArr = [
			...this._imageResList,
			...this._audioResList,
			...this._animaResList
		];
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			// this.loadEnd();

			if (window && window["air"]) {
				// cc.find('Canvas').opacity = 0;
				window.air.onCourseInScreen = (next) => {
					// cc.find('Canvas').opacity = 255;
					this.loadEnd();
					next();
				}
				window.air.hideAirClassLoading();
			} else {
				this.loadEnd();
			}

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

	//---------------------------------项目代码开始---------------------------------
	loadEnd() {
		cc.macro.ENABLE_MULTI_TOUCH = false;
		this.initData();
		this.initSingleData();
		this.initAudio();
		this.initView();
		this.initEvent();
	},




	//全局游戏
	_gameCode: null,
	resultArr: null,
	initData() {
		//数据解析
		GameManager.getIns().parseData(this.data);
		this._gameCode = 0;
		this.resultArr = [];
	},
	//单局游戏
	_cantouch: null,
	_cardPage: null,
	_cardLayout: null,
	_cardTouchItems: null,
	_successItems: null,
	initSingleData() {
		this._cat = GameManager.getIns().cat;
		this._tryagain = GameManager.getIns().tryagain;
		this._stageData = GameManager.getIns().getStageData();
		GameManager.getIns().setState(0);//调用数组中的数据，同时设置关卡状态为0
		// console.log("1")
		// this._title = GameManager.getIns().getTitle();
		// this._zhuClass = GameManager.getIns().getZhuClass();
		// // 所有全局变量 默认都是null 
		// this._cantouch = 0;
		// //界面用数据
		// this._cardTouchItems = [];
		// this._successItems = [];
		// this._cardPage = CardManager.getIns().getPage();
		// cc.log(this._cardPage);
	},
	initAudio() {
	},
	initView() {
		this.initLayout();
	},
	initLayout() {
		if (GameManager.getIns().getState() == 0) {
			this.state0InitPart();
		} else if (GameManager.getIns().getState() == 1) {
			this.state1StartPlay();
		} else if (GameManager.getIns().getState() == 2) {
			this.state2ComplatePlay();
		} else if (GameManager.getIns().getState() == 3) {
			this.state3GoodJob();
		} else if (GameManager.getIns().getState() == 4) {
			this.state4TryAgain();
		} else if (GameManager.getIns().getState() == 5) {
			this.state5Finish();
		} else if (GameManager.getIns().getState() == 6) {

		}
	},
	initEvent() {
		let btn_mao = pg.view.find(this, "btn_mao")
		let btn_carton = pg.view.find(this, "btn_carton")
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");
		let layout_normal = pg.view.find(this, "card_group/layout_normal");

		pg.view.touchOn(btn_record, this.onTouchRecord, this);//注册按钮监听
		pg.view.touchOn(btn_next, this.onTouchNext, this);
		pg.view.touchOn(btn_return, this.onTouchReturn, this);
		pg.view.touchOn(btn_recording, this.onTouchRecording, this);
		pg.view.touchOn(btn_replay, this.onTouchReplay, this);
		pg.view.touchOn(btn_picture, this.onTouchPicture, this);
		pg.view.touchOn(btn_carton, this.onTouchCarton, this);
		pg.view.touchOn(icon_ex, this.onTouchWord, this);
		pg.view.touchOn(layout_normal, this.onTouchWord, this);
		pg.view.touchOn(btn_mao, this.onTouchCat, this);
	},
	state0InitPart() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");
		let layout_normal = pg.view.find(this, "card_group/layout_normal");
		layout_normal.removeAllChildren();
		layout_normal.opacity = 0;
		let layout_card = pg.view.find(this, "card_group/layout_card");
		cc.find("card_group/card_bg2", this.node).opacity = 0;
		layout_card.removeAllChildren();
		pg.view.visible(pg.view.find(this, "card_group/slider"), false);
		this.hideRestartBtn();
		pg.view.visible(btn_record, false);
		pg.view.visible(end, false);//不显示的内容用false
		pg.view.visible(end_success, false);
		pg.view.visible(icon_ex, false);
		//更换书的样子
		pg.view.visible(btn_next, true);//显示的内容用true
		pg.view.visible(btn_return, true);
		// let bg_book_img = this._stageData.img;//从数组中调取img数据
		// pg.view.setNetImg(bg_book, bg_book_img);//与界面的节点绑定
		//拓展加载动画的内容
		this.animationName = "";
		this._tryagainCount = 0;

		if (!this._cat || !this._cat.start || this._catStartPlayed) {
			pg.view.loadDB(carton, { ske: this._stageData.cartoonSke, tex: this._stageData.cartoonTex, png: this._stageData.cartoonPng }).then((animationName) => {
				this.animationName = animationName;
				GameManager.getIns().setState(1);
				this.initLayout()//完成后直接进入下一步
			})
		} else {
			this.setMaoAni("begin");
			pg.audio.playAudioByUrl(this._cat.start).then(() => {
				this.setMaoAni("normal");
				this._catStartPlayed = true;
				pg.view.loadDB(carton, { ske: this._stageData.cartoonSke, tex: this._stageData.cartoonTex, png: this._stageData.cartoonPng }).then((animationName) => {
					this.animationName = animationName;
					GameManager.getIns().setState(1);
					this.initLayout()//完成后直接进入下一步
				})
			})
		}
	},
	state1StartPlay() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");


		let layout_card = pg.view.find(this, "card_group/layout_card");
		cc.find("card_group/card_bg2", this.node).opacity = 0;
		layout_card.removeAllChildren();
		let layout_normal = pg.view.find(this, "card_group/layout_normal");
		layout_normal.removeAllChildren();
		layout_normal.opacity = 0;

		this.hideRestartBtn();
		pg.view.visible(btn_record, false);
		this.playPartAni()
		this.playWordAni().then(() => {
			this.playRecordAudio();
		})
		let bg_book2 = pg.view.find(this, "bg_book2");
		pg.view.setNetImg(bg_book2, this._stageData.img, { w: 2056, h: 537 });
		// this._timeoutIds.push(setTimeout(() => {
		// 	pg.view.visible(icon_hand, true);
		// 	let action = cc.tween(icon_hand);
		// 	action.sequence(
		// 		cc.tween().by(0.5, { y: 50 }),
		// 		cc.tween().by(0.5, { y: -50 }),
		// 	).repeatForever();
		// 	action.start();
		// }, 1000 * 6.3));
	},
	state2ComplatePlay() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");

		pg.view.visible(icon_hand, false);
		pg.view.visible(btn_record, false);
		this.hideRestartBtn();
		pg.view.visible(btn_recording, true);
		pg.view.visible(progress, true);
	},
	state3GoodJob() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");
		pg.view.visible(btn_record, false);
		pg.view.visible(btn_recording, false);
		pg.view.visible(progress, false);
		this._timeoutIds.push(setTimeout(() => {//4秒钟之后出现goodjob提示
			pg.view.visible(end, true);
			pg.view.visible(end_success, true);
			this.playSFX("audio_goodjob");
		}, 1000 * 0.5));
		this._timeoutIds.push(setTimeout(() => {
			this.nextStage();
		}, 1000 * 4));//6秒钟之后进入下一关卡
	},
	state4TryAgain() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");

		// 一局失败弹出tryagain，同时下方录音按钮明亮并出现提示
		this.playSFX("audio_tryagain").then(() => {
			pg.view.visible(bg_tryagain, false);
			pg.view.visible(end, false);
		})
		pg.view.visible(end, true);
		pg.view.visible(bg_tryagain, true);
		pg.view.visible(btn_recording, false);
		pg.view.visible(btn_record, true);
		pg.view.visible(progress, false);

		this._playing = true;
		this._tryagainCount++;
		this._timeoutIds.push(setTimeout(() => {
			if (this._tryagainCount == 1) {
				pg.audio.playAudioByUrl(this._tryagain.one).then(() => {
					this._playing = false;
				})
				// this.playSFX("audio_record");
				pg.view.visible(icon_hand, true);
				let action = cc.tween(icon_hand);
				action.sequence(
					cc.tween().by(0.5, { y: 50 }),
					cc.tween().by(0.5, { y: -50 }),
				).repeatForever();
				action.start();
			} else if (this._tryagainCount == 2) {
				pg.audio.playAudioByUrl(this._tryagain.two).then(() => {
					this._playing = false;
				})
				// this.playSFX("audio_record");
				pg.view.visible(icon_hand, true);
				let action = cc.tween(icon_hand);
				action.sequence(
					cc.tween().by(0.5, { y: 50 }),
					cc.tween().by(0.5, { y: -50 }),
				).repeatForever();
				action.start();
			} else {
				pg.audio.playAudioByUrl(this._tryagain.three).then(() => {
					this._playing = false;
					this.nextStage();
				})
			}
		}, 1000 * 1));
	},
	state5Finish() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end");
		let end_success = pg.view.find(end, "bg_success")
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		let carton = pg.view.find(this, "carton")
		let bg_book = pg.view.find(this, "bg_book");
		let icon_ex = pg.view.find(this, "icon_ex");
		let btn_next = pg.view.find(this, "btn_next");
		let btn_return = pg.view.find(this, "btn_return");

		let icon_ex_txt = pg.view.find(icon_ex, "txt");
		let icon_hand = pg.view.find(this, "icon_hand");
		let btn_picture = pg.view.find(this, "btn_picture");
		pg.view.visible(end, false);
		pg.view.visible(end_success, false);
		pg.view.visible(bg_tryagain, false);


		this.setMaoAni("finish");
		pg.audio.playAudioByUrl(this._cat.finish).then(() => {
			this.setMaoAni("normal")
		})
		// this.playSFX("audio_finish");
		// pg.view.visible(btn_picture, true);
		pg.view.visible(btn_record, false);

		console.log('this.resultArr: ', JSON.stringify(this.resultArr));
		onHomeworkFinish && onHomeworkFinish({ result: this.resultArr });
	},

	playPartAni() {
		return new Promise((resolve, reject) => {
			let btn_replay = pg.view.find(this, "btn_replay")
			let btn_recording = pg.view.find(this, "btn_recording")
			let btn_record = pg.view.find(this, "btn_record")
			let progress = pg.view.find(this, "progress")
			let end = pg.view.find(this, "end");
			let end_success = pg.view.find(end, "bg_success")
			let bg_tryagain = pg.view.find(end, "bg_tryagain")
			let carton = pg.view.find(this, "carton")
			let bg_book = pg.view.find(this, "bg_book");
			let icon_ex = pg.view.find(this, "icon_ex");
			let btn_next = pg.view.find(this, "btn_next");
			let btn_return = pg.view.find(this, "btn_return");

			let icon_ex_txt = pg.view.find(icon_ex, "txt");
			let icon_hand = pg.view.find(this, "icon_hand");
			let btn_picture = pg.view.find(this, "btn_picture");

			let dragonDisplay = carton.getComponent(dragonBones.ArmatureDisplay);
			dragonDisplay.playAnimation(this.animationName, 1);//animation所有的动画名称
		});
	},
	playWordAni(jumpWait) {
		let self = this;
		return new Promise((resolve, reject) => {
			let btn_replay = pg.view.find(this, "btn_replay")
			let btn_recording = pg.view.find(this, "btn_recording")
			let btn_record = pg.view.find(this, "btn_record")
			let progress = pg.view.find(this, "progress")
			let end = pg.view.find(this, "end");
			let end_success = pg.view.find(end, "bg_success")
			let bg_tryagain = pg.view.find(end, "bg_tryagain")
			let carton = pg.view.find(this, "carton")
			let bg_book = pg.view.find(this, "bg_book");
			let icon_ex = pg.view.find(this, "icon_ex");
			let btn_next = pg.view.find(this, "btn_next");
			let btn_return = pg.view.find(this, "btn_return");

			let icon_ex_txt = pg.view.find(icon_ex, "txt");
			let icon_hand = pg.view.find(this, "icon_hand");
			let btn_picture = pg.view.find(this, "btn_picture");
			this._playing = true;
			icon_ex_txt.active = false;
			icon_ex.active = false;
			pg.view.visible(pg.view.find(this, "card_group/slider"), false);
			this.showCardLayout();
			if (jumpWait) {
				pg.view.visible(pg.view.find(this, "card_group/slider"), true);
				// pg.view.visible(icon_ex, true);
				let icon_ex_word = self._stageData.word;
				let aniFinished = true;
				let audioFinished = false;
				// this.wordAni(icon_ex_txt, icon_ex_word).then(() => {
				// 	aniFinished = true;
				// 	if (aniFinished && audioFinished) {
				// 		this._playing = false;
				// 		resolve('');
				// 	}
				// })
				// pg.audio.playAudioByUrlCall(this._stageData.sound).then((id) => {
				audioFinished = true;
				// let time = cc.audioEngine.getDuration(id);
				this.showCardAction(1).then(() => {
					this.showSliderAction(1).then(() => {
						pg.audio.playAudioByUrlCall(this._stageData.sound, () => {
							if (aniFinished && audioFinished) {
								this._playing = false;
								resolve('');
							}
						})
					});
				});
				// })
			} else {
				this._timeoutIds.push(setTimeout(() => {
					// pg.view.visible(icon_ex, true);
					pg.view.visible(pg.view.find(this, "card_group/slider"), true);
					let icon_ex_word = self._stageData.word;
					let aniFinished = true;
					let audioFinished = false;
					// this.wordAni(icon_ex_txt, icon_ex_word).then(() => {
					// 	aniFinished = true;
					// 	if (aniFinished && audioFinished) {
					// 		this._playing = false;
					// 		resolve('');
					// 	}
					// })
					// pg.audio.playAudioByUrlCall(this._stageData.sound).then((id) => {
					audioFinished = true;
					// let time = cc.audioEngine.getDuration(id);
					this.showCardAction(1).then(() => {
						this.showSliderAction(1).then(() => {
							pg.audio.playAudioByUrlCall(this._stageData.sound, () => {
								if (aniFinished && audioFinished) {
									this._playing = false;
									resolve('');
								}
							});
						});
					});
					// })
				}, 1000));
			}
		});
	},
	playRecordAudio() {
		return new Promise((resolve, reject) => {
			this._playing = true;
			let btn_replay = pg.view.find(this, "btn_replay")
			let btn_recording = pg.view.find(this, "btn_recording")
			let btn_record = pg.view.find(this, "btn_record")
			let progress = pg.view.find(this, "progress")
			let end = pg.view.find(this, "end");
			let end_success = pg.view.find(end, "bg_success")
			let bg_tryagain = pg.view.find(end, "bg_tryagain")
			let carton = pg.view.find(this, "carton")
			let bg_book = pg.view.find(this, "bg_book");
			let icon_ex = pg.view.find(this, "icon_ex");
			let btn_next = pg.view.find(this, "btn_next");
			let btn_return = pg.view.find(this, "btn_return");

			let icon_ex_txt = pg.view.find(icon_ex, "txt");
			let icon_hand = pg.view.find(this, "icon_hand");
			let btn_picture = pg.view.find(this, "btn_picture");
			pg.view.visible(btn_record, true);
			this.showRestartBtn();
			if (this._audio_record) {
				this._playing = false;
				resolve("");
			} else {
				this._audio_record = true;
				pg.audio.playAudioByUrl(this._cat.record).then(() => {
					this._playing = false;
					resolve('');
				})
			}
		});
	},



	wordAni(item, content) {
		return new Promise((resolve, reject) => {
			item.active = true;
			let itemfirst = pg.view.find(item, "first");
			//动态居中算法。
			//锚点在中间，左右延长，第一个字不去显示
			let contentArr = content.split("");
			let s0 = contentArr.shift();
			let s1 = contentArr.join("");
			//首字母变大
			let count = 100;
			let max = 150;
			let str1 = `<size=${max}><color=#ffffff>${s0}</color></size><size=${count}><color=#0000>${s1}</color></size>`
			let strfirst1 = `<size=${max}><color=#fc4a4a>${s0}</color></size>`;
			item.getComponent(cc.RichText).string = str1;
			itemfirst.y = 17;
			itemfirst.getComponent(cc.RichText).string = strfirst1;

			this._timeoutIds.push(setTimeout(() => {
				let times = 20;
				let time = 0;
				let inter = setInterval(() => {
					time++;
					let nowCount = count + (max - count) * (time / times);
					if (nowCount >= 150) {
						nowCount = 150;
						clearInterval(inter);
					}
					let str2 = `<size=${max}><color=#ffffff>${s0}</color></size><size=${nowCount}><color=#0000>${s1}</color></size>`
					itemfirst.y = 0;
					item.getComponent(cc.RichText).string = str2;
				}, 30);
				this._intervalIds.push(inter);
				setTimeout(() => {
					resolve('');
				}, 1200);
			}, 4100));
		});
	},

	showCardLayout() {
		let content = this._stageData.word;
		let card_group = cc.find("card_group", this.node);
		let layout_card = cc.find("layout_card", card_group);
		let layout_normal = cc.find("layout_normal", card_group);
		let card = cc.find("card", card_group);
		let card1 = cc.find("card1", card_group);
		let card2 = cc.find("card2", card_group);
		let add = cc.find("add", card_group);
		let normal_label = cc.find("normal_label", card_group);
		let slider = cc.find("slider", card_group);
		let card_bg2 = cc.find("card_group/card_bg2", this.node)
		slider.action = true;
		layout_card.removeAllChildren();
		normal_label.removeAllChildren();
		layout_card.opacity = 1;
		layout_normal.opacity = 0;
		let r = [239, 0, 135];
		let l = [2, 171, 241];
		content.forEach((item, idx) => {
			if (idx != 0) {
				let cAdd = cc.instantiate(add);
				layout_card.addChild(cAdd);
				cAdd.active = true;
			}
			let cCard = cc.instantiate(item.card.length == 1 ? card : item.card.length == 2 ? card1 : card2);
			layout_card.addChild(cCard);
			let text = cc.find("text", cCard);
			text.getComponent(cc.Label).string = item.card;
			text.color = item.color == 0 ? new cc.Color(r[0], r[1], r[2]) : new cc.Color(l[0], l[1], l[2]);
			cCard.active = true;
			cCard.data = item;
		})
		content.forEach((item, idx) => {
			if (item.card.length > 1) {
				let str = item.card.split("");
				str.forEach((c) => {
					let laebl = cc.instantiate(normal_label);
					layout_normal.addChild(laebl);
					laebl.getComponent(cc.Label).string = c;
					laebl.active = true;
				})

			} else {
				let laebl = cc.instantiate(normal_label);
				layout_normal.addChild(laebl);
				laebl.getComponent(cc.Label).string = item.card;
				laebl.active = true;
			}
		})
		layout_card.getComponent(cc.Layout).updateLayout();
		setTimeout(() => {
			layout_card.getComponent(cc.Layout).updateLayout();
			layout_normal.getComponent(cc.Layout).updateLayout();
			let size = this.node.width;
			let lWidth = layout_card.width;
			if (lWidth > size - 300) {
				layout_card.scale = size / lWidth - 0.05;
			} else {
				layout_card.scale = 1;
			}
			layout_card.opacity = 255;
			let nWidth = layout_normal.width;
			if (nWidth > size - 300) {
				layout_normal.scale = size / nWidth - 0.05;
			} else {
				layout_normal.scale = 1;
			}
		}, 60);

	},
	showCardAction(time) {
		return new Promise(async (resolve, reject) => {
			let layout_card = cc.find("card_group/layout_card", this.node);
			let len = layout_card.children.length
			let content = this._stageData.word;
			let t = time / content.length;
			for (let i = 0; i < len; i++) {
				let card = layout_card.children[i];
				if (card.name == "add") continue;
				await this.cardAction(card);
			}
			return resolve("")
		});
	},
	cardAction(card) {
		return new Promise((resolve, reject) => {
			if (card.data.audio) {
				pg.audio.playAudioByUrlCall(card.data.audio).then((id) => {
					let time = cc.audioEngine.getDuration(id);
					if (time < 0.5) time = 0.5;
					else if (time > 1) time = 1;
					cc.tween(card).to(time / 2, { scale: 1.1 }).to(time / 2, { scale: 1 }).call(() => { return resolve("") }).start();
				})
			} else {
				let time = 0.8;
				cc.tween(card).to(time / 2, { scale: 1.1 }).to(time / 2, { scale: 1 }).call(() => { return resolve("") }).start();
			}
		});
	},
	showSliderAction(time) {
		return new Promise((resolve, reject) => {
			let card_group = cc.find("card_group", this.node);
			let slider = cc.find("slider", card_group);
			slider.active = true;
			let sl = slider.getComponent(cc.Slider)
			sl.progress = 0;
			let t = time / 10;
			cc.tween(sl)
				.to(t, { progress: 0.1 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.2 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.3 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.4 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.5 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.6 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.7 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.8 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 0.9 }).call(() => { this.setCardColor(sl.progress); })
				.to(t, { progress: 1 }).call(() => {
					this.setCardColor(sl.progress);
					slider.active = false;
				})
				.delay(1).call(() => {
					this.hideBox();
					sl.progress = 0;
				})
				.delay(0.5).call(() => {
					return resolve("")
				})
				.start();
		});
	},
	hideBox() {
		let layout_normal = cc.find("card_group/layout_normal", this.node);
		cc.tween(layout_normal).to(0.5, { opacity: 255 }).start();
		let layout_card = cc.find("card_group/layout_card", this.node);
		// layout_card.opacity = 0;
		cc.tween(layout_card).to(0.1, { opacity: 0 }).start();

		// let card_bg2 = cc.find("card_group/card_bg2", this.node);
		// cc.tween(card_bg2).to(0.5, { opacity: 0 }).start();



		// layout_card.children.forEach((item) => {
		// 	if (item.name == "add") return;
		// 	item.getComponent(cc.Sprite).enabled = false;
		// 	// cc.tween(item).to(0.5, { opacity: 0 }).start();
		// })

	},
	setCardColor(progress) {
		let layout_card = cc.find("card_group/layout_card", this.node);
		let r = [239, 0, 135];
		let l = [2, 171, 241];
		let b = [35, 31, 32]


		layout_card.children.forEach((ch) => {
			if (ch.name == "add") return;
			let text = cc.find("text", ch);
			let ish = !ch.data.color;
			let nr = ish ? r[0] - progress * (r[0] - b[0]) : l[0] - progress * (l[0] - b[0]);
			let ng = ish ? r[1] - progress * (r[1] - b[1]) : l[1] - progress * (l[1] - b[1]);
			let nb = ish ? r[2] - progress * (r[2] - b[2]) : l[2] - progress * (l[2] - b[2]);
			text.color = new cc.Color(nr, ng, nb);
		})
	},
	//按钮触发，使用的方法
	onTouchRecord() {
		if (this._playing) {
			cc.audioEngine.stopAllEffects();
		}
		this.playSFX("audio_btns");
		let end = pg.view.find(this, "end");
		let bg_tryagain = pg.view.find(end, "bg_tryagain")
		pg.view.visible(end, false);
		pg.view.visible(bg_tryagain, false);
		GameManager.getIns().setState(2);
		this.initLayout()
		let str = "";
		this._stageData.word.forEach((t) => {
			str += t.card;
		})
		window.courseware && window.courseware.startTest(str); //开始录音
		this._timeoutIds.push(setTimeout(() => {
			if (!window.courseware) return this.recrodEnd({
				"dtLastResponse": "2021-09-17 13:36:26:109",
				"refText": "I haven't found anything out about him yet.",
				"recordId": "6144295213f0a2200000ed93",
				"eof": 1,
				"result": {
					"pronunciation": 25,
					"resource_version": "3.1.0",
					"fluency": 60,
					"rhythm": 90,
					"kernel_version": "5.2.4",
					"overall": 25,//75
					"integrity": 100,
					"duration": "6.779",
					"rear_tone": "fall",
					"speed": 96,
				},
				"tokenId": "6144295408558b08dd000001",
				"applicationId": "154838659000009e"
			})
			window.courseware && window.courseware.stopTest((data) => {
				data = JSON.parse(data);
				this.recrodEnd(data);
			}); //结束录音
		}, 4000));
	},
	recrodEnd(data) {
		let score = data.result.overall;
		this._stageData.curScore = score;
		// score = (score / 100) * 40 + (100 - 40);
		// score = 40;
		if (score >= 80) {
			GameManager.getIns().setState(3);
			this.initLayout();
		} else {
			GameManager.getIns().setState(4);
			this.initLayout();
		}
	},
	onTouchNext() {
		this.playSFX("audio_btns");

	},
	onTouchReturn() {
		this.playSFX("audio_btns");

	},
	onTouchRecording() {
		this.playSFX("audio_btns");

	},
	onTouchReplay() {
		if (this._playing) return;
		this.playSFX("audio_btns");
		GameManager.getIns().setState(1);
		this.initLayout()
	},
	onTouchPicture() {
		// this.playSFX("audio_btns");

	},
	onTouchCarton() {
		if (this._playing) return;
		this._playing = true;
		this.playPartAni();
		setTimeout(() => {
			this._playing = false;
		}, 900);
	},
	onTouchWord() {
		if (this._playing) return;
		this.playWordAni(true);
	},
	onTouchCat() {
		if (this._playing) return;
		this._playing = true;
		this.setMaoAni("begin");
		pg.audio.playAudioByUrl(this._cat.wait).then(() => {
			this.setMaoAni("normal");
			this._playing = false;
		})
	},

	nextStage() {
		let isOver = GameManager.getIns().addStage();//关卡标记+1

		this.pushResultData();

		if (isOver) {
			//执行总结束的内容
			GameManager.getIns().setState(5);
			this.initLayout()
		} else {
			this.initSingleData();//刷新当前关卡所使用的的数据
			this.initLayout();//刷新界面显示内容
		}
	},

	pushResultData() {

		console.log(' in pushResultData');
		const word = this._stageData.word;
		const score = this._stageData.curScore;
		this.resultArr.push({ word, score });
	},



	setMaoAni(aniName) {
		let mao_ske = cc.find("mao_ske", this.node);
		let ske = mao_ske.getComponent(dragonBones.ArmatureDisplay).playAnimation(aniName);

	},





	onTouchIconRecord() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_record = pg.view.find(this, "btn_record")
		let btn_recording = pg.view.find(this, "btn_recording")
		let progress = pg.view.find(this, "progress")
		this.hideRestartBtn();//隐藏
		pg.view.visible(btn_record, false);
		pg.view.visible(btn_recording, true);//显示
		pg.view.visible(progress, true);

	},
	initStep1() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_recording = pg.view.find(this, "btn_recording")
		let btn_record = pg.view.find(this, "btn_record")
		let progress = pg.view.find(this, "progress")
		let end = pg.view.find(this, "end")
		let ant_ske = pg.view.find(this, "ant_ske")
		let ax_ske = pg.view.find(this, "ax_ske")
		this.hideRestartBtn();
		pg.view.visible(btn_record, false);
		pg.view.visible(btn_recording, false);
		pg.view.visible(progress, false);
		pg.view.visible(end, false);
		pg.view.visible(ant_ske, false);
		pg.view.visible(ax_ske, false);
		this._timeoutIds.push(setTimeout(() => {
			this.initStep2();
		}, 2000));
	},
	initStep2() {
		let btn_replay = pg.view.find(this, "btn_replay")
		let btn_record = pg.view.find(this, "btn_record")
		this.showRestartBtn();
		pg.view.visible(btn_record, true);
	},
	initStep3() {

	},


	createAni() {
		// cc.assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err));


	},




	//显示replay
	showRestartBtn() {
		const btn = cc.find('Canvas/btn_replay');
		if (btn.canClick) {
			return;
		}

		btn.active = true;
		btn.canClick = true;

		const circle = cc.find('Canvas/btn_replay/btn_restart_circle');
		cc.tween(circle)
			.set({ scale: 0.8, opacity: 255 })
			.to(2, { scale: 1.2, opacity: 0 })
			.union()
			.repeatForever()
			.start();
	},

	hideRestartBtn() {
		console.log('hideRestartBtn op51');
		const btn = cc.find('Canvas/btn_replay');
		if (!btn.canClick) {
			return;
		}
		btn.canClick = false;
		btn.active = false;

		const circle = cc.find('Canvas/btn_replay/btn_restart_circle');
		circle.stopAllActions();
		circle.scale = 0.8;
		circle.opacity = 255;
	},


	//
	onTouchVoice(touch) {
		let item = touch.target;
		pg.audio.playAudioByUrl(item.data.audio_url);
	},
	//回合结束
	groupEnd() {
		for (let i = 0; i < this._boxItems.length; i++) {
			let box = this._boxItems[i];
			if (box.data.success.length != box.data.child.length) return;
		}
		// if (this._successItems.length < this._cardPage.length) return;
		if (this._gameCode != 0) return;
		this._gameCode = 2;
		//播放星星动画 然后结束
		this.playSFX("audio_sahua");
		this.createFireworkAni().then(() => {
			// 游戏结束时需要调用这个方法通知系统作业完成
			onHomeworkFinish();
		})
	},










	playSFX(name) {
		return new Promise((resolve, reject) => {
			let node = pg.view.find(this, name);
			if (!node) return resolve();
			let audioSource = node.getComponent(cc.AudioSource);
			if (!audioSource) return resolve();
			let audioClip = audioSource.clip;
			if (!audioClip) return resolve();
			let id = cc.audioEngine.play(audioClip, false, 1);
			cc.audioEngine.setFinishCallback(id, () => {
				resolve();
			})
		});
	},



	resizeInfo() {
		//0.设计尺寸
		let baseSize = cc.size(1280, 720);
		//1.获取屏幕尺寸
		let canvasSize = cc.view.getCanvasSize();
		//2.将屏幕宽高  以高度对齐的方式 换算出场景  宽度
		let sumSizeW = cc.size(canvasSize.width * baseSize.height / canvasSize.height, baseSize.height)
		//3.计算场景宽度与设计宽度比率
		let scaleX = sumSizeW.width / baseSize.width;
		//高屏幕适配
		if (scaleX <= 1) {
			let sumSizeY = cc.size(baseSize.width, canvasSize.height * (baseSize.width / canvasSize.width))
			let scaleY = sumSizeY.height / baseSize.height;
			let posY = sumSizeY.height - baseSize.height;
			return {
				scaleX: 1,
				posX: 0,
				moveX: 0,
				scaleY: scaleY,
				posY: posY,
				moveY: - posY / 2
			}
		} else {
			let posX = sumSizeW.width - baseSize.width;
			//需要拓展的宽度缩放比
			return {
				scaleX: scaleX,
				posX: posX,
				moveX: - posX / 2,
				scaleY: 1,
				posY: 0,
				moveY: 0
			};
		}
	},






























	playAudioAni(item) {
		return new Promise((resolve, reject) => {
			var anim = pg.view.find(item, `audio`).getComponent(cc.Animation);
			anim.play();
			//如果没有audio也要能正常走
			pg.audio.playAudioByUrl(item.data.audio).then(() => {
				anim.stop();
				pg.view.visible(pg.view.find(item, `audio/btn_laba`), true);
				resolve('');
			});
		});
	},

	createRightAni(pos) {
		let right = pg.view.find(this, 'right');
		let aniRight = cc.instantiate(right);
		aniRight.x = pos.x;
		aniRight.y = pos.y;
		pg.view.find(this, 'ani').addChild(aniRight);
		let armDisplay = aniRight.getComponent(dragonBones.ArmatureDisplay);
		armDisplay.playAnimation('newAnimation', 1);
		pg.view.visible(aniRight, true);
	},
	createStarAni() {
		return new Promise((resolve, reject) => {
			this.showStar();
			this._timeoutIds.push(setTimeout(() => {
				resolve('');
			}, 500));
		});
	},
	createFireworkAni() {
		return new Promise((resolve, reject) => {
			// this.showAllFirework(cc.find('Canvas/firework_ani'), cc.find('Canvas/paperBase').children);
			// setTimeout(() => {
			// 	resolve('');
			// }, 1000);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(0, -400), cc.v2(0, 1000), 200, 200,
				(id) => {
					this._timeoutIds.push(id);
				}
			);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(-600, -400), cc.v2(200, 1000), 200, 200,
				(id) => {
					this._timeoutIds.push(id);
				}
			);
			showFireworks(
				cc.find('Canvas/firework_ani'),
				cc.find('Canvas/RibbonNodeBase').children,
				cc.v2(600, -400), cc.v2(-200, 1000), 200, 200,
				(id) => {
					this._timeoutIds.push(id);
				}
			);
			this._timeoutIds.push(setTimeout(() => {
				resolve('');
			}, 1000));
		});
	},
	len: null,
	addStar() {
		if (!this.len) {
			this.len = 0;
		}
		this.len++;
		let length = this.len;

		const starLayout = cc.find('Canvas/layout_stars');
		starLayout.removeAllChildren();
		const paddingY = starLayout.getComponent(cc.Layout).spacingY;

		for (let i = 0; i < length; i++) {
			const starBase = cc.instantiate(cc.find('Canvas/StarBase'));
			starBase.name = `starBase_${i}`;
			starBase.scale = this.Between(0.5, (starLayout.height / length - paddingY) / starBase.height, 1);
			starBase.parent = starLayout;
		}
		this.currentStarIdx = 0;
	},

	currentStarIdx: null,
	showStar() {
		if (!this.currentStarIdx) {
			this.currentStarIdx = 0;
		}

		const starBase = cc.find(`Canvas/layout_stars/starBase_${this.currentStarIdx}`);
		if (!starBase) {
			return;
		}
		const star = starBase.getChildByName('Star');
		const starBig = star.getChildByName('StarBig');
		starBig.scale = 1;
		star.active = true;
		star.scaleX = 0.7 / starBase.scale;
		star.scaleY = 1 / starBase.scale;
		star.angle = 90;
		const canvas = cc.find('Canvas');
		const startPos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 2));
		const middlePos = this.exchangeNodePos(star.parent, canvas, cc.v2(0, -canvas.height / 4));
		star.x = startPos.x;
		star.y = startPos.y - starBig.height;

		console.log('middlePos = ' + JSON.stringify(middlePos));
		const time = 1;
		cc.tween(star)
			.to(0.3, { y: middlePos.y + 80 }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y + 40, scaleX: 1.2 / starBase.scale, scaleY: 0.8 / starBase.scale }, { easing: 'quadOut' })
			.to(0.1, { y: middlePos.y, scaleX: 1 / starBase.scale, scaleY: 1 / starBase.scale }, { easing: 'quadOut' })
			.delay(0.1)
			.to(0.8, { angle: -720, scale: 1 })
			.start();

		cc.tween(star)
			.delay(0.6)
			.to(0.8, { x: 0 }, { easing: 'quadIn' })
			.start();
		cc.tween(star)
			.delay(0.6)
			.to(0.8, { y: 0 }, { easing: 'quadOut' })
			.start();

		cc.tween(starBig)
			.delay(0.6)
			.to(0.8, { scale: 0 }, { easing: 'quadOut' })
			.call(() => {
				// this.checkGameEnd();
			})
			.start();

		this.currentStarIdx++;
	},

	Between(a, b, c) {
		return [a, b, c].sort()[1];
	},

	exchangeNodePos(targetNode, baseNode, basePos) {
		return targetNode.convertToNodeSpaceAR(baseNode.convertToWorldSpaceAR(cc.v2(basePos.x, basePos.y)));
	},


	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, (id) => {
				this._timeoutIds.push(id);
			});
		}
	},

	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;
	},

	// 生命周期
	onDestroy() {
		this._timeoutIds.forEach(id => {
			clearTimeout(id);
		});
		this._intervalIds.forEach(id => {
			clearInterval(id);
		});
	},
});
