/**
 * Created by rockyl on 2018/8/16.
 */

import { props } from "../props";
import { playSound, createSvga } from "./utils";
import ObjectPool = engine.ObjectPool;
import { getTextureByName } from "./utils";
import { showLog } from "./utils";
import { Tealeaf } from "./Tealeaf";


const MAXX = -8;
export default class GameView extends engine.Container {

	private _hasSetup;

	/**采茶叶自定义模块*/
	private teaImgSource: any;
	private tealeaf: Tealeaf;
	private teaHalfImg: engine.Image;
	private nowPercentage: any = 0;
	private progressbarBgImg: engine.Image;
	private progressbarImg: engine.Image;
	private teaFullFlagImg: engine.Image;
	private teaHalfFlagImg: engine.Image;
	private teaStarImg: engine.Image;
	private frontImg: engine.Image;
	private verseImg: engine.Image;
	private handGraspBgImg: engine.Image;
	//采茶背景层
	private pickTeaBg: engine.Container;
	//采茶进度计时器
	private pickTeaTimer: any
	//茶叶的数量进度 100/240
	private pickTeaCount: engine.Label;
	//语句
	private verseLabel: engine.TextField;
	//篮子集合
	private basketSvgaGroup: any;

	private basketLevel: any;
	//纸篮子svga
	private paperBasketSvga
	//布篮子svga
	private clothBasketSvga
	//竹篮子svga
	private bambooBasketSvga
	//木篮子svga
	private woodBasketSvga
	//+1
	private addOneSvga
	//采茶叶
	private pickTeaSvga
	//茶叶向上飞
	private teaSkyUpSvga
	//手抓去
	private handGraspSvga
	//半缺旋转
	private teaFullRotation

	private allFrames;
	/**采茶叶自定义模块*/

	//玩家
	private player: engine.Container;

	//触摸层
	private rectBg: engine.Rect;
	//npc层
	//private NpcBg: engine.Container;

	//当前分数
	private score
	//游戏状态
	private gameIng;
	//npc出身计时器
	private timer
	//倒计时计时器
	private countdownTimer: any
	//倒计时
	private countdown: number
	//当前速度
	private speed: number

	private schedule: any
	// 当前场景上面的物品
	private goodsItems = []


	constructor() {
		super();
		this.once(engine.Event.ADDED_TO_STAGE, this.setup, this);
	}

