// 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 { getSprNode } from "./util";
import { getSprNode, playAudioByUrl, getScaleRateBy2Node, localPosTolocalPos, randomSortByArr, loadDragonBones, playAudio, showTrebleFirework, delayCall, removeFromArr, showBtnAnima, asyncDelay, RandomInt, jellyShake, showLog} from "../script/util";

cc.Class({
	extends: cc.Component,

	properties: {
		baseWidth: {
			default: 1280,
			type: cc.Integer
		},
		baseHeight: {
			default: 720,
			type: cc.Integer
		}
	},

	onLoad() {
		cc.debug.setDisplayStats(false);
		this.initSceneData();
		this.initSize();
	},

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



	_designSize: null,
	_frameSize: null,
	_mapScaleMin: null,
	_mapScaleMax: null,
	_cocosScale: null,
	canvas: 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

		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;

		this.canvas = cc.find('Canvas');


		// cc.log('cc.Canvas: ', cc.Canvas);
	},

	isTeacher: null,
	serverAllUser: null,
	start() {
		let getData = this.getData.bind(this);
		if (window && window.courseware) {
			getData = window.courseware.getData;
		}
		getData((data, aspect) => {

			if (window['air']?.airClassInfo?.user?.classRole == 'tea') {
        this.isTeacher = true;
      }
			if (aspect) {
        console.log('aspect : ', aspect);
        this.serverAllUser = aspect.all_user;
				this.initPageData(aspect);
      }



			this.data = data || this.getDefaultData();
			console.log('data:', this.data);
			console.log('dataStr:', JSON.stringify( this.data ));

			this.preloadItem()
		})
	},

	// 用于存储公共数据 当翻页时清空 
	pageData: null, 
	initPageData(aspect) {
		const pageDataStr = aspect?.page_aspect?.pagedata;
		if (!pageDataStr) {
			this.pageData = {};
		} else {
			this.pageData = JSON.parse(pageDataStr);
		}
		console.log('this.pageData: ', this.pageData);
	},

	setPageData(key, value, isSend=true) {



		if (this.pageData) {

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

			this.pageData[key] = value;
			if (isSend) {
				this.sendPageData();
			}
		}
	},

	getPageData(key) {
		if (this.pageData && this.pageData[key] != null) {
			return this.pageData[key];
		}
	},

	sendPageData() {

		const data = this.pageData;
		if (window && window.courseware) {
			let storePageAspect = window.courseware.storePageAspect;
			if (storePageAspect) {
				storePageAspect(data);
				console.log('storePageAspect : ', data);
			}
		}
	},

	_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, 'ak_08');
			return;
		}

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

		func(this.getDefaultData());
	},

	getDefaultData() {
		const dataJson = '{"video_url":"http://staging-teach.cdn.ireadabc.com/537aa38d43627c3997b28da1f1cc43da.mp4","lrcData":{"audio_url":"http://staging-teach.cdn.ireadabc.com/c5bc3378e4e0be11b67fc6cf625dfdf7.mp3","fontSize":24,"lineHeight":32,"lyrics":[{"time":0,"data":"","newLine":false},{"time":4.105990000000002,"data":"Apple, apple. I like apples.","newLine":false},{"time":7.992413,"data":"I like apples.","newLine":false},{"time":10.024486,"data":"What about you?","newLine":false},{"time":11.416603999999996,"data":"","newLine":false},{"time":15.850838,"data":"Banana, banana. I like bananas.","newLine":false},{"time":20.004074,"data":"I like bananas.","newLine":false},{"time":21.992325,"data":"What about you?","newLine":false},{"time":23.668069,"data":"","newLine":false},{"time":25.011329000000003,"data":"Ah, banana, my favorite!","newLine":false},{"time":27.440496,"data":"","newLine":false},{"time":28.103187000000002,"data":"Orange, orange. I like oranges.","newLine":false},{"time":31.986444,"data":"I like oranges.","newLine":false},{"time":34.104426999999994,"data":"What about you?","newLine":false},{"time":35.740390999999995,"data":"","newLine":false}]},"accompany_audio_url":"http://staging-teach.cdn.ireadabc.com/6d59bf82e77182bcb6520e3a3593b579.mp3"}';
		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) => {
	
			this.addServerListener();

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

		this._audioResList.push({url: this.data.video_url});
		this._audioResList.push({url: this.data.accompany_audio_url});
		this._audioResList.push({url: this.data?.lrcData?.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(cb) {
		this.initData();

		this.initView(cb);

	},

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




	initData() {


		this.initAudioEffect();
	},



	bgClip: null,
	initAudioEffect() {
		// this.bgClip = cc.find('Canvas/res/audio/bg').getComponent(cc.AudioSource).clip;
	


	},

	playBgMusic() {
		playAudio(this.bgClip, () => {
			this.playBgMusic();
		})
	},


	sendServerEvent(key, data) {


    const c = window.courseware;
		if (c) {
			c.sendEvent(key, data);
		}
  },


	addServerListener() {

		console.log(' in addServerListener');

		const c = window.courseware;
		if (!c) {
			return;
		}


		if (!window.air) {
			console.log(' window air err !!!!!!!!')
			return;
		}

		window.air.onCourseInScreen = (next) => {
			//各种逻辑
			this.loadEnd(() => {
				next();
			});
		}




		c.onEvent('game_start', (data, next) => {
			this.gameStart();
			next();
		});



		// c.onEvent('top_btn_click', (data, next) => {
		// 	console.log('in top_btn_click : ', data);
		// 	this.topBtnClick(data.index);
		// 	next();
		// });
	

	},

	gameStart() {

		const labelNode = new cc.Node();
		const label = labelNode.addComponent(cc.Label);
		label.string = '游戏开始';
		labelNode.color = cc.Color.BLACK;
		labelNode.y = 200;
		this.canvas.addChild(labelNode);

	},






	initView(cb) {



		const progress = this.getPageData("progress");

		switch(progress) {
			case '1':
				this.gameStart();
				break;

			default:
				this.initBtn();
				break;
		}
		// this.initBtn();

		cb(); 

	},


	initBtn() {

		if (this.isTeacher) {
			const btn = getSprNode("submit")
			btn.scale = 0.5 * this._mapScaleMin;
			this.canvas.addChild(btn);

			btn.on(cc.Node.EventType.TOUCH_START, () => {

				this.sendServerEvent('game_start', {});
				this.setPageData('progress', '1')
				btn.active = false;
			})
		}
	
	},























	initListener() {

		const canvas = cc.find('Canvas');
		
		let downFlag = false;



		const touchStart = (e) => {
			this.canvasTouchStart(e);
			console.log('touch start');

			if (canvas.hasEventListener(cc.Node.EventType.MOUSE_DOWN)) {
				canvas.off(cc.Node.EventType.MOUSE_DOWN, mouseDown)
			}
		}


		const mouseDown = (e) => {
			if (!downFlag) {
				return;
			}
			this.canvasTouchStart(e);
			console.log('mouse down');

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


		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) => {
		
			downFlag = false;
			this.canvasTouchEnd(e);

			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) => {
	
			downFlag = false;

			this.canvasTouchEnd(e);

			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, touchStart)
		canvas.on(cc.Node.EventType.MOUSE_DOWN, mouseDown)

		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)

	},

	canvasTouchStart(e) {


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

	},

	canvasTouchMove(e) {

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

	},

	canvasTouchEnd(e) {

		if (!this._curShowItem) {
			return;
		}

		this._curShowItem = null;
	},



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

	removeHtmlTouchEnd() {
		// const canvasHtml = document.querySelector('canvas');
		// canvasHtml.removeEventListener('touchend', this.htmlCanvasTouchendFunc, this);
	},

















	isDestroy: null,
	onDestroy() {
		this.isDestroy = true;
		cc.Tween.stopAll();


	}


});
