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

cc.Class({

	extends: cc.Component,

	properties: {
	},

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

	_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 = JSON.parse(JSON.stringify(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.bgItem.url });
		this._imageResList.push(...this.data.hotZoneItemArr
			.map(data => data.pic_url)
			.map(url => { return { url: url } })
		);
	},

	addPreloadAudio() {
		this._imageResList.push(...this.data.hotZoneItemArr
			.map(data => data.audio_url)
			.map(url => { return { url: url } })
		);

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

	addPreloadAnima() {

	},

	preload() {
		const preloadArr = [
			...this._imageResList,
			...this._audioResList,
			...this._animaResList
		];
		cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {

			if (window && window["air"]) {
				cc.find('Canvas').opacity = 0;
				window.air.onCourseInScreen = (next) => {
					cc.find('Canvas').opacity = 255;
					this.loadEnd();
					next();
				}
				window.air.hideAirClassLoading();
			} else {
				this.loadEnd();
			}

			cc.debug.setDisplayStats(false);
		});
	},

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

	initData() {

	},

	async initView() {

		this.coolCatSpeakStart();

		const bg = cc.find('Canvas/bg/ImgBg');
		await this.asyncLoadSpriteByUrl(bg, this.data.bgItem.url);

		const canvas = cc.find('Canvas');
		bg.scale = Math.min((canvas.width / bg.width), (canvas.height / bg.height));

		this.itemList = [];
		this.data.hotZoneItemArr.forEach(async itemData => {
			const item = await this.createItem(itemData, bg);
			this.itemList.push(item);
		});
	},

	shakeItem(item) {
		const time = 0.05;
		cc.tween(item)
			.to(time, { angle: 10 })
			.to(time * 2, { angle: -10 })
			.to(time, { angle: 0 })
			.start();
	},

	coolCatAlreadySpeakEnd: null,
	async createItem(itemData, bg) {
		const bgScale = bg.width / this.data.bgItem.rect.width;

		const item = cc.instantiate(cc.find('item'));
		item.parent = bg;

		item.on('click', async () => {
			item.clicked = true;
			this.shakeItem(item);
			await this.asyncPlayAudioByUrl(itemData.audio_url);
			if (!this.coolCatAlreadySpeakEnd) {
				if (this.itemList.every(tmpItem => tmpItem.clicked)) {
					this.coolCatAlreadySpeakEnd = true;
					await asyncDelay(0.3);
					await this.coolCatSpeakEnd();
					onHomeworkFinish();
				}
			}
		});

		await this.asyncLoadSpriteByUrl(item, itemData.pic_url);

		item.scale = itemData.imgScale * bgScale;
		item.x = itemData.rect.x * bgScale - bg.width / 2 + item.width * item.scaleX / 2;
		item.y = bg.height / 2 - itemData.rect.y * bgScale - item.height * item.scaleY / 2;

		return item;
	},

	initListener() {

	},


	async coolCatSpeakStart(cb) {
		const cat = cc.find('Canvas/catFrame/cat');
		playDragonBoneAnimation(cat, 'begin', -1);
		await this.asyncPlayAudioByUrl(this.data.startAudio);
		playDragonBoneAnimation(cat, 'normal', -1);
	},

	async coolCatSpeakEnd() {
		const cat = cc.find('Canvas/catFrame/cat');
		playDragonBoneAnimation(cat, 'finish', -1);
		await this.asyncPlayAudioByUrl(this.data.endAudio);
		playDragonBoneAnimation(cat, 'normal', -1);
	},






















	asyncLoadSpriteByUrl(node, url) {
		return new Promise((resolve, reject) => {
			cc.loader.load({ url }, (err, img) => {
				const spriteFrame = new cc.SpriteFrame(img)
				const spr = node.getComponent(cc.Sprite);
				spr.spriteFrame = spriteFrame;
				resolve();
			});
		});
	},

	currentAudioId: null,
	stopCurrentAudio() {
		if (this.currentAudioId !== null) {
			cc.audioEngine.stop(this.currentAudioId);
			this.currentAudioId = null;
		}
	},

	asyncPlayAudioByUrl(audio_url) {
		if (!audio_url) {
			return;
		}
		return new Promise((resolve, reject) => {
			cc.assetManager.loadRemote(audio_url, (err, audioClip) => {
				this.stopCurrentAudio();
				const audioId = cc.audioEngine.play(audioClip, false, 0.8);
				cc.audioEngine.setFinishCallback(audioId, () => {
					resolve();
				});
			});
		});
	},
});
