import { onHomeworkFinish } from "../script/util";
import { defaultData } from "../script/defaultData";

cc.Class({


	extends: cc.Component,

	properties: {
		item: cc.Node,
		itembgTop: cc.Node,
		itembgBottom: cc.Node,
		itemParentT: cc.Node,
		itemParentB: cc.Node,

		sahuaNode: cc.Node,
		timeoutNode: cc.Node,

		endNode: cc.Node,
		posList: [],
		itemPosList: [],
		itemParent: cc.Node,
		comfirBtn: cc.Node,
		progress: cc.ProgressBar,
		title: cc.Label,
		timeEnd: false,
		timer: 10,
	},


	// moveItem(){

	// }

	onLoad() {
		// this.item.on(cc.Node.EventType.TOUCH_MOVE, this.mouseFun, this);
		this.initSceneData();
		this.initSize();
		// for (let i = 0; i < this.itemParent.children.length; i++) {
		// 	this.posList.push(this.itemParent.children[i].getPosition())
		// }
	},

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

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

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

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

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

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


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

		getData((data) => {
			console.log('data:', data);
			this.data = data || this.getDefaultData();
			// this.data = { "listNum": 3, "title": "foolse", "titleAudio": "http://staging-teach.cdn.ireadabc.com/69d6e4097490ff9c53f2f57442af39a9.mp3", "music0": "http://staging-teach.cdn.ireadabc.com/952b3b26f8a617bfe9d60a9304e141d4.mp3", "music1": "http://staging-teach.cdn.ireadabc.com/c14ff6730182ed312d629b3d234f1a0c.mp3", "music2": "http://staging-teach.cdn.ireadabc.com/f9ef4481b596618f6e3574b00417d7ab.mp3", "pic0": "http://staging-teach.cdn.ireadabc.com/773bbe32b7917a072e5c977bcdfca021.jpeg", "pic1": "http://staging-teach.cdn.ireadabc.com/241097d62285721e4a70a15289093525.png", "pic2": "http://staging-teach.cdn.ireadabc.com/4f45f37ea1f07e444f3ef94101857067.jpeg" }
			// this.data = { "listNum": 3, "title": "foolse", "titleAudio": "http://staging-teach.cdn.ireadabc.com/69d6e4097490ff9c53f2f57442af39a9.mp3", "music0": "http://staging-teach.cdn.ireadabc.com/952b3b26f8a617bfe9d60a9304e141d4.mp3", "music1": "http://staging-teach.cdn.ireadabc.com/b121f1180eb32bca23d728e55d370e58.mp3", "music2": "http://staging-teach.cdn.ireadabc.com/f9ef4481b596618f6e3574b00417d7ab.mp3", "pic0": "http://staging-teach.cdn.ireadabc.com/773bbe32b7917a072e5c977bcdfca021.jpeg", "pic1": "http://staging-teach.cdn.ireadabc.com/241097d62285721e4a70a15289093525.png", "pic2": "http://staging-teach.cdn.ireadabc.com/4f45f37ea1f07e444f3ef94101857067.jpeg", "timer": "20" };
			// this.data = {"listNum":7,"title":"shfdklsw","titleAudio":"http://staging-teach.cdn.ireadabc.com/3968bcd14a5edb20dffc6fa3e9d2d6bd.mp3","music0":"http://staging-teach.cdn.ireadabc.com/952b3b26f8a617bfe9d60a9304e141d4.mp3","music1":"http://staging-teach.cdn.ireadabc.com/b121f1180eb32bca23d728e55d370e58.mp3","music2":"http://staging-teach.cdn.ireadabc.com/f9ef4481b596618f6e3574b00417d7ab.mp3","pic0":"http://staging-teach.cdn.ireadabc.com/773bbe32b7917a072e5c977bcdfca021.jpeg","pic1":"http://staging-teach.cdn.ireadabc.com/241097d62285721e4a70a15289093525.png","pic2":"http://staging-teach.cdn.ireadabc.com/4f45f37ea1f07e444f3ef94101857067.jpeg","timer":"20","music3":"http://staging-teach.cdn.ireadabc.com/f9ef4481b596618f6e3574b00417d7ab.mp3","music4":"http://staging-teach.cdn.ireadabc.com/952b3b26f8a617bfe9d60a9304e141d4.mp3","music5":"http://staging-teach.cdn.ireadabc.com/b121f1180eb32bca23d728e55d370e58.mp3","music6":"http://staging-teach.cdn.ireadabc.com/f21e5dfacc838787c9844d59eabdc415.mp3","pic6":"http://staging-teach.cdn.ireadabc.com/73082243c775235d13a5e0bf37981f68.jpeg","pic3":"http://staging-teach.cdn.ireadabc.com/68ca0ac4d0c0c7bc47215c84970f33af.jpeg","pic4":"http://staging-teach.cdn.ireadabc.com/f21c152a06d0239baa511b8adb8fc766.jpeg","pic5":"http://staging-teach.cdn.ireadabc.com/2f88797f4d298a5f36513d09b2d1d534.jpeg"};
			this.data = JSON.parse(JSON.stringify(this.data))
			// console.log(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);
		});
	},


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

	_cantouch: null,
	initData() {
		// 所有全局变量 默认都是null 
		this._cantouch = true;
	},

	audioBtn: null,
	sahuaMusic: null,
	timeoutMusic: null,
	warnMusic: null,
	initAudio() {
		const audioNode = cc.find('Canvas/res/audio');

		const getAudioByResName = (resName) => {
			return audioNode.getChildByName(resName).getComponent(cc.AudioSource);
		}
		this.audioBtn = getAudioByResName('btn');
		this.sahuaMusic = getAudioByResName('sahua');
		this.timeoutMusic = getAudioByResName('timeout');
		this.warnMusic = getAudioByResName('warn');
	},


	initView() {
		this.initTitle()
		this.initItem()
		this.initClock()


		// this.initBg();
		// this.initPic();
		// this.initBtn();
		// this.initIcon();
	},
	initTitle() {
		this.title.string = this.data.title;
		this.playAudioByUrl(this.data.titleAudio);
	},
	initClock() {
		let count = this.data.timer;
		this.callback = function () {
			this.progress.progress = count / this.data.timer
			this.progress.node.children[1].y = 160 - (320 - count / this.data.timer * 320)
			if (count <= 0) {
				this.unschedule(this.callback);
				this.timeEnd = true;
				this.checkTheList()
				this.comfirBtn.active = true;
				return
			}
			count--;
		}
		this.schedule(this.callback, 1);
	},
	initItem() {
		let numList = []
		for (let i = 0; i < this.data.listNum; i++) {
			numList.push(i)
			let nodeT = cc.instantiate(this.itembgTop)
			nodeT.parent = this.itemParentT;
			nodeT.y = 100;
			nodeT.children[0].getComponent(cc.Label).string = i + 1
			nodeT.active = true;

			let nodeB = cc.instantiate(this.itembgBottom)
			nodeB.parent = this.itemParentB;
			nodeB.y = -100;
			nodeB.active = true;
		}
		numList.sort(this.randomSort)
		this.scheduleOnce(() => {
			// for()
			for (let i = 0; i < this.data.listNum; i++) {
				this.posList.push(this.itemParentT.children[i].getPosition())
				this.posList.push(this.itemParentB.children[i].getPosition())
				let item = cc.instantiate(this.item)
				item.active = true;
				item.parent = this.itemParent;
				item.numberIndex = numList[i];
				this.getSpriteFrimeByUrl(this.data['pic' + numList[i]], (texture) => {
					const spriteFrame = new cc.SpriteFrame(texture)
					item.children[2].getComponent(cc.Sprite).spriteFrame = spriteFrame
					item.children[2].scale = this.getPicScale(texture)
				})
				item.setPosition(this.itemParentB.children[i].getPosition())
				item.on(cc.Node.EventType.TOUCH_START, this.mouseStart, this);
				item.on(cc.Node.EventType.TOUCH_MOVE, this.mouseFun, this);
				item.on(cc.Node.EventType.TOUCH_END, this.mouseEnd, this);
				// item.node.
			}
		}, 0.01)

	},
	getPicScale(node) {

		let scale1 = node.width / node.height;
		if (scale1 == 9 / 8) {
			return 180 / node.width
		} else if (scale1 > 9 / 8) {
			return 180 / node.width
		} else if (scale1 < 9 / 8) {
			return 160 / node.height
		}

	},
	mouseStart(event) {
		this.oldPostion = event.target.getPosition()
		let num = event.target.numberIndex
		this.playAudioByUrl(this.data['music' + num]);
	},
	mouseFun(event) {
		let delta = event.getDelta();
		event.target.x += delta.x;
		event.target.y += delta.y;
	},
	mouseEnd(event) {
		let position = event.target.getPosition()
		let reSetPostion = true;
		let newPostion = (0, 0);
		for (let i = 0; i < this.posList.length; i++) {
			if (position.x > this.posList[i].x - 75 && position.x < this.posList[i].x + 75 && position.y < this.posList[i].y + 75 && position.y > this.posList[i].y - 75) {
				reSetPostion = false;
				newPostion = this.posList[i]
			}
		}
		if (reSetPostion) {
			event.target.setPosition(this.oldPostion)
		} else {
			for (let i = 0; i < this.itemParent.children.length; i++) {
				if (newPostion.x == this.itemParent.children[i].getPosition().x && newPostion.y == this.itemParent.children[i].getPosition().y) {
					this.itemParent.children[i].setPosition(this.oldPostion)
					event.target.setPosition(newPostion)
					return;
				}
			}
			event.target.setPosition(newPostion)
			this.showBtn()
		}
	},

	randomSort(a, b) { return Math.random() > 0.5 ? -1 : 1; },
	randomSort2(a, b) { return a.x < b.x ? -1 : 1 },
	showBtn() {
		let showbtn = true;
		for (let i = 0; i < this.itemParent.children.length; i++) {
			if (this.posList[0].y != this.itemParent.children[i].getPosition().y) {
				showbtn = false;
			}
		}
		if (showbtn) {
			this.comfirBtn.active = true;
		} else {
			this.comfirBtn.active = false;
		}
	},
	comfirBtnClick() {
		this.checkTheList()
	},
	checkTheList() {
		cc.audioEngine.stopMusic();
		let numlist = []
		let NodeList = []
		for (let i = 0; i < this.itemParent.children.length; i++) {
			NodeList.push(this.itemParent.children[i])
		}
		let suc = true;
		NodeList.sort(this.randomSort2)
		for (let i = 0; i < NodeList.length; i++) {
			if (NodeList[i].numberIndex != i || NodeList[i].y == this.posList[1].y) {
				NodeList[i].children[1].active = true;
				cc.audioEngine.play(this.warnMusic.clip, false, 0.8)
				this.actionMove(NodeList[i])
				suc = false;
			}
		}
		if (suc) {
			this.sahuaNode.active = true;
			cc.audioEngine.play(this.sahuaMusic.clip, false, 0.8)
			this.unschedule(this.callback);
			this.endNode.active = true
			// 游戏结束时需要调用这个方法通知系统作业完成
			onHomeworkFinish();
		} else {
			if (this.timeEnd) {
				this.timeoutNode.active = true;
				cc.audioEngine.play(this.timeoutMusic.clip, false, 0.8)
				this.unschedule(this.callback);
				this.endNode.active = true
				// 游戏结束时需要调用这个方法通知系统作业完成
				onHomeworkFinish();
			}
		}

	},
	actionMove(node) {
		let x = node.x;
		cc.tween(node)
			.to(0.1, { position: cc.v2(x - 10, node.y) })
			.to(0.1, { position: cc.v2(x + 10, node.y) })
			.to(0.1, { position: cc.v2(x - 10, node.y) })
			.to(0.1, { position: cc.v2(x + 10, node.y) })
			.to(0.1, { position: cc.v2(x, node.y) })
			.call(() => { node.children[1].active = false; })
			.start()
	},
	initBg() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;
	},

	pic1: null,
	pic2: null,
	initPic() {
		const canvas = cc.find('Canvas');
		const maxW = canvas.width * 0.7;

		this.getSprNodeByUrl(this.data.pic_url, (sprNode) => {
			const picNode1 = sprNode;
			picNode1.scale = maxW / picNode1.width;
			picNode1.baseX = picNode1.x;
			canvas.addChild(picNode1);
			this.pic1 = picNode1;

			const labelNode = new cc.Node();
			labelNode.color = cc.Color.YELLOW;
			const label = labelNode.addComponent(cc.Label);
			label.string = this.data.text;
			label.fontSize = 60;
			label.lineHeight = 60;
			label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent('cc.Label').font;
			picNode1.addChild(labelNode);
		});

		this.getSprNodeByUrl(this.data.pic_url_2, (sprNode) => {
			const picNode2 = sprNode;
			picNode2.scale = maxW / picNode2.width;
			canvas.addChild(picNode2);
			picNode2.x = canvas.width;
			picNode2.baseX = picNode2.x;
			this.pic2 = picNode2;

			const labelNode = new cc.Node();
			const label = labelNode.addComponent(cc.RichText);
			const size = 60
			label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent(cc.Label).font;
			label.string = `<outline color=#751e00 width=4><size=${size}><color=#ffffff>${this.data.text}</color></size></outline>`
			label.lineHeight = size;
			picNode2.addChild(labelNode);
		});

	},

	initIcon() {
		const iconNode = this.getSprNode('icon');
		iconNode.zIndex = 5;
		iconNode.anchorX = 1;
		iconNode.anchorY = 1;
		iconNode.parent = cc.find('Canvas');
		iconNode.x = iconNode.parent.width / 2 - 10;
		iconNode.y = iconNode.parent.height / 2 - 10;

		iconNode.on(cc.Node.EventType.TOUCH_START, () => {
			this.playAudioByUrl(this.data.audio_url);
		})
	},

	curPage: null,
	initBtn() {

		this.curPage = 0;
		const bottomPart = cc.find('Canvas/bottomPart');
		bottomPart.zIndex = 5; // 提高层级

		bottomPart.x = bottomPart.parent.width / 2;
		bottomPart.y = -bottomPart.parent.height / 2;

		const leftBtnNode = bottomPart.getChildByName('btn_left');
		//节点中添加了button组件 则可以添加click事件监听
		leftBtnNode.on('click', () => {
			if (!this._cantouch) {
				return;
			}
			if (this.curPage == 0) {
				return;
			}
			this.curPage = 0
			this.leftMove();

			// 游戏结束时需要调用这个方法通知系统作业完成
			onHomeworkFinish();

			cc.audioEngine.play(this.audioBtn.clip, false, 0.8)
		})

		const rightBtnNode = bottomPart.getChildByName('btn_right');
		//节点中添加了button组件 则可以添加click事件监听
		rightBtnNode.on('click', () => {
			if (!this._cantouch) {
				return;
			}
			if (this.curPage == 1) {
				return;
			}

			this.curPage = 1
			this.rightMove();

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

	leftMove() {
		this._cantouch = false;
		const len = this.pic1.parent.width;
		cc.tween(this.pic1)
			.to(1, { x: this.pic1.baseX }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.pic2)
			.to(1, { x: this.pic2.baseX }, { easing: 'cubicInOut' })
			.call(() => {
				this._cantouch = true;
			})
			.start();
	},

	rightMove() {
		this._cantouch = false;
		const len = this.pic1.parent.width;
		cc.tween(this.pic1)
			.to(1, { x: this.pic1.baseX - len }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.pic2)
			.to(1, { x: this.pic2.baseX - len }, { easing: 'cubicInOut' })
			.call(() => {
				this._cantouch = true;
			})
			.start();
	},
	// update (dt) {},
























	// ------------------------------------------------
	getSprNode(resName) {
		const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
		const node = new cc.Node();
		node.addComponent(cc.Sprite).spriteFrame = sf;
		return node;
	},


	getSpriteFrimeByUrl(url, cb) {
		cc.assetManager.loadRemote(url, (err, texture) => {
			// console.log(texture)

			if (cb) {
				cb(texture);
			}
		});
		// cc.assetManager.loadRemote({ url }, (err, img) => {
		// 	const spriteFrame = new cc.SpriteFrame(img)
		// 	if (cb) {
		// 		cb(spriteFrame);
		// 	}
		// })
	},

	getSprNodeByUrl(url, cb) {
		const node = new cc.Node();
		const spr = node.addComponent(cc.Sprite);
		this.getSpriteFrimeByUrl(url, (sf) => {
			spr.spriteFrame = sf;
			if (cb) {
				cb(node);
			}
		})
	},

	playAudioByUrl(audio_url, cb = null) {

		if (audio_url) {
			cc.audioEngine.stopMusic();
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				// const audioId = cc.audioEngine.play(audioClip, false, 0.8);
				cc.audioEngine.playMusic(audioClip, false);
				if (cb) {
					cc.audioEngine.setFinishCallback(audioId, () => {
						cb();
					});
				}
			});
		}
	},

	// ------------------------------------------

});
