const tools = require("./tools");

cc.Class({
	extends: cc.Component,

	properties: {
		picNode: {
			type: cc.Node,
			default: null
		},
		picTempNode: {
			type: cc.Node,
			default: null
		},
		leftNode: {
			type: cc.Node,
			default: null
		},
		rightNode: {
			type: cc.Node,
			default: null
		},
		checkNode: {
			type: cc.Node,
			default: null
		},
		bgNode: cc.Node,
		bgAudioNode: cc.Node,
		btnClip: cc.AudioClip,
		tipClip: cc.AudioClip,
		buttomBgs: [cc.Node]
	},

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

		const canvas = cc.find("Canvas");
		canvas.on("mousemove", function () { });
		cc.director._scene.on("mousemove", function () {
			console.log('喵喵喵')
		});
		cc.director._scene.on("thoucmove", function () {
			console.log('汪汪汪')
		});
		cc.director._scene.on("touchmove", function () {
			console.log('汪汪汪2')
		});

	},

	_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 && data.length) ? data : this.getDefaultData();
			this.data = JSON.parse(JSON.stringify(this.data))
			this.preloadItem()
		})
		//init show
		this.picNode.opacity = 0
		this.leftNode.active = false
		this.rightNode.active = false
		this.answerState = false
	},

	onEnable() {

	},

	onDisable() {

	},


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

	getDefaultData() {
		const dataJson = ' [{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/5716af983b610b43b13efbdefec93a51.png","bgAudioUrl":"http://staging-teach.cdn.ireadabc.com/303c4bbddbdbda72b2ac1997359f8aa1.mp3","rect":{"x":190,"y":0,"width":784,"height":441},"colorType":"1"},"hotZoneItemArr":[{"id":"1621330074613","index":0,"itemType":"text","fontScale":0.909375,"imgScale":1,"mapScale":0.909375,"gIdx":"0","actionData_":{"type":"text","changeOption":[["fontColor","000000"],["fontSize","50"]],"text":"I work____ this school.","audio_url":"http://staging-teach.cdn.ireadabc.com/c1aad7a9bc0ca31e97cf10abfc2bb8bf.mp3"},"rect":{"width":440.02,"height":45.47,"x":188.68,"y":102.46}},{"id":"1621330240433","index":1,"itemType":"text","fontScale":0.909375,"imgScale":1,"mapScale":0.909375,"gIdx":"1","actionData_":{"type":"text","changeOption":[["fontColor","d66a70"],["fontSize","50"]],"text":"in"},"rect":{"width":38.27,"height":45.47,"x":340.02,"y":101.38}},{"id":"1621331048944","index":2,"pic_url":"http://staging-teach.cdn.ireadabc.com/bb7f9a709e4d4d4173c5bdc9b95765d8.jpeg","itemType":"pic","fontScale":0.909375,"imgScale":0.4843462246777164,"mapScale":0.909375,"gIdx":"2","rect":{"x":-42.9,"y":24.38,"width":273.17,"height":263}}]},{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/5716af983b610b43b13efbdefec93a51.png","rect":{"x":375,"y":0,"width":1456,"height":819},"colorType":"1"},"hotZoneItemArr":[{"id":"1621331260891","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/4a98b713c3cad009e02394dde6449773.png","itemType":"pic","fontScale":1.7234375,"imgScale":0.82171581769437,"mapScale":1.7234375,"gIdx":"2","rect":{"x":380.5,"y":-2,"width":613,"height":613}},{"id":"1621331278633","index":1,"itemType":"text","fontScale":1.7234375,"imgScale":1,"mapScale":1.7234375,"gIdx":"0","actionData_":{"type":"text","changeOption":[["fontColor","#000000"],["fontSize","100"]],"text":"aaaaaaa"},"rect":{"width":709.22,"height":172.34,"x":363.39,"y":634.33}}]},{"bgItem":{"url":"http://staging-teach.cdn.ireadabc.com/5716af983b610b43b13efbdefec93a51.png","rect":{"x":375,"y":0,"width":1456,"height":819},"colorType":"1"},"hotZoneItemArr":[{"id":"1621331328218","index":0,"pic_url":"http://staging-teach.cdn.ireadabc.com/4601f56cba1a6c1178c111b2dd29225b.png","itemType":"pic","fontScale":1.7234375,"imgScale":1.4078125,"mapScale":1.7234375,"gIdx":"2","rect":{"x":262.8,"y":-4,"width":902.41,"height":901}},{"id":"1621331360035","index":1,"itemType":"text","fontScale":1.7234375,"imgScale":1,"mapScale":1.7234375,"gIdx":"0","actionData_":{"type":"text","changeOption":[["fontColor","#000000"],["fontSize","100"]],"text":"girl","audio_url":"http://staging-teach.cdn.ireadabc.com/b6a1ee625d8298a757e8d78bf50352ab.mp3"},"rect":{"width":257.42,"height":172.34,"x":572.29,"y":622.33}}]}]'
		const data = JSON.parse(dataJson);
		return data;
	},

	preloadItem() {
		this.addPreload()
		this.preload();
	},

	addPreload() {
		for (let item of this.data) {
			item.bgAudioUrl && this._audioResList.push({ url: item.bgAudioUrl })
			for (let item of item.hotZoneItemArr) {
				item.audio_url && this._audioResList.push({ url: item.audio_url })
				item.actionData_ && item.actionData_.audio_url && this._audioResList.push({ url: item.actionData_.audio_url })
			}
		}
	},

	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.initView();
		// this.initListener();
	},

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

	initView() {
		this.initBg();
		this.initPic();
	},

	initBg() {
		// const bgNode = cc.find('Canvas/bg');
		// bgNode.scale = this._mapScaleMax;
		// cc.find('Canvas/bottomPart').scale = this._mapScaleMin
	},

	initPic() {
		this.picNode.opacity = 0
		cc.Tween.stopAllByTarget(this.picNode)
		cc.tween(this.picNode).to(1, { opacity: 255 }, { easing: 'cubicInOut' }).start()
		this.curPage = 0
		if (this.data.length == 1) {
			this.leftNode.active = false
			this.rightNode.active = false
		} else {
			this.leftNode.active = false
			this.rightNode.active = true
		}
		if (this.data[0].bgItem.colorType == '1') {
			this.buttomBgs[0].active = true
			this.buttomBgs[1].active = false
			this.bgNode.color = cc.color('#b9d7f5')
		} else {
			this.buttomBgs[0].active = false
			this.buttomBgs[1].active = true
			this.bgNode.color = cc.color('#C5F4BB')
		}
		this.setContent(this.picNode, this.data[0])
	},
	curPage: null,

	onClickRight() {
		if (!this._cantouch) {
			return;
		}

		this.curPage += 1

		if (this.curPage == 1) {
			this.leftNode.active = true
			this.leftNode.scale = 1
		}

		if (this.curPage == this.data.length - 1) {
			this.rightNode.active = false
		}

		this.leftMove()

		cc.audioEngine.play(this.btnClip, false, 0.5)
	},

	onClickLeft() {
		if (!this._cantouch) {
			return;
		}
		this.curPage -= 1
		if (this.curPage == 0) {
			this.leftNode.active = false
		}

		if (this.curPage == this.data.length - 2) {
			this.rightNode.active = true
			this.rightNode.scale = 1
		}
		this.rightMove()

		cc.audioEngine.play(this.btnClip, false, 0.8)
	},

	/** 左移动 */
	leftMove() {
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width
		this.picNode.x = 0
		this.picTempNode.x = width
		this.setContent(this.picTempNode, this.data[this.curPage])
		cc.tween(this.picNode)
			.to(1, { x: -width }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.picTempNode)
			.to(1, { x: 0 }, { easing: 'cubicInOut' })
			.call(() => {
				let temp = this.picNode
				this.picNode = this.picTempNode
				this.picTempNode = temp
				this._cantouch = true;
			})
			.start();
	},

	/** 右移动 */
	rightMove() {
		this.stopAudio()
		this._cantouch = false;
		let width = cc.winSize.width
		this.picNode.x = 0
		this.picTempNode.x = -width
		this.setContent(this.picTempNode, this.data[this.curPage])
		cc.tween(this.picNode)
			.to(1, { x: width }, { easing: 'cubicInOut' })
			.start();

		cc.tween(this.picTempNode)
			.to(1, { x: 0 }, { easing: 'cubicInOut' })
			.call(() => {
				let temp = this.picNode
				this.picNode = this.picTempNode
				this.picTempNode = temp
				this._cantouch = true
			})
			.start();
	},
	stopAudio() {
		cc.systemEvent.emit('stopBgMusic')
		cc.systemEvent.emit('stopWordsMusic')
		this.answerState = false
		this.checkNode.children[0].active = false
		this.checkNode.children[1].active = true
	},

	// ------------------------------------------------
	/**设置显示区域内容 */
	setContent(picNode, data) {
		if (!data) {
			console.log('数据错误')
			return
		}
		picNode.getComponent('picNode').initWithData(data)

		let url = data.bgItem.bgAudioUrl
		if (url && url != '') {
			this.bgAudioNode.active =true
			this.bgAudioNode.getComponent('audioItem').init(url)
		} else {
			this.bgAudioNode.active = false
		}
	},

	answerState: null,

	/** 点击切换答案显示 */
	onCheckall() {
		this.answerState = !this.answerState
		if (this.answerState) {
			cc.audioEngine.playEffect(this.btnClip)
			cc.audioEngine.playEffect(this.tipClip)
		} else {
			cc.audioEngine.playEffect(this.btnClip)
			cc.systemEvent.emit('stopWordsMusic')
		}
		this.checkNode.children[0].active = this.answerState
		this.checkNode.children[1].active = !this.answerState
		cc.systemEvent.emit('changeAnswerState', this.answerState)
	}
	// ------------------------------------------
});