	private waterSvga
	private boomSvga
	private playerSvga
	private _touchEnabled = true
	setup() {
		if (this._hasSetup) {
			return;
		}
		this._hasSetup = true;
		this.pickTeaBg = new engine.Container();
		this.basketLevel = null;
		// let bgGroud = new engine.Image()
		// bgGroud.source = '//yun.duiba.com.cn/aurora/assets/a988c47db8d3131faad175c7c2944773392be643.png'
		// this.addChild(bgGroud);

		this.addChild(this.pickTeaBg);
		this.teaHalfImg = new engine.Image();

		this.paperBasketSvga = createSvga("采茶童-纸篮子");
		this.clothBasketSvga = createSvga("采茶童-布篮子");
		this.bambooBasketSvga = createSvga("采茶童-竹编篮");
		this.woodBasketSvga = createSvga("采茶童-木篮子");
		this.addOneSvga = createSvga("+1");
		this.pickTeaSvga = createSvga("采茶叶");

		this.teaSkyUpSvga = createSvga("茶叶向上飞");
		this.handGraspSvga = createSvga("手抓去");

		this.frontImg = new engine.Image(getTextureByName('前景'));

		this.pickTeaBg.addChild(this.paperBasketSvga);
		this.pickTeaBg.addChild(this.clothBasketSvga);
		this.pickTeaBg.addChild(this.bambooBasketSvga);
		this.pickTeaBg.addChild(this.woodBasketSvga);
		//this.pickTeaBg.addChild(this.addOneSvga);
		this.pickTeaBg.addChild(this.pickTeaSvga);
		this.pickTeaBg.addChild(this.teaSkyUpSvga);
		//this.pickTeaBg.addChild(this.handGraspSvga);
		this.basketSvgaGroup = [this.paperBasketSvga, this.clothBasketSvga, this.bambooBasketSvga, this.woodBasketSvga]

		this.progressbarBgImg = new engine.Image(getTextureByName('进度条底框'));
		this.progressbarImg = new engine.Image(getTextureByName('进度'));
		this.teaHalfFlagImg = new engine.Image(getTextureByName('茶叶进度缺'));
		this.teaFullFlagImg = new engine.Image(getTextureByName('茶叶进度满'));
		this.teaStarImg = new engine.Image(getTextureByName('小茶叶'));

		this.handGraspBgImg = new engine.Image(getTextureByName('茶叶收取底图'));
		this.verseImg = new engine.Image(getTextureByName('气泡框'));
		this.pickTeaBg.addChild(this.verseImg);


		let mask = new engine.Rect();
		mask.width = 600;
		mask.height = 50;
		mask.x = 10;
		mask.y = 0;
		mask.alpha = 1;

		this.progressbarImg.mask = mask
		showLog(this.progressbarImg.mask)

		this.addChild(this.frontImg);

		this.progressbarBgImg.addChild(this.progressbarImg);

		this.progressbarBgImg.addChild(mask);
		showLog('遮罩坐标')
		showLog(mask.x, mask.y)
		this.progressbarBgImg.addChild(this.addOneSvga);

		this.progressbarBgImg.addChild(this.handGraspBgImg);

		this.handGraspBgImg.addChild(this.handGraspSvga);

		this.progressbarBgImg.addChild(this.teaHalfFlagImg);
		this.progressbarBgImg.addChild(this.teaFullFlagImg);
		this.progressbarBgImg.addChild(this.teaStarImg);
		this.pickTeaCount = new engine.Label();
		this.progressbarBgImg.addChild(this.pickTeaCount);

		this.addChild(this.progressbarBgImg);
		this.initView();

		// setTimeout(() => {
		// 	this.setPickTeaLevel(1)
		// 	this.setTeaNum({ totalNum: 150, nowNum: 60, serverData: 1585290768011 })
		// 	//this.setTeaNum({ totalNum: 100, nowNum: 0 })
		// }, 500)
		// setTimeout(() => {
		// 	this.handGrasp();

		// 	this.setTeaNum({ totalNum: 10, nowNum: 0, serverData: 1585290768011 })

		// }, 12000)
		//playSound('采茶叶');

	}
	reset() {
		this.initView()
	}
	start() {

	}
	pause() {
		this.gameIng = false;
	}
	revive() {
		this.gameIng = true;
	}

	resume() {
		this.reset();
		this.start()
	}

