/*
 * @Author: ls
 * @Date: 2022-04-14 19:58:47
 * @LastEditors: ls
 * @LastEditTime: 2022-04-21 19:11:18
 * @Description: file content
 * @FilePath: \ls_activity_before\assets\ls_activity_before\scene\ls_activity_before.ts
 */

import { MyCocosSceneComponent } from '../script/MyCocosSceneComponent';
import { callMiddleLayerFunction } from '../script/util';

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
	addPreloadImage() {
		// TODO 根据自己的配置预加载图片资源
		for (let index = 0; index < this.data.gameInfo.length; index++) {
			this._imageResList.push({ url: this.data.gameInfo[index].img });
		}
	}

	addPreloadAudio() {
		// TODO 根据自己的配置预加载音频资源
		this._audioResList.push({ url: this.data.audio });
	}

	addPreloadAnima() { }

	onLoadEnd() {
		// TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
		this.initData();
		this.initView();
		this.initListener();
	}

	initData() {
		// 所有全局变量 默认都是null
	}

	audioId = null;
	initView() {
		this.initBg();

		let dev = cc.find('Canvas/dev');
		for (let index = 0; index < dev.children.length; index++) {
			const element = dev.children[index];
			if (this.data.gameInfo[index].img !== '') {
				this.getSpriteFrimeByUrl(this.data.gameInfo[index].img, (sp) => {
					cc.find('img', element).getComponent(cc.Sprite).spriteFrame = sp;
				});
			}

			if (this.data.gameInfo[index].icon > 0) {
				if (cc.find('done', element)) {
					cc.find('done', element).active = true;
				}
			} else if (this.data.gameInfo[index].icon < 0) {
				if (cc.find('done', element)) {
					cc.find('done', element).active = false;
				}
			}
		}

		if (this.data.audio && this.data.audio !== '' && this.data.autoPlay) {
			let girl_ske = cc.find('Canvas/girl_ske').getComponent(dragonBones.ArmatureDisplay);
			girl_ske.playAnimation('speak', 0);
			this.audioId = this.playAudioByUrl(this.data.audio, () => {
				girl_ske.playAnimation('normal', 0);
			});
		} else {
			let girl_ske = cc.find('Canvas/girl_ske').getComponent(dragonBones.ArmatureDisplay);
			girl_ske.playAnimation('normal', 0);
		}
	}

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

	initListener() { }

	playLocalAudio(audioName) {
		const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
		return new Promise((resolve, reject) => {
			const id = cc.audioEngine.playEffect(audio.clip, false);
			cc.audioEngine.setFinishCallback(id, () => {
				resolve(id);
			});
		});
	}

	onCallBack(event, str) {
		this.playLocalAudio('btn');
		// TODO
		let info = this.data.gameInfo[Number(str)];

		callMiddleLayerFunction('NS_select_game', { gameId: info.id }, (result) => {
			console.log(JSON.stringify(result));
		});
		// callFunc('NS_select_game', { gameId: info.id });
	}

	onDestroy() {
		if (this.audioId) {
			cc.audioEngine.pause(this.audioId);
		}
	}
}
