// import frameData from './frameData';
import layoutData from './layout';
import createLayout from './createView';
// import maskCreater from './maskCreater';		//mask creater
import { gsap } from "gsap";
// import utils from '@/utils/index.js'
// import { MotionPathPlugin } from "gsap/MotionPathPlugin.js";
// import Soul 		 from './plugins/ScrollContainer';	//app scroll plugin module

class layout {
	constructor() {
		this.filterMatrix = new createjs.ColorMatrix().adjustSaturation(-200);

		// 注册路径插件
		// gsap.registerPlugin(MotionPathPlugin);
	}

	init() {


		//update btns position by viewport
		// this.updatePosByViewport();

		return this
	}

	upgrate(GAME, VIEW, ANI) {
		this.game = GAME;
		this.view = VIEW;
		this.ani = ANI;

		return this
	}

	//根据页面更新适配内容
	updatePosByViewport() {
		// console.log(this.game.scene.oHeight)
		if (this.game.oHeight <= 1181 / 2) {
			if (this.game.scene.oHeight > 1110 / 2) {
				//iphone 5 5s
				console.log('iphone 5 5s')
				this.game_score_text.y += 140;
				this.game_time_bar.y += 140;
				this.game_score_bar.y += 140;
				this.game_time_text.y += 140;

			} else {
				//suitable huawei		
				console.log('suitable huawei')
				this.game_score_text.y += 220;
				this.game_time_bar.y += 220;
				this.game_score_bar.y += 220;
				this.game_time_text.y += 220;

			}
		} else if (this.game.scene.oHeight <= 673) {
			console.log('iphone8p')
			this.game_score_text.y += 120;
			this.game_time_bar.y += 120;
			this.game_score_bar.y += 120;
			this.game_time_text.y += 120;

		} else {
			console.log('适配机型x')
		}
	}

	createBitmap(spriteSheet, name) {
		return new createjs.Sprite(spriteSheet, name);
	}

	//创建loading页
	loading(GAME) {
		this.game = GAME;
		this.loadingCacheContainer = new createjs.Container();
		this.loadingAnimation = {};
		//create layout
		for (let i in layoutData['loading']) {
			let item = layoutData['loading'][i];
			item.layout = this;
			item.game = this.game;
			item.loader = this.game.loadingLoader;
			item.container = this.game.stage.loadingContainer;
			item.cacheContainer = this.loadingCacheContainer;

			if (item.singleSprite && item.singleSprite.visible) {
				item.singleSprite.parent = this.loadingSprite;
			}

			createLayout(item);
		}

		gsap.to(this.loading_snow, { rotation: 360, ease: 'none', repeat: -1, duration: 5 })

		// 创建粒子动画
		this.createLoadingParticle();

		return this
	}

	//隐藏loading页面
	hideLoading(step = 1) {
		//create story index
		this.game.scene = 2;
		gsap.to(this.game.stage.loadingContainer, {
			alpha: 0, duration: 0.65, delay: step == 3 ? 1 : 0, onComplete: () => {
				// 将loading重置ui显示 为二次加载资源做显示
				this.changeLoadingLayout(step);
			}
		})
		gsap.to(this.game.stage.mainContainer, { alpha: 1, duration: 0.65 });
	}

	// 准备下一次loading
	changeLoadingLayout(step) {
		if (step == 1) {
			// 进度归零
			this.loading_progress_text.text = '0%';
			// 隐藏元素
			gsap.set([this.loading_start, this.loading_progress_bg, this.loading_progress_bar, this.loading_snow, this.loading_text], { alpha: 0 })
			// 显示元素
			gsap.set([this.loading_text2, this.loading_box, this.loading_light, this.loading_person], { alpha: 1 })
			gsap.set(this.loading_progress_text, { alpha: 1, y: 1260 })
			// 准备动画
			this.readyLangLoaderAni();
		} else if (step == 2) {
			// 隐藏元素
			gsap.set([this.loading_text2, this.loading_light, this.loading_person], { alpha: 0 })
			gsap.set(this.loading_progress_text, { alpha: 0 })
			// 显示元素
			gsap.set([this.loading_text3, this.loading_light2, this.loading_arrow], { alpha: 1 })
			// 如果是英文 显示英文文案
			if (this.game.langConfig.id == 3) {
				gsap.set([this.loading_text2_en, this.loading_text3], { alpha: 0 })
				gsap.set([this.loading_text3_en], { alpha: 1 })
			}
			// 准备动画
			this.readyPosterLoaderAni();
		}
	}