	initView() {
		this.pickTeaBg.mouseEnabled = false;
		this.teaHalfImg.visible = false;
		//this.teaHalfImg.source = '';
		this.pickTeaSvga.visible = false;
		this.teaSkyUpSvga.visible = false;
		this.verseImg.visible = false;
		this.frontImg.visible = props.showFrontImg == 1;
		this.initChildrenPos()
	}
	initChildrenPos() {
		for (let i = 0; i < this.basketSvgaGroup.length; i++) {
			this.basketSvgaGroup[i].visible = false
			this.basketSvgaGroup[i].x = props.basketSvgaPos[0];
			this.basketSvgaGroup[i].y = props.basketSvgaPos[1];;
			//this.basketSvgaGroup[i].addEventListener(engine.MouseEvent.CLICK, this.showVerse, this);
		}
		let pickTeaSVGA = this.basketSvgaGroup[0];

		//console.log('总共有多少',pickTeaSVGA.children.length)
		this.allFrames = pickTeaSVGA.children.length;

		this.verseImg.x = props.versePos[0]
		this.verseImg.y = props.versePos[1]
		this.addOneSvga.x = props.addOneSvgaPos[0]
		this.addOneSvga.y = props.addOneSvgaPos[1];
		this.pickTeaSvga.x = props.pickTeaSvgaPos[0];
		this.pickTeaSvga.y = props.pickTeaSvgaPos[1];

		this.teaSkyUpSvga.x = props.teaSkyUpSvgaPos[0];
		this.teaSkyUpSvga.y = props.teaSkyUpSvgaPos[1];

		this.handGraspSvga.x = props.handGraspSvgaPos[0];
		this.handGraspSvga.y = props.handGraspSvgaPos[1];

		this.handGraspBgImg.x = props.handGraspBgImgPos[0];
		this.handGraspBgImg.y = props.handGraspBgImgPos[1];

		this.progressbarBgImg.x = props.progressbarBgImgPos[0]

		this.progressbarBgImg.y = props.progressbarBgImgPos[1]

		this.progressbarImg.x = props.progressbarImgPos[0]
		this.progressbarImg.y = props.progressbarImgPos[1]

		this.teaHalfFlagImg.x = props.teaHalfFlagImgPos[0]
		this.teaHalfFlagImg.y = props.teaHalfFlagImgPos[1]
		this.teaHalfFlagImg.anchorX = this.teaHalfFlagImg.width / 2
		this.teaHalfFlagImg.anchorY = this.teaHalfFlagImg.height / 2

		this.teaFullFlagImg.x = props.teaHalfFlagImgPos[0]
		this.teaFullFlagImg.y = props.teaHalfFlagImgPos[1]

		this.frontImg.x = props.FrontImgPos[0]
		this.frontImg.y = props.FrontImgPos[1]

		this.teaFullFlagImg.visible = false;

		this.teaStarImg.x = props.teaStarImgPos[0]
		this.teaStarImg.y = props.teaStarImgPos[1]

		this.pickTeaCount.fillColor = 'white';
		this.pickTeaCount.size = 30;
		this.pickTeaCount.text = ''

		this.pickTeaCount.x = props.pickTeaCountPos[0]
		this.pickTeaCount.y = props.pickTeaCountPos[1]

		this.pickTeaCount.height = 50;
		this.pickTeaCount.width = 200;

		this.verseLabel = new engine.TextField();
		this.verseLabel.size = props.verseLabel[2];
		this.verseLabel.text = ''
		this.verseLabel.fillColor = props.verseColor[0]
		this.verseLabel.height = props.verseLabel[1];
		this.verseLabel.width = props.verseLabel[0];
		this.verseLabel.strokeColor = props.verseColor[1]
		this.verseLabel.stroke = 0.5;

		this.verseLabel.y = 15;
		this.verseLabel['textHeight'] = 14;
		this.verseLabel.textAlign = engine.TEXT_ALIGN.CENTER;
		this.verseImg.visible = false;
		this.verseImg.addChild(this.verseLabel);

		// label.x = (width - label.width) / 2;
		// label.y = guideHole.y + guideHole.height + 50;
	}
	showVerse() {
		showLog('显示诗句')
		// if (!this._touchEnabled) {
		// 	return;
		// }
		//this._touchEnabled = false;
		this.verseImg.visible = true;
		let len = props.verses.length;
		let random = Math.floor(Math.random() * len);
		showLog('random', random)
		showLog('props.verses')
		showLog(props.verses)
		let verse = props.verses[random];
		showLog('verse', verse)
		this.verseLabel.text = verse;
		let y = this.verseImg.y
		engine.Tween.get(this.verseImg)
			.to({ alpha: 0 }, 3000).call(() => {
				this.verseImg.visible = false;
				this.verseImg.alpha = 1
			})
	};
	/*采茶叶活动*/
	//总量除以当前 小于3分之1 没有树叶  ，3分之1到3分之2一点点树叶 ，大于3分之2满树叶
	setTeaNum(TeaNums) {
		if (this.schedule) {
			showLog('清理定时器，重新设置同步')
			clearInterval(this.schedule);
		}
		let totalNum = TeaNums.totalNum;
		let nowNum = TeaNums.nowNum
		showLog('nowNum:', nowNum)
		this.getTeaPercentage(nowNum, totalNum);
		let surplus = nowNum - totalNum;
		if (surplus == 0) {
			this.gotoMaxLength();
			return;
		}
		showLog('surplus', surplus);
		let width = this.progressbarImg.width;
		let myDate = new Date();
		let nowData = myDate.getTime();
		let serverData = TeaNums.serverData;
		//前后端本身的差值
		let fbdvalue = Math.abs((nowData - serverData))
		showLog('fbdvalue', fbdvalue)
		/**/
		//设置数据校正
		// let serverData = 0;
		let dataDiff = 0;
		/**/
		//let rate = (443 - width * (1 - nowNum / totalNum))
		//已经走得
		let x = -width * (1 - (nowNum / totalNum))

		showLog('原先的X：', this.progressbarImg.x)
		showLog('比例后的X', x);
		//showLog('parseFloat(x.toFixed(3))', parseFloat(x.toFixed(5)))

		this.progressbarImg.x = parseFloat(x.toFixed(5)) + this.teaFullFlagImg.width - Math.abs(this.teaFullFlagImg.x)
		showLog('减去长款的x', this.progressbarImg.x)
		showLog('this.teaFullFlagImg.width', this.teaFullFlagImg.width)

		if (this.progressbarImg.x > (this.teaFullFlagImg.width / 2)) {
			let minus = this.teaFullFlagImg.width - Math.abs(this.teaFullFlagImg.x) - this.progressbarImg.x
			showLog('minus', minus)
			this.progressbarImg.x = this.progressbarImg.x - this.teaFullFlagImg.width / 2 + Math.abs(this.teaFullFlagImg.x)
			showLog('负段x重组', this.progressbarImg.x)
		}

		showLog('补宽的X', this.progressbarImg.x);
		showLog('this.progressbarImg.x', this.progressbarImg.x)
		let step = (this.teaFullFlagImg.width / 2 - this.progressbarImg.x) / surplus
		showLog('step', step)
		//step = parseFloat(step.toFixed(6));
		//showLog('进图条每秒比例step', step)
		let speed = props.pickTeaSpeed;
		if (!this.teaFullRotation) {
			this.teaFullRotation = engine.Tween.get(this.teaHalfFlagImg, { loop: true })
				.to({ rotation: 360 }, speed).call(() => {
					this.teaHalfFlagImg.rotation = 0;
				})
		}
		this.teaHalfFlagImg.visible = true;
		this.teaFullFlagImg.visible = !this.teaHalfFlagImg.visible
		this.addOneSvga.visible = this.teaHalfFlagImg.visible

		engine.Tween.resumeTweens(this.teaFullRotation);
		this.schedule = setInterval(() => {
			//showLog('nowNum', nowNum, 'totalNum', totalNum)
			nowNum++;
			this.addOneSvga.play(1, true);
			if (nowNum == totalNum) {
				this.gotoMaxLength();
				this.getTeaPercentage(nowNum, totalNum);
				engine.Tween.pauseTweens(this.teaFullRotation);
				//this.setTeaNum({ totalNum: 100, nowNum: 0, serverData: 1585290768011 });
				return;
			}
			if (this.progressbarImg.x < this.teaFullFlagImg.width / 2) {
				this.progressbarImg.x -= step;
			}
			this.getTeaPercentage(nowNum, totalNum);
			dataDiff += speed;
			myDate = new Date();
			nowData = myDate.getTime();
			if (Math.abs((nowData - serverData)) - dataDiff > (fbdvalue + 3000)) {
				showLog('校准数据前后数据偏差过大');
				showLog(Math.abs((nowData - serverData)) - dataDiff - (fbdvalue + 3000))
				showLog(this.schedule)
				clearInterval(this.schedule);
				engine.Tween.pauseTweens(this.teaFullRotation);
				engine.globalEvent.dispatchEvent('event-setchange-TeaNum');
				this.addOneSvga.visible = false;
				this.addOneSvga.stop();
				return;
			}
		}, speed)
	}
	getTeaPercentage(nowNum, totalNum) {
		if (nowNum > totalNum) {
			return;
		}
		this.pickTeaCount.text = nowNum + '/' + totalNum;
		let teaPercentage = 2;
		let portion = totalNum / 3
		if (nowNum < portion) {
			return;
		}
		if (nowNum < (portion * 2)) {
			teaPercentage = 1;
		}
		showLog('teaPercentage', teaPercentage)
		if (this.nowPercentage != teaPercentage) {
			showLog('状态改变')
			this.nowPercentage = teaPercentage;
			this.updateTeaPercentage(teaPercentage);
		}
	}
	//进度条达到最大长度
	gotoMaxLength() {
		showLog('达到最大长度');
		if (this.schedule) {
			clearInterval(this.schedule);
		}
		this.progressbarImg.x = this.teaFullFlagImg.width / 2
		this.teaHalfFlagImg.visible = false;
		this.teaFullFlagImg.visible = !this.teaHalfFlagImg.visible
		this.addOneSvga.visible = this.teaHalfFlagImg.visible
		this.addOneSvga.stop();
	}
	//需要更换茶叶数量皮肤
	updateTeaPercentage(teaPercentage = 0) {
		// console.log('需要更换茶叶数量皮肤')
		// console.log('this.basketLevel', this.basketLevel)
		if (!this.basketLevel)
			this.basketLevel = 0;
		let pickTeaSVGA = this.basketSvgaGroup[this.basketLevel];
		let templength = pickTeaSVGA.children.length;
		//console.log('templength',templength)
		if (this.allFrames < templength) {
			pickTeaSVGA.removeChildAt(10);
		}

		let originframes = pickTeaSVGA.children[7];
		if (!originframes) {
			return;
		}
		//按照采茶叶的多少来 设置茶叶是不是满的图片
		let teaBucketframes = JSON.parse(JSON.stringify(originframes.frames));
		//let teaNumImg = this.teaHalfImg;
		if (teaPercentage == 1) {
			this.teaHalfImg = new engine.Image(getTextureByName('茶叶-少'));
		}
		else if (teaPercentage == 2) {
			this.teaHalfImg = new engine.Image(getTextureByName('茶叶-满'));
		}
		this.teaHalfImg.visible = false;
		this.teaHalfImg['frames'] = teaBucketframes;

		//showLog('this.teaHalfImg');
		//showLog(this.teaHalfImg);
		pickTeaSVGA.addChildAt(this.teaHalfImg, 10)
	}

