// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import {getScaleRateBy2Node, localPosTolocalPos, randomSortByArr, getDistance} from "./util";

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: {
			default: 1280,
			type: cc.Integer
		},
		baseHeight: {
			default: 720,
			type: cc.Integer
		}
		// foo: {
		//     // ATTRIBUTES:
		//     default: null,        // The default value will be used only when the component attaching
		//                           // to a node for the first time
		//     type: cc.SpriteFrame, // optional, default is typeof default
		//     serializable: true,   // optional, default is true
		// },
		// bar: {
		//     get () {
		//         return this._bar;
		//     },
		//     set (value) {
		//         this._bar = value;
		//     }
		// },
	},

	// LIFE-CYCLE CALLBACKS:

	// baseWidth: 1280;
	// baseHeight: 720;

	onLoad() {
		this.initSceneData();
		this.initSize();
	},

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

	_designSize: null,
	initSize() {
		this._designSize = cc.view.getDesignResolutionSize();

	},

	start() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			// console.log('has window');
			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()
		})
	},


	_imageResList: null,
	_audioResList: null,
	_animaResList: null,
	preloadItem() {
		this.addPreloadImage();
		this.addPreloadAudio();
		this.addPreloadAnima();
		this.preload();
	},

	getData(func) {
		func(this.getDefaultData());
	},

	getDefaultData() {


		const dataJson = '{"groupArr":[{"title":"","letter":"h","audio_url":"http://staging-teach.cdn.ireadabc.com/b39dfb2221c22175d3e8ac972923a82b.mp3","bg":"2","picArr":[{"letter":"b","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/be8ec5cee7a3074440478b00a4a84f5e.png","audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3","text":""},{"letter":"t","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/c8abf7383d65bcbdba8f390785cece60.png","audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3","text":""},{"letter":"h","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/f6f4bbef497409fef3c8f1d375893829.png","audio_url":"http://staging-teach.cdn.ireadabc.com/9f0aee80e252005721a445cbbf04e8b1.mp3","text":""},{"letter":"h","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/7b18a7931d64f7b9e8b7ecd25cb5e3d4.png","audio_url":"http://staging-teach.cdn.ireadabc.com/a5fa20e0c6024421b0d9a7007c303503.mp3","text":""},{"letter":"h","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/e12d13282a10f92d65ac41b4aecaad4c.png","audio_url":"http://staging-teach.cdn.ireadabc.com/32258b839eca32b6ccf94f3dd6c86e0c.mp3","text":""}]},{"title":"","letter":"B","audio_url":"http://staging-teach.cdn.ireadabc.com/253a1653c954edd8f047f79ec401065d.mp3","bg":"3","picArr":[{"letter":"g","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/94cabac22be548c6dbab64c4be326547.png","audio_url":"http://staging-teach.cdn.ireadabc.com/f51e3fedc88aa69a99f6ef579f7de047.mp3","text":""},{"letter":"j","word":"","pic_url":"http://staging-teach.cdn.ireadabc.com/3d8f631b4ce08b8850051ad9a2490322.png","audio_url":"http://staging-teach.cdn.ireadabc.com/fbe2f23b9eb191a9330f99800e0d54d5.mp3","text":""}]}]}'

		const data1 = JSON.parse(dataJson);
		return data1;
	},

	preload() {

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

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

	addPreloadImage() {
		if (this.data.bgItem) {
			this._imageResList.push({url: this.data.bgItem.url});
		}

	},

	addPreloadAudio() {

		this.data.groupArr.forEach((item) => {
			this._audioResList.push({url: item.audio_url});

			item.picArr.forEach((subItem) => {
				this._audioResList.push({url: subItem.audio_url});
			})
		});
	},

	addPreloadAnima() {
		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			// if (item.gIdx == '0') {
			// 	this._animaResList.push({url: item.skeJsonData.url});
			// 	this._animaResList.push({url: item.texJsonData.url});
			// 	this._animaResList.push({url: item.texPngData.url});
			// }

		})

	},

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

	audioEnter: null,
	audioTitle: null,
	audioBgm: null,
	audioWrong: null,
	audioRight: null,
	audioStar: null,
	audioBtn: null,
	audioFinish: null,
	initAudio() {
		const audioNode = cc.find('Canvas/res/audio');
		this.audioEnter = audioNode.getChildByName('enter').getComponent(cc.AudioSource);
		this.audioTitle = audioNode.getChildByName('title').getComponent(cc.AudioSource);
		this.audioBgm = audioNode.getChildByName('bgm').getComponent(cc.AudioSource);
		this.audioWrong = audioNode.getChildByName('wrong').getComponent(cc.AudioSource);
		this.audioRight = audioNode.getChildByName('right').getComponent(cc.AudioSource);
		this.audioStar = audioNode.getChildByName('star').getComponent(cc.AudioSource);
		this.audioBtn = audioNode.getChildByName('btn').getComponent(cc.AudioSource);
		this.audioFinish = audioNode.getChildByName('finish').getComponent(cc.AudioSource);


		cc.audioEngine.play(this.audioBgm.clip, true, 0.1)
		// this.audioBgm.loop = true;
		// this.audioBgm.play();
	},

	groupIdx: null,
	_cantouch: null,
	frameSize: null,
	_mapScale: null,
	_mapScaleMax: null,
	initData() {
	
		this.groupIdx = 0;
		this.curGroup	= this.data.groupArr[this.groupIdx];

		const frameSize = cc.view.getFrameSize();
		this.frameSize = frameSize;
		let sx = frameSize.width / this._designSize.width;
		let sy = frameSize.height / this._designSize.height;
		this._mapScale  = Math.min(sx, sy);
		this._mapScaleMax  = Math.max(sx, sy);


		 sx = cc.winSize.width / frameSize.width;
		 sy = cc.winSize.height / frameSize.height;
		const s = Math.min(sx, sy);

		this._cocosScale = s;
		this._mapScale *= s;

		console.log('this._mapScale: ', this._mapScale);
		console.log('this._cocosScale: ', this._cocosScale);

		this.initQuestionData();
		this.initOutlineMaterial();
		this.initCircleSpr();
		this.initFontFamily();
	},

	initFontFamily() {

		// const fontLabel = this.node.getChildByName('font').getComponent(cc.Label);
		// 	this._labelFont = fontLabel.font;
	},

	circleSpr: null,
	initCircleSpr() {
		this.circleSpr = cc.find('Canvas/res/img/bg_zi').getComponent(cc.Sprite);
	},

	questionData: null,
	questionIndex : null,
	initQuestionData() {

		if (!this.curGroup) {
			return;
		}
		this.questionArr = randomSortByArr(this.curGroup.picArr);
		this.questionIndex = 0;
		this.questionData = this.questionArr[this.questionIndex];
	},

	initView() {
		this.initBg();
		this.initWave();
		this.initTrack();
		this.initBtn();
		this.initTrain();
		this.initTrainBox();
		this.addSoundBtnListener();

	},

	
	initListener() {
	
		const canvas = cc.find('Canvas');
		canvas.width = cc.winSize.width;
		canvas.height =cc.winSize.height;

		console.log('canvas: ', canvas);
		console.log('cc.winSize: ', cc.winSize);

		if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
			return;
		
		}
		canvas.on(cc.Node.EventType.TOUCH_MOVE, (e) => {
			this.canvasTouchMove(e);
		},)
		canvas.on(cc.Node.EventType.TOUCH_CANCEL, (e) => {
			this.canvasTouchEnd(e);
		})
		canvas.on(cc.Node.EventType.TOUCH_END, (e) => {
			this.canvasTouchEnd(e);
		})
	},

	_cocosScale: null,
	bg: null,
	curGroup: null,
	initBg() {
		const frameSize = this.frameSize;
		let sx = cc.winSize.width / frameSize.width;
		let sy = cc.winSize.height / frameSize.height;
		let s = Math.min(sx, sy);

		this._cocosScale = s;

		console.log('data:' , this.data);

		// const group = this.data.groupArr[0];
		if (!this.curGroup) {
			return;
		}
		// this.curGroup = group;

	
		const oldBg = this.bg;
		
	

		const group = this.curGroup;

		const bgNode = cc.find('Canvas/bg_' + group.bg)
		bgNode.active = true;

		console.log('grouo.bg:', group.bg);
		if (oldBg && oldBg != bgNode) {
			bgNode.opacity = 0;

			cc.tween(bgNode)
			.to(0.5, {opacity: 255})
			.call(() => {
				if (oldBg) {
					cc.tween(oldBg)
						.to(0.5, {opacity: 0})
						.call(() => {
							oldBg.active = false;
						})
						.start()
				}
			})
			.start()
		}

		const worldBgRect = bgNode.getBoundingBoxToWorld();

		let windowSize = cc.view.getVisibleSize();



		console.log('worldBgRect: ', worldBgRect)
		console.log('frameSize: ', frameSize)
		console.log('windowSize: ', windowSize)
		console.log('cc.winSize: ', cc.winSize)


		sx = windowSize.width / worldBgRect.width;
		sy = windowSize.height / worldBgRect.height;
		s = Math.max(sx, sy);
		console.log('s:' , s);
		bgNode.scale *= s;

		// sx = frameSize.width / bgNode.width;
		// sy = frameSize.height / bgNode.height;
		// bgNode.scale = Math.max(sx, sy) * s;
		// bgNode.anchorX = 1;
		// bgNode.anchorY = 0
		// bgNode.x = frameSize.width / 2 * s;
		// bgNode.y = -frameSize.height / 2;

		// const worldPos = cc.v2(0, 0);
		// const localPos = bgNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
		// bgNode.y = localPos.y;

		this.bg = bgNode;


	},

	wave_1_1: null,
	wave_1_2: null,
	wave_2_1: null,
	wave_2_2: null,
	waveSpeed1: null,
	waveSpeed2: null,
	waveArr1: null,
	waveArr2: null,
	initWave() {
		this.wave_1_1 = cc.find('Canvas/bg_wavefront_1');
		this.wave_1_2 = cc.find('Canvas/bg_wavefront_2');
		this.wave_2_1 = cc.find('Canvas/bg_wavebehind_1');
		this.wave_2_2 = cc.find('Canvas/bg_wavebehind_2');

		this.waveSpeed1 = -2;
		this.waveSpeed2 = -1;

		
		this.wave_1_1.zIndex = 10;
		this.wave_1_2.zIndex = 10;
		this.wave_2_1.zIndex = 0;
		this.wave_2_2.zIndex = 0;

		this.waveArr1 = [this.wave_1_2, this.wave_1_1];
		this.waveArr2 = [this.wave_2_2, this.wave_2_1];
		
		// const worldPos = cc.v2(0, 0);
		// const localPos = this.wave_1_1.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
		this.wave_1_1.y = this.wave_1_2.y = this.wave_2_1.y = this.wave_2_2.y = 0 ; //this.frameSize.height / 2;

		// this.initWaveScale();
	},

	_enterInitTrack: null,
	initTrack() {
		if (this._enterInitTrack) {
			return;
		}
		this._enterInitTrack = true;


	
		const track = cc.find('Canvas/bg_gui');
		track.zIndex = 5;
		track.anchorX = 0;

		const localPos0 = track.parent.convertToNodeSpaceAR(cc.v2(0, 0));
		const localPosW = track.parent.convertToNodeSpaceAR(cc.v2(this.frameSize.width, 0));

		track.x = localPos0.x;

		
		let oldTrack = track;
		const rect = track.getBoundingBoxToWorld();
		let w = rect.width;
		console.log('w: ', w);
		console.log('this.frameSize.width: ', this.frameSize.width);
		console.log('cc.windSize: ', cc.winSize.width);
		console.log(' localPosW.x: ',  localPosW.x);
		while(w < cc.winSize.width) {
			const newTrack = cc.instantiate(oldTrack);
			newTrack.parent = oldTrack.parent;
			newTrack.zIndex = oldTrack.zIndex;
			newTrack.x = oldTrack.x - 2 + oldTrack.width * oldTrack.scaleX;
			w += rect.width;
			oldTrack = newTrack;
		}
	},

	_enterWaveScale: null,
	initWaveScale() {
		if (this._enterWaveScale) {
			return;
		}
		this._enterWaveScale = true;

		
		
		// this.wave_1_1.scale = this._mapScaleMax;
		// this.wave_1_2.scale = this._mapScaleMax;
		// this.wave_2_1.scale = this._mapScaleMax;
		// this.wave_2_2.scale = this._mapScaleMax;
	},


	initBtn() {
		let startBtn = cc.find('Canvas/btn_start');
		if (this.isRestart) {
			startBtn = cc.find('Canvas/btn_restart');
		}
		startBtn.active = true;
		startBtn.opacity = 255;

		startBtn.scale = 0;
		cc.tween(startBtn) 
			.to(0.5, {scale: 1}, {easing: 'elasticOut'})
			.start();

		cc.audioEngine.play(this.audioBtn.clip, false, 0.5);

		startBtn.once('click', () => {

			cc.audioEngine.play(this.audioBtn.clip, false, 0.5);

			cc.tween(startBtn)
			.to(0.06, {scale: 0.8})
			.to(0.06, {scale: 1, opacity: 0})
			.call(() => {
				startBtn.active = false;
				this.showTrain();
			})
			.start();
		})
	},

	train: null,
	initTrain() {
		const cheW = 180;
		const trainNode = cc.find('Canvas/train');
		trainNode.baseX = trainNode.x;
		const train = trainNode.getChildByName('anima');
		const totalW = train.width + 180 * 5;
		this.train = train;

		const anima = train.getComponent(dragonBones.ArmatureDisplay);

		anima.off(dragonBones.EventObject.COMPLETE)
		anima.on(dragonBones.EventObject.COMPLETE, (e) => {
			if (anima.animationName == 'right') {
				this.train.getComponent(dragonBones.ArmatureDisplay)
					.playAnimation('normal', -1);
			}
		})
		
		trainNode.x = trainNode.parent.convertToNodeSpaceAR(cc.v2(-150, 0)).x;

		// const frameSize = cc.view.getFrameSize();
		trainNode.scale = this._mapScale //frameSize.width / totalW;


	},

	trainBox: null,
	initTrainBox() {

		this.trainBox = [];
		const trainNode = cc.find('Canvas/train');
		trainNode.zIndex = 6;
		// trainNode.x 

		const picArr = this.curGroup ? this.curGroup.picArr : [];
		const rightArr = [];
		picArr.forEach(pic => {
			if (pic.letter == this.curGroup.letter) {
				rightArr.push(pic);
			}
		});


		for (let i = 0; i < 5; i ++) {
			const box = trainNode.getChildByName('che_' + (i+1));

			const starNode = box.getChildByName('star');
			starNode.rotation = 0;
			starNode.active = false;

			if (box.item) {
				this.resetPicNode(box.item);
				box.item = null;
			}

			if (rightArr[i]) {
				box.active = true;
				this.trainBox.push(box);
			} else {
				box.active = false;
			}
		}
	},

	resetPicNode(pNode) {
		pNode.parent = pNode.baseP;
		pNode.x = pNode.baseX;
		pNode.y = pNode.baseY;
		pNode.scale = 1;
		pNode.parent.active = false;
		pNode.anchorY = 0.5;
		pNode.box = null;

		
	},

	showTrain() {
		const frameSize = this.frameSize;

		const trainNode = cc.find('Canvas/train');
		const train = trainNode.getChildByName('anima');
		console.log('train: ', train);

		train.getComponent(dragonBones.ArmatureDisplay)
		.playAnimation('move', -1);

		cc.tween(trainNode)
			.to(3.3, {x: cc.winSize.width / 1.7 + train.width * 0}, {easing: 'sineOut'})
			.call(() => {
				this.stopTrain(train);
				this.showTitle();
				// this.showPic();
			})
			.start();

		this.waveSpeed1 = -6;
		this.waveSpeed2 = -3;
		cc.audioEngine.play(this.audioEnter.clip, false, 0.2)
		// this.audioEnter.play();
	},

	stopTrain(train) {
		train.getComponent(dragonBones.ArmatureDisplay)
		.playAnimation('normal', -1);
		this.waveSpeed1 = -2;
		this.waveSpeed2 = -1;
	},

	showTitle() {
		const titleNode = cc.find('Canvas/title');
		titleNode.active = true;
		titleNode.opacity = 255;
		titleNode.y = this.frameSize.height / 4;
		titleNode.scale = 0;

		const star = titleNode.getChildByName('star');
		star.active = false;

		const letterBg = titleNode.getChildByName('bg_letter');
		letterBg.active = false;


		cc.tween(titleNode) 
			.to(0.9, {scale: 1}, {easing: 'elasticOut'})
			.call(() => {
				this.playAudioByUrl(this.curGroup.audio_url);
				this.showTitleLetter(titleNode);
			})
			.start();

		cc.audioEngine.play(this.audioTitle.clip, false, 0.5)
		// this.audioTitle.play();
	},

	font: null,
	showTitleLetter(titleNode) {
		const letterBg = titleNode.getChildByName('bg_letter');
		letterBg.baseY = letterBg.y;
		letterBg.y = this.frameSize.height / 2;

		const label = letterBg.getChildByName('label').getComponent(cc.RichText);
		label.string = `<outline color=#fe538f width=5>${this.curGroup.letter}</outline>`
		this.font = label.font;
		
		cc.tween(letterBg)
		.to(1.7, {y: letterBg.baseY}, {easing: 'bounceOut'})
		.call(() => {
			this.showTitleStar(titleNode);
		})
		.start();

		letterBg.active = true;

	},

	showTitleStar(titleNode) {
		const star = titleNode.getChildByName('star');
		star.active = true;
		star.scale = 0;
		star.rotation = 0;

		cc.tween(star)
		.to(0.7, {rotation: 360, scale: 1}, {easing: 'cubicOut'})
		.delay(1)
		.call(() => {
			this.hideTitle(titleNode);
		})
		.start();
	},

	hideTitle(titleNode) {
		cc.tween(titleNode)
		.to(0.7, {opacity: 0}, {easing: 'cubicIn'})
		.call(() => {
			this.showPic();
		})
		.start();
	},


	addSoundBtnListener() {
		const btn = cc.find('Canvas/btn_laba');
		const anima = btn.getComponent(cc.Animation);
		if (btn.hasEventListener('click')) {
			return;
		}
		btn.on('click', () => {
			console.log('anima: ', anima);
			this.showSound();
		})
	},

	showSound() {
		if (!this._cantouch) {
			return;
		}
		if (!this.questionData) {
			return;
		}
		const btn = cc.find('Canvas/btn_laba');
		const anima = btn.getComponent(cc.Animation);
		anima.play('laba')

		this.playAudioByUrl(this.curGroup.audio_url);
		// this.playAudioByUrl(this.questionData.audio_url);
	},


	playAudioByUrl(audio_url, cb=null) {
	if (audio_url) {
		cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
			const audioID = cc.audioEngine.play(audioClip, false, 0.8);

			if (cb) {
				cc.audioEngine.setFinishCallback(audioID, function () {
					cb();
				});
			}
		});
	}
	},

	showPic() {
		// console.log('data:', this.data)
			if (!this.curGroup || !this.curGroup.picArr) {
				return;
			}
			this._cantouch = true;

			this.showSound();

			const picLen = 240;

			const picArr = this.curGroup.picArr;
			const posNode = cc.find('Canvas/posNode/node_' + (picArr.length))
			posNode.active = true;
			posNode.scale = this._mapScale;
			posNode.parent.zIndex = 8;


			let index = 0;
			picArr.forEach((item) => {

				console.log('item: ', item)
				const picNode = posNode.getChildByName('p_' + (index + 1))
				picNode.baseX = picNode.x;
				picNode.baseY = picNode.y;
				picNode.baseP = picNode.parent;
				picNode.data = item;
				index ++;

				picNode.scale = 0;


				cc.loader.load({url: item.pic_url}, (err, img) => {

					// const spr = picNode.addComponent(cc.Sprite);
					const spr = picNode.getComponent(cc.Sprite);
					spr.spriteFrame = new cc.SpriteFrame(img)

					const sx = picLen / picNode.width;
					const sy = picLen / picNode.height;
					const s = Math.min(sx, sy);
					// picNode.baseS = s;

					cc.tween(picNode)
						.delay(Math.random() * 0.2)
						.to(0.5, {scale: s}, {easing: 'elasticOut'})
						.start();

					this.addPicTouchListener(picNode);

					if (!spr.baseMaterial) {
						spr.baseMaterial = spr.getMaterial(0);
					}

					let letterNode = picNode.letterNode;
					if (!picNode.letterNode) {
						
						letterNode = new cc.Node();
						const letterBg = letterNode.addComponent(cc.Sprite);
						letterBg.spriteFrame = this.circleSpr.spriteFrame;
						letterNode.parent = picNode;

						const labelNode = new cc.Node();
						labelNode.parent = letterNode;
						const label = labelNode.addComponent(cc.RichText);
						label.font = this.font;
						label.fontSize = 90;
						label.verticalAlign = cc.Label.VerticalAlign.CENTER;
						// labelNode.anchorY = 0.5;
						labelNode.y = 7;


						label.lineHeight = letterNode.height;

						if (Math.random() < 0.5) {
							labelNode.color = new cc.Color(0,162,255);
						} else {
							labelNode.color = new cc.Color(245,50,39);
						}
						
						picNode.label = label;
						picNode.letterNode = letterNode;
					}

					letterNode.active = true;

					letterNode.scale = 1 / s;
					letterNode.x = picNode.width / 2;
					letterNode.y = picNode.height / 2;


					picNode.label.string = item.letter;
		

				});

			})

			
	},

	outlineMaterial: null,
	initOutlineMaterial() {
		const spr = cc.find('Canvas/material').getComponent(cc.Sprite);
		this.outlineMaterial = spr.getMaterial(0);
	},

	showOutline() {
		const spr = this._curShowItem.getComponent(cc.Sprite);

		const m = cc.MaterialVariant.create(this.outlineMaterial, spr);
		// console.log('m: ', m);
		
		spr.setMaterial(0, m);


		// let variant1 = cc.MaterialVariant.createWithBuiltin(cc.Material.BUILTIN_NAME.SPRITE);

		// 设置材质到指定索引，一般来说 2d 渲染组件的 index 都是 0
		// variant1 由于没有指定 owner render component，所以会直接被 renderComponent1 使用并且设置 owner 为 renderComponent1
		// spr.setMaterial(0, variant1);
		// spr.setMaterial(0, this.outlineMaterial);

		// spr.markForRender(true);

	},

	hideOutLine() {
		const spr = this._curShowItem.getComponent(cc.Sprite);
		spr.setMaterial(0, spr.baseMaterial);
	},


	_curShowItem: null,
	addPicTouchListener(node) {
		if (node.hasEventListener('cc.Node.EventType.TOUCH_START')) {
			return;
		}
		node.on(cc.Node.EventType.TOUCH_START, (e) => {

			if (!this._cantouch) {
				return;
			}
			if (node.box) {
				return;
			}
			this._cantouch = false;
			e.bubbles = false;
			this._curShowItem = node;

			// this.playAudioByUrl(this.curGroup.audio_url, () => {
				this.playAudioByUrl(this._curShowItem.data.audio_url);
			// });
			this.showOutline();
		});
		
	},

	canvasTouchMove(e) {

		if (!this._curShowItem) {
			return;
		}

		const pos = e.getLocation();

		const worldPos = e.currentTarget.parent.convertToWorldSpaceAR(cc.v2(pos.x, pos.y));
		const localPos = this._curShowItem.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));

		this._curShowItem.x = localPos.x;
		this._curShowItem.y = localPos.y;
	},

	canvasTouchEnd(e) {

		if (!this._curShowItem) {
			return;
		}

		this.checkOnTargetBox(e);
		this._curShowItem = null;
	},

	checkOnTargetBox(e) {
		const checkLen = 100 * this._cocosScale;
		let minLen = checkLen, curBox;
		for (let i = 0; i < this.trainBox.length; i++) {
			const worldStartPos = this._curShowItem.parent.convertToWorldSpaceAR(this._curShowItem);
			const tmpP = cc.v2(this.trainBox[i].x - this.trainBox[i].width / 2, this.trainBox[i].y + this.trainBox[i].height / 2)
			const worldEndPos = this.trainBox[i].parent.convertToWorldSpaceAR(tmpP);
			const tmpLen = getDistance(worldStartPos, worldEndPos)
			if (tmpLen <= minLen && !this.trainBox[i].item) {
				curBox = this.trainBox[i];
				minLen = tmpLen;
			}
		}

		if (curBox && this._curShowItem.data.letter == this.curGroup.letter ) {
			this.addBoxPic(curBox, this._curShowItem);
		} else {
			this.itemBack();
		}
	},

	itemBack() {

		const startPos = cc.v2(this._curShowItem.x, this._curShowItem.y);
		const endPos = cc.v2(this._curShowItem.baseX, this._curShowItem.baseY);
		let distance = startPos.sub(endPos).mag();
		// if (distance <= 20 && this._curShowItem.data.audioClip) {
		// 	cc.audioEngine.stopAll();
		// 	cc.audioEngine.play(this._curShowItem.data.audioClip, false, 0.8);
		// } else {
			// this._wrongAudioSource.play();
		// }

		const backItem = this._curShowItem;
		cc.tween(backItem)
			.to(0.3, {x: backItem.baseX, y: backItem.baseY}, {easing: 'elasticOut'})
			.call(( ) => {
				// backItem.bgBottomItem.opacity = 255;
				// backItem.removeFromParent();
				// backItem.data.isDrag = false;
				this._cantouch = true;
			})
			.start();

		this.hideOutLine();
		cc.audioEngine.play(this.audioWrong.clip, false, 0.5)

	},
	

	addBoxPic(box, showItem) {
		showItem.parent = box;
		showItem.x = -box.width / 2 - 12;
		showItem.y = box.height / 2 + 2;
		showItem.zIndex = -1;

		box.item = showItem;
		showItem.box = box;

		showItem.scale = box.width * 0.8 / showItem.width;
		showItem.anchorY = 0;

		const baseS = showItem.scale;
		showItem.scale = 0;

		showItem.letterNode.active = false;

		cc.tween(showItem)
			.to(0.3, {scale: baseS}, {easing: 'sineOut'})
			.start()

		this.showBoxStar(box);
		this.hideOutLine();

	},

	showBoxStar(box) {
		const star = box.getChildByName('star');
		const parent = star.parent;
		star.baseX = star.x;
		star.baseY = star.y;
		star.baseS = 0.15 // star.scale;
		star.zIndex = 10;

		star.parent = cc.find('Canvas');
		star.active = true;
		star.scale = 0;

		star.x = 0;
		star.y = 0;

		const worldPos = parent.convertToWorldSpaceAR(cc.v2(star.baseX, star.baseY));
		let	pos = star.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y)); 
		cc.tween(star)
			.to(0.7, {scale: 1}, {easing: 'elasticOut'})
			.delay(0.3)
			.to(1.5, {rotation: 360, scale: star.baseS, x: pos.x, y: pos.y}, {easing: 'cubicOut'})
			.call(() => {
		
				const worldRect1 = star.getBoundingBoxToWorld();

				star.parent = box;
				star.x = star.baseX;
				star.y = star.baseY;

				const worldRect2 = star.getBoundingBoxToWorld();
				const sx = worldRect1.width / worldRect2.width;
				star.scale *= sx;

				this.showTrainRight();
			})
			.start()

			cc.audioEngine.play(this.audioStar.clip, false, 0.3)

	},

	showTrainRight() {

		const anima = this.train.getComponent(dragonBones.ArmatureDisplay);
		anima.playAnimation('right', 1);

		// let arma = anima.armature();

		cc.audioEngine.play(this.audioRight.clip, false, 0.5)

		// this.changeQuestion();
		this.checkGroupEnd();

		this._cantouch = true;
	},

	checkGroupEnd() {

		for (let i = 0; i < this.trainBox.length; i++) {
			if (!this.trainBox[i].item) {

				setTimeout(() => {
					this.showSound();
				}, 500);
				return;
			}
		}

		// 结束
		if (this.groupIdx == this.data.groupArr.length - 1) {
			this.showParticle();
	
		} else {
			setTimeout(() => {
				this.showTrainLeave();
			}, 500);
		}
			
	},

	changeQuestion() {

		console.log(' in changeQuestion');
		this.questionIndex ++;
		this.questionData = this.questionArr[this.questionIndex];

		if (!this.questionData) {
			if (this.groupIdx == this.data.groupArr.length - 1) {
				this.showParticle();
		
			} else {
				setTimeout(() => {
					this.showTrainLeave();
				}, 500);
			}
			
			return;
		}

		setTimeout(() => {
			this.showSound();
		}, 500);
	},

	showTrainLeave() {
		console.log( ' in  showTrainLeave')
		const trainNode = cc.find('Canvas/train');
		this.train.getComponent(dragonBones.ArmatureDisplay)
			.playAnimation('move', -1);
		this.waveSpeed1 = -6;
		this.waveSpeed2 = -3;
		cc.audioEngine.play(this.audioEnter.clip, false, 0.2)

		cc.tween(trainNode)
			.to(3.1, {x: this.frameSize.width * 1.5}, {easing: 'sineIn'})
			.call(() => {

				this.waveSpeed1 = -2;
				this.waveSpeed2 = -1;
				trainNode.x = trainNode.baseX;
				this.nextGroup();
			})
			.start()
	},

	nextGroup() {

		this.setNextGroupData();
		this.initQuestionData();

		this.initTrainBox();



		if (!this.curGroup) {
			this.showRestart();
		} else {
			this.showTrain();
			this.initBg();
		}
	},

	isRestart: null,
	showRestart() {

		this.isRestart = true;
		this.initData();
		this.initView();
	},

	
	setNextGroupData() {
		this.groupIdx ++;
		this.curGroup = this.data.groupArr[this.groupIdx];
	},

	showParticle() {

		const pNode = cc.find('Canvas/particle_finish');
		pNode.active = true;
		pNode.zIndex = 20;
		const particle = pNode.getComponent(cc.ParticleSystem);
		particle.resetSystem();

		cc.audioEngine.play(this.audioFinish.clip, false, 0.5)

		setTimeout(() => {
			this.showTrainLeave();
		}, 1000);
	},

	checkWaveOnEdgeOld(wave1, wave2) {
		let waveLeft, waveRight
		if (wave1.x < wave2.x) {
			waveLeft = wave1;
			waveRight = wave2;
		} else {
			waveLeft = wave2;
			waveRight = wave1;
		}

		const worldRect = waveLeft.getBoundingBoxToWorld();
		if (worldRect.x + worldRect.width < 0) {
			waveLeft.x = waveRight.x + waveRight.width * Math.abs(waveRight.scaleX) - 1;
		}
	},

	checkWaveOnEdge(waveArr) {
		const lastWave = waveArr[waveArr.length - 1];
		const lastWaveWRect = lastWave.getBoundingBoxToWorld();

		let isLog = false;
		if (waveArr == this.waveArr2) {
			isLog = true;
		}

		if (lastWaveWRect.x + lastWaveWRect.width <= cc.winSize.width) {
		
			let newWave;
			const firstWave = waveArr[0];
			const firstWaveWRect = firstWave.getBoundingBoxToWorld();
			if (firstWaveWRect.x + firstWaveWRect.width < 0) {
				if (isLog) {
					console.log(' new wave is shift' );
				}
				newWave = waveArr.shift();
			} else {
				if (isLog) {
					console.log(' new wave is clone' );
				}
				newWave =  cc.instantiate(lastWave);
				newWave.parent = lastWave.parent;
				newWave.y = lastWave.y;
				newWave.anchorX = lastWave.anchorX;

				newWave.zIndex = lastWave.zIndex;
			}

			if (isLog) {
				console.log('waveArr.length: ', waveArr.length);
			}
			newWave.x = lastWave.x + newWave.width * newWave.scaleX - 1;
			waveArr.push(newWave);

		}
	},


	updateWave() {
		if (!this.wave_1_1) {
			return;
		}
		// this.wave_1_1.x += this.waveSpeed1;
		// this.wave_1_2.x += this.waveSpeed1;
		// this.wave_2_1.x += this.waveSpeed2;
		// this.wave_2_2.x += this.waveSpeed2;

		this.waveArr1.forEach(item => {
			item.x += this.waveSpeed1;
		})

		this.waveArr2.forEach(item => {
			item.x += this.waveSpeed2;
		})

		this.checkWaveOnEdge(this.waveArr1);
		this.checkWaveOnEdge(this.waveArr2);
		// this.checkWaveOnEdge(this.wave_1_1, this.wave_1_2);
		// this.checkWaveOnEdge(this.wave_2_1, this.wave_2_2);
	},

	update (dt) {
		this.updateWave();
	}
});