	// 准备语言加载动画
	readyLangLoaderAni() {
		this.langLoaderAni = [];
		let ani1 = new gsap.timeline({ repeat: -1, paused: true })
			.to([this.loading_light, this.loading_person], { alpha: 0.86, duration: 0.2 })
			.to([this.loading_light, this.loading_person], { alpha: 1, duration: 0.15 })
			.to([this.loading_light, this.loading_person], { alpha: 0.6, duration: 0.2 })
			.to([this.loading_light, this.loading_person], { alpha: 1, duration: 0.1 })

		let ani2 = gsap.to([this.loading_person, this.loading_box], { y: '+=15', yoyo: true, repeat: -1, duration: 1.5 })


		this.langLoaderAni.push(ani1, ani2)
	}

	// 播放语言加载时动画
	playLangLoaderAni() {
		this.langLoaderAni.forEach((item) => {
			item.restart();
		})
	}

	// 暂停语言加载时动画
	pauseLangLoaderAni() {
		this.langLoaderAni.forEach((item) => {
			item.pause();
		})
	}

	// 准备语言加载动画
	readyPosterLoaderAni() {
		this.posterLoaderAni = [];
		let ani1 = new gsap.timeline({ repeat: -1, paused: true })
			.to(this.loading_light2, { alpha: 0.86, duration: 0.2 })
			.to(this.loading_light2, { alpha: 1, duration: 0.15 })
			.to(this.loading_light2, { alpha: 0.6, duration: 0.2 })
			.to(this.loading_light2, { alpha: 1, duration: 0.1 })

		let ani2 = gsap.to([this.loading_box], { y: '+=15', yoyo: true, repeat: -1, duration: 1.5 })

		let ani3 = gsap.to([this.loading_arrow], { y: '+=15', scaleX: 0.95, yoyo: true, repeat: -1, duration: 1.5 })


		this.posterLoaderAni.push(ani1, ani2, ani3)
	}

	// 播放语言加载时动画
	playPosterLoaderAni() {
		this.posterLoaderAni.forEach((item) => {
			item.restart();
		})
	}

	// 暂停语言加载时动画
	pausePosterLoaderAni() {
		this.posterLoaderAni.forEach((item) => {
			item.pause();
		})
	}


	// 帧生成动画
	framePlayer(config) {
		// 图像资源
		// 容器
		// const container = new createjs.Container();

		// loader
		const loader = this.game[config.name];

		// images 
		const images = [];
		config.imgIds.forEach((item) => {
			images.push(loader.getResult(item));
		})

		// handle speed
		Object.keys(config.sprite.animations).forEach((key) => {
			// console.log('speed=', this.game.globalSpeed * 0.18)
			config.sprite.animations[key].speed = this.game.globalSpeed * 0.18;
			config.sprite.animations[key].next = 'wait'
		});

		// animation config
		const aniData = {
			images,
			frames: config.sprite.frames,
			animations: config.sprite.animations
		}

		const spriteSheet = new createjs.SpriteSheet(aniData);
		const animation = new createjs.Sprite(spriteSheet);

		// default setting
		if (config.name === 'guide' || config.name === 'wait') {
			animation.set({
				name: config.name,
				x: 390,
				y: 280 + 512,
				scaleX: 1.25,
				scaleY: 1.25,
				regX: 750 * 0.85 / 2,
				regY: 1624 * 0.85 / 2,
				alpha: 0
			})
		} else {
			animation.set({
				name: config.name,
				x: 220,
				y: 565 + 512,
				scaleX: 1,
				scaleY: 1,
				regX: 750 * 1 / 2,
				regY: 1624 * 1 / 2,
				alpha: 0
			})
		}





		return animation
	}