	setPickTeaLevel(level) {
		showLog('setPickTeaLevel', level);
		this.basketLevel = level;
		let pickTeaSVGA = this.basketSvgaGroup[level];
		pickTeaSVGA.visible = true;
		//console.log('总共有多少', pickTeaSVGA.children.length)
		//showLog('littleTea url')
		//showLog(this.teaHalfImg['_source'])
		//需要svga缓存结束
		//setTimeout(() => {
		showLog('延迟500ms')
		let originframes = pickTeaSVGA.children[7];

		//按照采茶叶的多少来 设置茶叶是不是满的图片
		this.teaHalfImg.visible = true;
		let teaBucketframes = JSON.parse(JSON.stringify(originframes.frames));
		//this.teaHalfImg = //new engine.Image(getTextureByName('茶叶-少'));
		if (this.teaHalfImg) {
			//this.teaHalfImg.source = ''
			this.teaHalfImg['frames'] = teaBucketframes;
		}
		showLog('this.teaHalfImg');
		showLog(this.teaHalfImg);
		pickTeaSVGA.addChildAt(this.teaHalfImg, 10)
		pickTeaSVGA.gotoAndPlay(1, true);
		//}, 300)
	}
	handGrasp() {
		showLog('handGrasp')
		let that = this;
		this.updateTeaPercentage(0);
		setTimeout(() => {
			//that.handGraspSvga.play(1, true);
			// this.pickTeaSvga.play(1, false);
			// this.teaSkyUpSvga.play(1, false);
			engine.Tween.get(that.handGraspSvga)
				.to({ x: props.handGraspMovePos[0], y: props.handGraspMovePos[1] }, 400).call(() => {
					showLog('this.pickTeaSvga.play')
					that.handGraspSvga.play(1, true);
					setTimeout(() => {
						that.handGraspSvga.stop()
						that.handGraspSvga.x = props.handGraspSvgaPos[0];
						that.handGraspSvga.y = props.handGraspSvgaPos[1];
					}, 600)
					that.pickTeaSvga.visible = true
					playSound('采茶叶');
					that.teaHalfImg.source = ''
					that.pickTeaSvga.play(1, false);
				})

			that.pickTeaSvga.addEventListener(engine.Event.END_FRAME, function () {
				showLog('this.teaSkyUpSvga.play')
				that.teaSkyUpSvga.visible = true
				playSound('茶叶飞起');
				that.teaSkyUpSvga.play(1, false);

			})

			that.teaSkyUpSvga.addEventListener(engine.Event.END_FRAME, function () {
				that.teaSkyUpSvga.visible = false;
				//that.updateTeaPercentage(0)
				console.log('茶叶初始化')
			})
		}, 500);
	}

	/*采茶叶活动*/
}
