// 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 { localPosTolocalPos, playAudio, showTrebleFirework} 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() {
		// cc.sys.capabilities = true;
		cc.macro.ENABLE_MULTI_TOUCH = true;

		cc.debug.setDisplayStats(false);
		
		this.initSceneData();
		this.initSize();

	},

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

	_designSize: null,
	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

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

		
	},

	start() {
		cc.debug.setDisplayStats(false);
		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.preloadItem()
		})

		console.log('cc.sys.capabilities["touches"] = ', cc.sys.capabilities["touches"]);
	},


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

  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() {

		const dataJson = '{"bgColor":"#f9bd03","bgColorId":0,"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/9cdf3b30720c91c2876c88a07c997c8b.jpg","rect":{"x":248.39,"y":0,"width":1038.22,"height":584}},"hotZoneItemArr":[{"id":"1607409055453","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/71108d9f5c53f900a433d930ae63848b.jpg","text":"aaaa","audio_url":"http://staging-teach.cdn.ireadabc.com/a4d27ad173a95823d4b8ec82363c5aa0.mp3","itemType":"rect","fontScale":1.19921875,"imgScale":0.45807812500000006,"mapScale":1.19921875,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/51e9d8e4e2e963a7658d07eba6c282f8.json","name":"Ubbie_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/4232e00c9b1d272e650e51dbb785e498.json","name":"Ubbie_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/2e56dbe3134380952a725eacceb86359.png","name":"Ubbie_tex.png"},"gIdx":"0","rect":{"x":64.45,"y":161.67,"width":198.98,"height":198.98}},{"id":"1607409064053","index":1,"pic_url":"http://staging-teach.cdn.ireadabc.com/9dfdcdb9f7c0daa15ea8f7864342893a.jpg","text":"bbbb","audio_url":"http://staging-teach.cdn.ireadabc.com/440cf9d57752b30691d90ed565e8c924.mp3","itemType":"rect","fontScale":1.19921875,"imgScale":0.45807812500000006,"mapScale":1.19921875,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/7efceac56cc9a61b107a11457390d3c6.json","name":"finish1_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/d6e8db4fb385127de9e3cd9d8a9530f7.json","name":"finish1_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/96f5c7a9ac9f433c9c870c38b0811a38.png","name":"finish1_tex.png"},"gIdx":"0","rect":{"x":715.1,"y":151.72,"width":198.98,"height":198.98}},{"id":"1611130853038","index":2,"pic_url":"http://staging-teach.cdn.ireadabc.com/f6f4bbef497409fef3c8f1d375893829.png","audio_url":"http://staging-teach.cdn.ireadabc.com/85cff126986f5cc11b05e95181da5869.mp3","itemType":"pic","fontScale":1.19921875,"imgScale":0.6276324728260869,"mapScale":1.19921875,"gIdx":"1","rect":{"x":821.16,"y":397.2,"width":173.23,"height":173.23}},{"id":"1611130870716","index":3,"audio_url":"http://staging-teach.cdn.ireadabc.com/5285e1e88a26a08783757e9c43a8653f.mp3","itemType":"rect","fontScale":1.19921875,"imgScale":1,"mapScale":1.19921875,"skeJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/7efceac56cc9a61b107a11457390d3c6.json","name":"finish1_ske.json"},"texJsonData":{"url":"http://staging-teach.cdn.ireadabc.com/d6e8db4fb385127de9e3cd9d8a9530f7.json","name":"finish1_tex.json"},"texPngData":{"url":"http://staging-teach.cdn.ireadabc.com/96f5c7a9ac9f433c9c870c38b0811a38.png","name":"finish1_tex.png"},"gIdx":"2","rect":{"x":388.75,"y":161.64,"width":260.72,"height":260.72}}],"bg_audio_url":"http://staging-teach.cdn.ireadabc.com/3fa65d5f667a2ef9059d3dfc5df74a4d.mp3"}'
		const data = JSON.parse(dataJson);
		return data;
	},

	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 });
		}
		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			if (item.pic_url) {
				this._imageResList.push({ url: item.pic_url });
			}
		})

	},

	addPreloadAudio() {

		if (!this.data.hotZoneItemArr) {
			return;
		}
		this.data.hotZoneItemArr.forEach((item) => {
			this._audioResList.push({ url: item.audio_url });
		})


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

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

	},

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

	initMusic() {
		if (this.data.bg_audio_url) {
			cc.assetManager.loadRemote(this.data.bg_audio_url, (err, clip) => {
				cc.audioEngine.setMusicVolume(0.3);
				const audioID = cc.audioEngine.playMusic(clip, true);
			});
		}
	},

	_wrongAudioSource: null,
	_gjAudioSource: null,
	_endAudio: null,
	initAudio() {
		this._wrongAudioSource = cc.find('Canvas/res/wrong_audio').getComponent(cc.AudioSource);
		this._gjAudioSource = cc.find('Canvas/res/good_job').getComponent(cc.AudioSource);
		this._endAudio = cc.find('Canvas/res/end_audio').getComponent(cc.AudioSource);
	},

	initListener() {
		const bgBottom = cc.find('Canvas/bgBottom');
		const canvas = cc.find('Canvas');

		// this.initWebListener();
		
		let downFlag = false;
		bgBottom.on('item_touch_start', (item) => {
			downFlag = true;
			this.touchStartItem(item);
		})


		const touchMove = (e) => {
			this.canvasTouchMove(e);
			console.log('touch move');

			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_MOVE)) {
				canvas.off(cc.Node.EventType.MOUSE_MOVE, mouseMove)
			}
		}

		const mouseMove = (e) => {
			if (!downFlag) {
				return;
			}
			this.canvasTouchMove(e);
			console.log('mouse move');

			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_MOVE)) {
				canvas.off(cc.Node.EventType.TOUCH_MOVE, touchMove)
				this.removeHtmlCanvasListener('touchmove');
			}
		}

		const touchEnd = (e) => {
			// if (downFlag == false) {
			// 	return;
			// }
			downFlag = false;
			this.canvasTouchEnd(e);
			console.log('touch end')

			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_UP)) {
				canvas.off(cc.Node.EventType.MOUSE_UP, mouseUp)
			}
			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_LEAVE)) {
				canvas.off(cc.Node.EventType.MOUSE_LEAVE, mouseUp)
			}
			this.removeHtmlTouchEnd();
		}

		const mouseUp = (e) => {
			// if (downFlag == false) {
			// 	return;
			// }
			downFlag = false;

			this.canvasTouchEnd(e);
			console.log('mouse up')

			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_END)) {
				canvas.off(cc.Node.EventType.TOUCH_END, touchEnd)
			}
			if (canvas.hasEventListener(cc.Node.EventType.TOUCH_CANCEL)) {
				canvas.off(cc.Node.EventType.TOUCH_CANCEL, touchEnd)
			}
		}

		// canvas.on(cc.Node.EventType.TOUCH_START, () => {
		// 	console.log('canvas touch start')
		// })
		// canvas.on(cc.Node.EventType.MOUSE_DOWN, (e) => {
		// 	console.log('canvas MOUSE_DOWN ')
		// })
		


		canvas.on(cc.Node.EventType.TOUCH_MOVE, touchMove)
		canvas.on(cc.Node.EventType.MOUSE_MOVE, mouseMove)

		canvas.on(cc.Node.EventType.TOUCH_END, touchEnd)
		canvas.on(cc.Node.EventType.TOUCH_CANCEL, touchEnd)
		canvas.on(cc.Node.EventType.MOUSE_UP, mouseUp)
		// canvas.on(cc.Node.EventType.MOUSE_LEAVE, mouseUp)
	},

	removeHtmlCanvasListener(type) {
		const canvasHtml = document.querySelector('canvas');
		canvasHtml.addEventListener(type, (e) => {})
	},

	initWebListener() {

		
		// canvas.on(cc.Node.EventType.MOUSE_DOWN, (e) => {
		// 	console.log('mouse down e: ', e)
		// 	console.log('location: ', e.getLocation());
		// })

		console.log('in initWebListener');
		const canvasHtml = document.querySelector('canvas');

		document.addEventListener('touchstart', this.htmlCanvasTouchstartFunc.bind(this), this);
		document.addEventListener('touchmove', this.htmlCanvasTouchmoveFunc.bind(this), this);
		document.addEventListener('touchend', this.htmlCanvasTouchendFunc.bind(this), this);
		document.addEventListener('click', this.htmlCanvasClickFunc.bind(this), this);
		// canvasHtml.addEventListener('touchcancel', this.htmlCanvasTouchcancelFunc, this);



		// canvasHtml.addEventListener('touchstart', (e) => {
		// 	console.log('html touch start e: ', e);
			 
		// 	const evt = this.createTouchEvent(canvas, 'mousedown', e);
		// 	canvas.dispatchEvent(evt);
		// });

		// canvasHtml.addEventListener('touchmove', (e) => {
		// 	console.log('html touch move e: ', e);

		// 	const evt = this.createTouchEvent(canvas, 'mousemove', e);
		// 	canvas.dispatchEvent(evt);
		// });

		// canvasHtml.addEventListener('touchend', (e) => {
		// 	console.log('html touch end e: ', e);

		// 	const evt = this.createTouchEvent(canvas, 'mouseup', e);
		// 	canvas.dispatchEvent(evt);
		// });

		// canvasHtml.addEventListener('touchcancel', (e) => {
		// 	console.log('html touch cancel e: ', e);

		// 	const evt = this.createTouchEvent(canvas, 'mouseleave', e);
		// 	canvas.dispatchEvent(evt);
		// });


		// canvasHtml.addEventListener('mousedown', (e) => {
		// 	console.log('html mousedown e: ', e);
			
		// 	const baseNode = canvas 
		// 	const subY = e.target.clientHeight;

		// 	const p1 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.clientX, subY - e.clientY));
		// 	const p2 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.layerX, subY - e.layerY));
		// 	const p3 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.offsetX, subY - e.offsetY));
		// 	const p4 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.pageX, subY - e.pageY));
		// 	const p5 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.screenX, subY - e.screenY));
		// 	const p6 = baseNode.parent.convertToNodeSpaceAR(cc.v2(e.x, subY - e.y));


		// 	console.log('p1: ', p1);
		// 	console.log('p2: ', p2);
		// 	console.log('p3: ', p3);
		// 	console.log('p4: ', p4);
		// 	console.log('p5: ', p5);
		// 	console.log('p6: ', p6);
		// });


	
	},

	htmlCanvasTouchstartFunc(e) {
		console.log('html htmlCanvasTouchstartFunc')
		const canvasHtml = document.querySelector('canvas');
		const evt = this.createTouchEvent(canvasHtml, 'mousedown', e);
		canvasHtml.dispatchEvent(evt);
	},
	htmlCanvasTouchmoveFunc(e) {
		console.log('html htmlCanvasTouchmoveFunc')
		const canvasHtml = document.querySelector('canvas');
		const evt = this.createTouchEvent(canvasHtml, 'mousemove', e);
		canvasHtml.dispatchEvent(evt);
	},
	htmlCanvasTouchendFunc(e) {
		console.log('html htmlCanvasTouchendFunc')
		const canvasHtml = document.querySelector('canvas');
		const evt = this.createTouchEvent(canvasHtml, 'mouseup', e);
		canvasHtml.dispatchEvent(evt);
	},
	htmlCanvasTouchcancelFunc(e) {
		const canvasHtml = document.querySelector('canvas');
		const evt = this.createTouchEvent(canvasHtml, 'mouseleave', e);
		canvasHtml.dispatchEvent(evt);
	},

	htmlCanvasClickFunc(e) {
		if (e.aaas){
			return
		}
		const canvasHtml = document.querySelector('canvas');
		const evt = this.createTouchEvent(canvasHtml, 'click', e);
		evt.aaas=1
		canvasHtml.dispatchEvent(evt);
	},
	
	removeHtmlTouchEnd() {
		const canvasHtml = document.querySelector('canvas');

		canvasHtml.removeEventListener('touchend', this.htmlCanvasTouchendFunc, this);

	},

	


	initView() {		
		this.initBg();
		this.initHotZone();
		this.initBottomPart();
	},



	_cocosScale: null,
	initBg() {
		const frameSize = cc.view.getFrameSize();

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

		this._cocosScale = s;

		const bgNode = cc.find('Canvas/bg');
		// const sx = cc.winSize.width / bgNode.width;
		// const sy = cc.winSize.height / bgNode.height;
		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 * s;


	
		const bg = cc.find('Canvas/bg');
		const rectNode = new cc.Node();
		rectNode.x = -bg.x;
		rectNode.y = -bg.y;
		rectNode.scaleX = bg.scaleX;
		rectNode.scaleY = bg.scaleY;
		bg.addChild(rectNode);
		const ctx = rectNode.addComponent(cc.Graphics);
		ctx.fillColor = this.data.bgColor || '#f9bd03';
		ctx.fillRect(-bg.width / 2 , -bg.height / 2, bg.width, bg.height);
		ctx.fill();


	},


	initHotZone() {
		this.initHotZoneBg();

	},

	hotZoneBg: null,
	hotzoneCircleArr: null,
	initHotZoneBg() {
		this.hotZoneBg = new cc.Node();
		this.hotZoneBg.name = 'hotZoneBg';
		this.hotZoneBg.parent = cc.find('Canvas');
		this.hotZoneBg.zIndex = 4;

		this.hotzoneCircleArr = [];


		if (!this.data.bgItem) {
			return;
		}

		cc.loader.load({ url: this.data.bgItem.url }, (err, img) => {

			this.addMask(this.hotZoneBg);

			this.hotZoneBg.width = img.width;
			this.hotZoneBg.height = img.height;



			const box = this.hotZoneBg.getBoundingBox();


			const tmpS = 640 / 720;
			let subNum = 720 - 640;
			const frameSize = cc.view.getFrameSize();
			const winSize = cc.winSize;

			console.log('this.hotZoneBg.box: ', this.hotZoneBg.getBoundingBox());
			console.log('let visiSize=cc.director.getVisibleSize();: ', cc.view.getVisibleSize());
			console.log('lframeSize: ', frameSize);

			let sx = frameSize.width / this._designSize.width;
			let sy = frameSize.height / this._designSize.height;
			const mapS = Math.min(sx, sy);
			// const sy = canvas.height * tmpS / box.height;


			const bgBottom = cc.find('Canvas/bgBottom');
			bgBottom.scale = mapS * this._cocosScale;
			// subNum = bgBottom.height;

			sx = frameSize.width * this._cocosScale / img.width;
			sy = (frameSize.height * this._cocosScale - subNum * mapS * this._cocosScale) / img.height;


			const sprNode = new cc.Node();
			var sf = new cc.SpriteFrame(img);
			// const spr = this.hotZoneBg.addComponent(cc.Sprite);
			const spr = sprNode.addComponent(cc.Sprite);
			spr.spriteFrame = sf
			sprNode.width = this.hotZoneBg.width;
			sprNode.height = this.hotZoneBg.height;
			sprNode.parent = this.hotZoneBg;

			this.hotZoneBg.scale = Math.min(sx, sy);

			// this.hotZoneBg.y = -frameSize.height / 2 * this._cocosScale + this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY + (subNum * mapS * this._cocosScale);
			this.hotZoneBg.y = frameSize.height / 2 * this._cocosScale - this.hotZoneBg.height / 2 * this.hotZoneBg.scaleY;


			// this.hotZoneBg.opacity = 20;

			const bgWhite = cc.find('Canvas/bgWhite');
			bgWhite.y = this.hotZoneBg.y;

			bgWhite.scaleX = this.hotZoneBg.width * this.hotZoneBg.scaleX / bgWhite.width;
			bgWhite.scaleY = this.hotZoneBg.height * this.hotZoneBg.scaleY / bgWhite.height;


			const canvas = cc.find('Canvas');
			const shadowNode = new cc.Node();
			shadowNode.y = bgWhite.y;
			shadowNode.scaleX = bgWhite.scaleX;
			shadowNode.scaleY = bgWhite.scaleY;
			canvas.addChild(shadowNode);
			const ctx = shadowNode.addComponent(cc.Graphics);
			ctx.fillColor = cc.Color.BLACK.setA(30);
			// ctx.fillRect(5, 5, this.hotZoneBg.width*this.hotZoneBg.scaleX, this.hotZoneBg.height * this.hotZoneBg.scaleY);
			ctx.fillRect(-bgWhite.width / 2 + 8 / bgWhite.scaleX * this.hotZoneBg.scale, -bgWhite.height / 2 - 8 / bgWhite.scaleX * this.hotZoneBg.scale, bgWhite.width, bgWhite.height);
			ctx.fill();

			shadowNode.zIndex = 1;
			bgWhite.zIndex = 2;

			bgBottom.y = -frameSize.height / 2 * this._cocosScale - 15 * bgBottom.scaleY;

			this.data.hotZoneItemArr.forEach((item) => {
				if (item.gIdx == '0') {
					this.setOneCirclePoint(item);
				} else if (item.gIdx == '1') {
					this.setOnePic(item);
				} else if(item.gIdx == '2') {
					this.setOneAnima(item);
				}

			});

		});

	},

	addMask(node) {
		const mask = node.addComponent(cc.Mask);
		mask.type = cc.Mask.Type.RECT;
	},

	bottomPicArr: null,
	initBottomPart() {

		const bgBottom = cc.find('Canvas/bgBottom');
		const script = bgBottom.getComponent('bgBottom_cc_mz_003');

		const picArr = [];
		this.data.hotZoneItemArr.forEach((item) => {
			if (item.gIdx == '0') {
				picArr.push(item);
			}
		});
		script.setItemData(picArr);
		this.bottomPicArr = picArr;
	},

	getBottomPicArr() {
		const arr = [];
		// for (let i = 0; i < this.hotzoneCircleArr.length; i++) {
		// 	arr.push(this.hotzoneCircleArr[i].data);
		//
		// }
		this.hotzoneCircleArr.forEach((item) => {
			console.log('item: ', item);
			arr.push(item.data);
			console.log('arr: ', arr);

		});

		console.log('hotzoneCircleArr: ', this.hotzoneCircleArr);
		console.log('arr: ', arr);
		return arr;
	},

	setOneAnima(data) {


		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		this.hotZoneBg.addChild(rectNode);


		const ctx = rectNode.addComponent(cc.Graphics);
		// 红色矩形
		ctx.lineWidth = 4;
		ctx.strokeColor = cc.Color.BLACK;
		ctx.fillColor = cc.Color.WHITE.setA(100);

		const scale = rate / this.hotZoneBg.scaleY;

		rectNode.width = data.rect.width * scale;
		rectNode.height = data.rect.height * scale;
		rectNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

		rectNode.anchorX = rectNode.anchorY = 0;


		if (this.data.bgItem.isShowDebugLine) {
			ctx.rect(0, 0, rectNode.width, rectNode.height);
		}
		ctx.stroke();
		ctx.fill();



		const animaNode = new cc.Node();
		animaNode.name = 'anima_' + data.index;
		this.hotZoneBg.addChild(animaNode);

		// rectNode.addChild(animaNode);
		// animaNode.x = rectNode.width / 2;
		// animaNode.y = rectNode.height / 2;


		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				animaNode.audioClip = audioClip;
			});
		}


		const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);

		const image = data.texPngData.url//"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
		const ske = data.skeJsonData.url//"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
		const atlas = data.texJsonData.url//"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
		cc.loader.load(image, (error, texture) => {

			cc.loader.load({ url: atlas, type: 'txt' }, (error, atlasJson) => {

				cc.loader.load({ url: ske, type: 'txt' }, (error, dragonBonesJson) => {

					const atlas = new dragonBones.DragonBonesAtlasAsset();
					atlas.atlasJson = atlasJson;
					atlas.texture = texture;

					const asset = new dragonBones.DragonBonesAsset();
					asset.dragonBonesJson = dragonBonesJson;

					dragonDisplay.dragonAtlasAsset = atlas;
					dragonDisplay.dragonAsset = asset;

					let json = JSON.parse(asset.dragonBonesJson);
					let armatures = json["armature"];
					console.log('armatures: ', armatures);
					let armatureNames = [];
					for (let i = 0; i < armatures.length; i++) {
						armatureNames.push(armatures[i].name);
					}
					// console.log('armatureNames: ', armatureNames);
					if (armatureNames.length > 0) {
						let defaultArmatureName = armatureNames[0];
						dragonDisplay.armatureName = defaultArmatureName;
						// let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
						let defaultArmature = armatures[0];
						let animations = defaultArmature.animation;
						let animationNames = [];
						for (let i = 0; i < animations.length; i++) {
							animationNames.push(animations[i].name);
						}

						rectNode.addComponent(cc.Button);
						rectNode.on('click', () => {
							if (rectNode.isClicked) {
								// return;
							}
							rectNode.isClicked = true;
							console.log('clicked');

							if (animaNode.audioClip) {
								cc.audioEngine.stopAllEffects();
								cc.audioEngine.playEffect(animaNode.audioClip, false, 0.8);
							}

							if (animationNames.length > 0) {
								dragonDisplay.playAnimation(animationNames[0], 1);
							}
						});
					}

				});
			});
		});

	},



	setOnePic(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const picNode = new cc.Node();
		picNode.data = data;
		this.hotZoneBg.addChild(picNode);

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

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

			const scale = rate / this.hotZoneBg.scaleY;

			picNode.width = data.rect.width * scale;
			picNode.height = data.rect.height * scale;
			picNode.x = -this.hotZoneBg.width / 2 + data.rect.x * scale;
			picNode.y = this.hotZoneBg.height / 2 - data.rect.height * scale - data.rect.y * scale;

			picNode.anchorX = picNode.anchorY = 0;

			if (data.audio_url) {
				this.addPicAudio(picNode);
			}
		});

	},

	addPicAudio(picNode) {
		const data = picNode.data;
		
		cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
			picNode.audioClip = audioClip;
		});

		picNode.addComponent(cc.Button);
		picNode.on('click', () => {
				if (picNode.audioClip) {
					cc.audioEngine.stopAllEffects();
					cc.audioEngine.playEffect(picNode.audioClip, false, 0.8);
				}
		});
	},

	setOneCirclePoint(data) {
		const rate = (this.hotZoneBg.scale * this.hotZoneBg.width) / this.data.bgItem.rect.width;

		const rectNode = new cc.Node();
		rectNode.name = 'rect' + data.index;
		rectNode.data = data;
		this.hotZoneBg.addChild(rectNode);


		const spr = rectNode.addComponent(cc.Sprite);
		const circleSmallNode = cc.find('Canvas/res/circle_bg_small')
		spr.spriteFrame = circleSmallNode.getComponent(cc.Sprite).spriteFrame;


		const scale = rate / this.hotZoneBg.scaleY;

		rectNode.width = circleSmallNode.width;
		rectNode.height = circleSmallNode.height;
		rectNode.x = -this.hotZoneBg.width / 2 + (data.rect.x + data.rect.width / 2) * scale;
		rectNode.y = this.hotZoneBg.height / 2 - data.rect.height / 2 * scale - data.rect.y * scale;

		rectNode.anchorX = rectNode.anchorY = 0.5;

		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				data.audioClip = audioClip;
			});
		}

		this.hotzoneCircleArr.push(rectNode);



		if (!data.skeJsonData) {
			return;
		}



		const animaNode = new cc.Node();
		animaNode.name = 'anima_' + data.index;
		this.hotZoneBg.addChild(animaNode);

		data.animaNode = animaNode;
		animaNode.active = false;

		if (data.audio_url) {
			cc.assetManager.loadRemote(data.audio_url, (err, audioClip) => {
				animaNode.audioClip = audioClip;
			});
		}


		const dragonDisplay = animaNode.addComponent(dragonBones.ArmatureDisplay);

		const image = data.texPngData.url//"http://staging-teach.cdn.ireadabc.com/5a0c5af3e952acd0ac83a6e5c6f03ff1.png";
		const ske = data.skeJsonData.url//"http://staging-teach.cdn.ireadabc.com/bd825dcceea298d1146be8067ae3d17f.json";
		const atlas = data.texJsonData.url//"http://staging-teach.cdn.ireadabc.com/246f8991b729fa3e5a7f4802de828efa.json";
		cc.loader.load(image, (error, texture) => {

			cc.loader.load({ url: atlas, type: 'txt' }, (error, atlasJson) => {

				cc.loader.load({ url: ske, type: 'txt' }, (error, dragonBonesJson) => {

					const atlas = new dragonBones.DragonBonesAtlasAsset();
					atlas.atlasJson = atlasJson;
					atlas.texture = texture;

					const asset = new dragonBones.DragonBonesAsset();
					asset.dragonBonesJson = dragonBonesJson;

					dragonDisplay.dragonAtlasAsset = atlas;
					dragonDisplay.dragonAsset = asset;

					let json = JSON.parse(asset.dragonBonesJson);
					let armatures = json["armature"];
					console.log('armatures: ', armatures);
					let armatureNames = [];
					for (let i = 0; i < armatures.length; i++) {
						armatureNames.push(armatures[i].name);
					}
					// console.log('armatureNames: ', armatureNames);
					if (armatureNames.length > 0) {
						let defaultArmatureName = armatureNames[0];
						dragonDisplay.armatureName = defaultArmatureName;
						// let animationNames = dragonDisplay.getAnimationNames(defaultArmatureName);
						let defaultArmature = armatures[0];
						let animations = defaultArmature.animation;
						let animationNames = [];
						for (let i = 0; i < animations.length; i++) {
							animationNames.push(animations[i].name);
						}

						// rectNode.addComponent(cc.Button);
						animaNode.showAnima = () => {
							animaNode.active = true;
							// rectNode.on('click', () => {
							if (rectNode.isClicked) {
								// return;
							}
							rectNode.isClicked = true;
							console.log('clicked');

							if (animaNode.audioClip) {
								cc.audioEngine.stopAllEffects();
								const audioID = cc.audioEngine.playEffect(animaNode.audioClip, false, 0.8);
								cc.audioEngine.setFinishCallback(audioID, () => {

									const gjId = cc.audioEngine.playEffect(this._gjAudioSource.clip, false, 0.8);
									cc.audioEngine.setFinishCallback(gjId, () => {

										const isEnd = this.checkGameEnd();
										if (isEnd) {
											this.gameEnd();
										}
									});
								});
							}

							if (animationNames.length > 0) {
								dragonDisplay.playAnimation(animationNames[0], 1);
							}
						}
					}

				});
			});
		});

	},

	checkGameEnd() {
		for (let i=0; i<this.hotzoneCircleArr.length; i++) {
			if (this.hotzoneCircleArr[i].active) {
				return false;
			}
		}
		return true;
	},

	gameEnd() {
		console.log('this.gameEnd');
		this.playEndEffect();
	},


	playEndEffect() {
		playAudio(this._endAudio.clip, 0.8);
		const camera = cc.find('Canvas/Main Camera');
		camera.zIndex = 100;

		showTrebleFirework(camera, cc.find('RibbonNodeBase').children);
	},



	_curShowItem: null,
	bottomItemClick(item) {

		return;

		if (this._curShowItem) {
			return;
		}
		if (item.data.isClicked) {
			return;
		}
		item.data.isClicked = true;
		item.opacity = 100;




		// const data = item.data;

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

		const newNode = new cc.Node();
		newNode.parent = cc.find('Canvas');
		newNode.zIndex = 10;
		newNode.scale = 1.5;
		newNode.opacity = 255;
		newNode.scale = 0.1;
		newNode.data = item.data;

		this._curShowItem = newNode;


		// button
		newNode.addComponent(cc.Button);
		newNode.on('click', () => {
			if (newNode.isSmall) {
				if (this._curShowItem) {
					return;
				}
				this._curShowItem = newNode;
				this._toCenterShow(newNode);
			} else {
				console.log('newNode', newNode);

				if (newNode.data.audioClip) {
					cc.audioEngine.stopAllEffects();
					cc.audioEngine.playEffect(newNode.data.audioClip, false, 0.8);
				}
			}
			console.log('newNode click');
		});



		// sprite
		const spr = newNode.addComponent(cc.Sprite);
		const circleBgNode = cc.find('Canvas/res/circle_bg')
		spr.spriteFrame = circleBgNode.getComponent(cc.Sprite).spriteFrame;
		newNode.width = circleBgNode.width;
		newNode.height = circleBgNode.height;

		// position
		const worldPos = item.parent.convertToWorldSpaceAR(cc.v2(item.x, item.y));
		const localPos = newNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
		newNode.x = localPos.x;
		newNode.y = localPos.y;

		// copy item
		const sprNode = cc.instantiate(item);

		sprNode.parent = newNode;
		sprNode.opacity = 255;
		sprNode.x = 0;
		sprNode.y = 0;
		sprNode.scale = (newNode.width - 200) / sprNode.width;
		sprNode.removeComponent(cc.Button);


		this._toCenterShow(newNode);

	},

	_toCenterShow(node) {
		const bgBottom = cc.find('Canvas/bgBottom');
		cc.tween(node)
			.to(1, { x: 0, y: 0, scale: bgBottom.scale }, { easing: 'cubicOut' })
			.call(() => {
			})
			.start();

		node.isSmall = false;
		node.zIndex = 11;

	},


	hideCurShowItem() {

		const targetNode = this.getTargetCircleNode();

		const worldPos = targetNode.parent.convertToWorldSpaceAR(cc.v2(targetNode.x + targetNode.width / 2, targetNode.y + targetNode.height / 2));
		const localPos = this._curShowItem.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));

		const s = targetNode.parent.scaleY * targetNode.height * targetNode.scaleY / this._curShowItem.height;

		const changeNode = this._curShowItem;
		changeNode.cantouch = false;
		cc.tween(this._curShowItem)
			.to(1, { scale: s * 0.95, x: localPos.x, y: localPos.y }, { easing: 'cubicOut' })
			.call(() => {
				changeNode.cantouch = true;
			})
			.start();

		this._curShowItem.isSmall = true;
		this._curShowItem.zIndex = 9;
		this._curShowItem = null;


	},

	getTargetCircleNode() {

		const dataIndex = this._curShowItem.data.index;
		return this.hotzoneCircleArr.find((item) => {
			return item.data.index == dataIndex;
		});
	},




	canvasClick() {
		console.log('canvas click');
		if (!this._curShowItem) {
			return;
		}

		this.hideCurShowItem();
	},



	touchStartItem(item) {

		if (item.data.isDrag) {
			return;
		}
		item.data.isDrag = true;



		const circleSmallNode = cc.find('Canvas/res/circle_bg_small')
		const bgBottom = cc.find('Canvas/bgBottom')

		item.opacity = 0;


		const newNode = new cc.Node();
		newNode.parent = cc.find('Canvas');
		newNode.zIndex = 10;
		newNode.opacity = 255;
		newNode.data = item.data;
		newNode.width = circleSmallNode.width;
		newNode.height = circleSmallNode.height;
		newNode.scale = bgBottom.scale * item.scale;





		// position
		const worldPos = item.parent.convertToWorldSpaceAR(cc.v2(item.x, item.y));
		const localPos = newNode.parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
		newNode.x = localPos.x;
		newNode.y = localPos.y;

		// copy item
		const sprNode = cc.instantiate(item);

		sprNode.parent = newNode;
		sprNode.opacity = 255;
		sprNode.x = 0;
		sprNode.y = 0;
		sprNode.scale = (newNode.width) / sprNode.width;
		sprNode.removeComponent(cc.Button);



		const worldRect1 = item.getBoundingBoxToWorld();
		const worldRect2 = newNode.getBoundingBoxToWorld();
		const rate = worldRect1.width / worldRect2.width;
		console.log('worldRect1: ', worldRect1);
		console.log('worldRect2: ', worldRect2);
		console.log('rate: ', rate);
		newNode.scale *= rate;


		this._curShowItem = newNode;
		this._curShowItem.bgBottomItem = item;
		this._curShowItem.baseX = this._curShowItem.x;
		this._curShowItem.baseY = this._curShowItem.y;



	},

	checkOnTargetCircle(e) {

		for (let i = 0; i < this.hotzoneCircleArr.length; i++) {

			const circle = this.hotzoneCircleArr[i];
			if (circle.data.index == this._curShowItem.data.index) {
				const worldPos = this._curShowItem.parent.convertToWorldSpaceAR(cc.v2(this._curShowItem.x, this._curShowItem.y));
				const worldRect = circle.getBoundingBoxToWorld();
				if (worldRect.contains(worldPos)) {
					this.itemAppear(circle);
					return;
				}
			}
		}


		this.itemBack();
	},

	itemAppear(circle) {
		circle.active = false;
		this._curShowItem.active = false;


		// cc.tween(this._curShowItem.data.pic)
		// 	.to(3, {opacity: 255}, {easing: 'cubicOut'})
		// 	.start();
		// if (circle.data.audioClip) {
		// 	cc.audioEngine.stopAllEffects();
		// 	cc.audioEngine.playEffect(circle.data.audioClip, false, 0.8);
		// }


		if (circle.data.animaNode) {
			circle.data.animaNode.showAnima();
		}
	},

	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.stopAllEffects();
			cc.audioEngine.playEffect(this._curShowItem.data.audioClip, false, 0.8);
		} else {

			cc.audioEngine.playEffect(this._wrongAudioSource.clip, false, 0.8);

			// console.log("this._wrongAudioSource: ", this._wrongAudioSource);
			// 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;
			})
			.start();


	},


	canvasTouchMove(e) {

		if (!this._curShowItem) {
			return;
		}

		const pos = e.getLocation();
		this._curShowItem.x = pos.x - e.currentTarget.width / 2;
		this._curShowItem.y = pos.y - e.currentTarget.height / 2;
	},

	canvasTouchEnd(e) {

		if (!this._curShowItem) {
			return;
		}

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






	createTouchEvent(touchTarget, type, e) {  
		const otcs = [...e.touches];
		// console.log(e.type, e)
		// e = e.type.startsWith('touch') ?  e.touches[0] : e
		// if (!e.touches) {
		//     e.touches = otcs
		// }
		const posInfo = e.touches ? e.touches[0] || {} : e;


		const touch = new Touch({
				identifier: -Date.now(),
				target: touchTarget,
				clientX: posInfo.clientX||0,
				clientY: posInfo.clientY||0,
				force: posInfo.force,
				pageX: posInfo.pageX,
				pageY: posInfo.pageY,
				radiusX: posInfo.radiusX,
				radiusY: posInfo.radiusY,
				rotationAngle: e.rotationAngle,
				screenX: posInfo.screenX,
				screenY: posInfo.screenY,
			});
			const touchEvent = new TouchEvent(type, {
				touches: [touch],
				view: window,
				cancelable: true,
				bubbles: true,
			 
				changedTouches:  [touch]
			});
			touchEvent.fireByMe = true;
			touchEvent.pageX = posInfo.pageX
			touchEvent.pageY = posInfo.pageY
			touchEvent.clientX = posInfo.clientX
			touchEvent.clientY = posInfo.clientY
			touchEvent.screenX = posInfo.screenX
			touchEvent.screenY = posInfo.screenY
		return touchEvent;
	},

	// update (dt) {},
});