	// 生成海报
	createPoster(nickname = '', level = 1) {
		this.posterContainer = new createjs.Container().set({ alpha: 1, name: 'posterContainer' });
		// this.game.stage.mainContainer.addChild(this.posterContainer);

		// 海报图片
		let posterImg = this.game.posterLoader.getResult('poster_bg');
		// 海报对象
		let poster = new createjs.Bitmap(posterImg);

		// nickname
		let nt;
		if (nickname) {
			nt = this.game.vue.$Utils.cutString(nickname, 20, true);
		}
		let nicknameText = new createjs.Text(nt, "38px Helvetica, Arial, sans-serif", "#31425b").set({
			x: 375,
			y: 1086,
			textAlign: 'center'
		});

		let levelImg = this.game.posterLoader.getResult(`word_${level}`);
		let posConfig = [
			{
				x: 50,
				y: 239
			},
			{
				x: 70,
				y: 242
			},
			{
				x: 54,
				y: 243
			},
			{
				x: 57,
				y: 224
			},
			{
				x: 50,
				y: 243
			}
		]
		// 等级称号
		let levelTitle = new createjs.Bitmap(levelImg).set(
			this.game.langConfig.id == 3 ? posConfig[Number(level) - 1] : posConfig[4]
		);


		let personImg = this.game.posterLoader.getResult('person');
		// 王冰冰
		let person = new createjs.Bitmap(personImg).set({
			x: this.game.langConfig.id == 3 ? 76 : 86,
			y: this.game.langConfig.id == 3 ? 381 : 256
		});

		// 根据版本选择不同的二维码 目前全部选用微信版本二维码
		let codeName = 'qrcode';
		// switch (process.env.VUE_APP_CURRENTMODE) {
		// 	case 'ysprod':
		// 		codeName = 'ys_qrcode';
		// 		break;
		// 	case 'wbprod':
		// 		codeName = 'wb_qrcode';
		// 		break;
		// 	default:
		// 		codeName = 'qrcode';
		// 		break;
		// }
		let qrcodeImg = this.game.posterLoader.getResult(codeName);
		// 海报对象
		let qrcode = new createjs.Bitmap(qrcodeImg).set({
			x: this.game.langConfig.id == 3 ? 305 : 306,
			y: this.game.langConfig.id == 3 ? 1256 : 1275,
			scaleX: 0.34,
			scaleY: 0.34,
			width: 136,
			height: 136
		});

		let logoImg = this.game.posterLoader.getResult('logo');
		// 海报对象
		let logo = new createjs.Bitmap(logoImg).set({
			x: this.game.langConfig.id == 3 ? 341 : 341,
			y: this.game.langConfig.id == 3 ? 1482 : 1482,
		});

		// 插入container
		this.posterContainer.addChild(poster, nicknameText, qrcode, levelTitle, person, logo);

		this.posterContainer.cache(0, 0, 750, 1538);

		// easejs > 1.0.0 getCacheDataURL报错 0.8.2版本正常
		let baseUrl = this.posterContainer.cacheCanvas.toDataURL('image/png');
		// let baseUrl = this.posterContainer.getCacheDataURL();

		setTimeout(() => {
			this.destroyPosterCreater();
		}, 1000);

		return baseUrl
	}

	// 销毁海报生成器
	destroyPosterCreater() {
		this.posterContainer.uncache();
		this.posterContainer.removeAllChildren();
		this.game.stage.mainContainer.removeChild(this.posterContainer);
		this.posterContainer = null;
	}

	// index 粒子制造机
	createParticle() {

		// 容器
		// const loadingContainer = this.game.stage.loadingContainer;

		// loader
		const loader = this.game.vue.$beforeLoader;

		// sprite image
		const spriteImg = loader.getResult('snowSprite');


		const container = new createjs.Container();


		const aniData = {
			images: [spriteImg],
			frames: [
				[1, 1, 77, 82, 0, 0, 0],
				[1, 85, 57, 55, 0, 0, 0],
				[1, 142, 46, 45, 0, 0, 0],
				[49, 142, 15, 15, 0, 0, 0],
				[60, 85, 8, 12, 0, 0, 0],
				[60, 99, 6, 6, 0, 0, 0]
			],
			animations: {
				"snow-1": { "frames": [0] },
				"snow-2": { "frames": [1] },
				"snow-3": { "frames": [2] },
				"snow-4": { "frames": [3] },
				"snow-5": { "frames": [4] },
				"snow-6": { "frames": [3] },
				"snow-7": { "frames": [4] },
				"snow-8": { "frames": [2] },
				"snow-9": { "frames": [3] },
				"snow-10": { "frames": [1] },
			}
		}

		const spriteSheet = new createjs.SpriteSheet(aniData);

		const arr = [];
		for (let i = 0; i < (window.deviceInfo.system == 'IOS' ? 50 : 50); i++) {
			const scale = Math.random() * 0.35 + 0.5;
			const name = `snow-${this.game.vue.$Utils.rangeRandom(1, 10)}`;
			const sprite = this.createBitmap(spriteSheet, name).set({
				x: Math.random() * 750 - 30,
				y: Math.random() * 1300,
				ox: Math.random() * 750,
				oy: -50,
				// regX:14,
				// regY:14,
				scaleX: scale,
				scaleY: scale,
				speedX: (Math.random() > 0.5 ? 1 : -1) * (Math.random() * 0.5 + 0.25),
				speedY: Math.random() * 1 + 1,
				speedR: Math.random() * 0.5 + 0.5,
				alpha: Math.random() * 0.3 + 0.5,
			})

			arr.push(sprite)
		}
		// const mask = new createjs.Shape().setTransform(0, 0, 1, 1);
		// mask.graphics.f('#000000').drawRoundRect(0, 0, 750, 1300, 0).es();
		// contianer.mask = mask;
		// contianer.compositeOperation = 'darker';
		// arr.push(mask)
		container.children = arr;

		this.prarticleContainer = container;
		this.game.stage.mainContainer.addChild(container);
		return container
	}


	// loading 粒子制造机
	createLoadingParticle() {
		const container = new createjs.Container();

		const arr = [];
		for (let i = 0; i < (window.deviceInfo.system == 'IOS' ? 200 : 250); i++) {
			const scale = Math.random() * 0.35 + 0.5;
			const name = `snow_${this.game.utils.rangeRandom(1, 20)}`;
			const sprite = this.createBitmap(this.loadingSprite.spriteSheet, name).set({
				x: Math.random() * 750 - 30,
				y: Math.random() * 1624,
				ox: Math.random() * 750,
				oy: -100,
				// regX:14,
				// regY:14,
				scaleX: scale,
				scaleY: scale,
				speedX: (Math.random() > 0.5 ? 1 : -1) * (Math.random() * 0.25 + 0.25),
				speedY: Math.random() * 1 + 0.5,
				alpha: Math.random() * 0.3 + 0.5
			})

			arr.push(sprite)
		}
		// const mask = new createjs.Shape().setTransform(0, 0, 1, 1);
		// mask.graphics.f('#000000').drawRoundRect(0, 0, 750, 1300, 0).es();
		// contianer.mask = mask;
		// contianer.compositeOperation = 'darker';
		// arr.push(mask)
		container.children = arr;

		this.loadingPrarticleContainer = container;
		this.game.stage.loadingContainer.addChild(container);
		return container
	}

	//粒子动画更新
	update() {
		if (!this.game) return
		if (this.game.scene == 1 && this.loadingPrarticleContainer) {
			if (this.loadingPrarticleContainer.alpha == 0) {
				// console.log('2=>1')
				this.loadingPrarticleContainer.alpha = 1;
			}
			if (this.prarticleContainer && this.prarticleContainer.alpha == 1) {
				this.prarticleContainer.alpha = 0;
			}
			this.loadingPrarticleContainer.children.forEach((item, index) => {

				if (item.x < -30 || item.x > 800 || item.y > 1624) {
					item.y = item.oy;
					item.x = item.ox;
				}
				item.x += item.speedX
				item.y += item.speedY

			})
		}
		if (this.game.scene == 2 && this.prarticleContainer) {
			if (this.prarticleContainer.alpha == 0) {
				// console.log('1=>2')
				this.prarticleContainer.alpha = 1;
			}

			if (this.loadingPrarticleContainer.alpha == 1) {
				this.loadingPrarticleContainer.alpha = 0;
			}			//题目一 粒子运动
			this.prarticleContainer.children.forEach((item, index) => {

				if (item.x < -30 || item.x > 800 || item.y > 1400) {
					item.y = item.oy;
					item.x = item.ox;
					item.rotation = 0;
				}
				item.x += item.speedX * this.game.globalSpeed
				item.y += item.speedY * this.game.globalSpeed
				item.rotation += item.speedR * this.game.globalSpeed

			})
		}

	}
}

module.exports = layout;