import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import { ABNetManager } from "../../libs/tc/manager/ABNetManager";
import FriendItem from "./FriendItem";
import { NetName } from "../../libs/tw/enum/NetName";
import DogItem from "./DogItem";
import DataConversion from "./DataConversion";
import SceneCtrl from "../ctrls/sceneCtrl";
import TopLayerCtrl from "../ctrls/topLayerCtrl";
import Loading from "../loading/Loading";
export default class MainScene extends Scene {

	public bg: eui.Image;
	public topGroup: eui.Group;
	public lvText: eui.Label;
	public recordBtn: eui.Button;
	public ruleBtn: eui.Button;
	public shareBtn: eui.Button;
	public rankBtn: eui.Button;
	public doglist_0: eui.Group;
	public doglist_1: eui.Group;
	public doglist_2: eui.Group;
	public doglist_3: eui.Group;
	public doglist_4: eui.Group;
	public doglist_5: eui.Group;
	public doglist_6: eui.Group;
	public doglist_7: eui.Group;
	public doglist_8: eui.Group;
	public doglist_9: eui.Group;
	public doglist_10: eui.Group;
	public doglist_11: eui.Group;
	public bottomGroup: eui.Group;
	public recycleBtn: eui.Button;
	public mapBtn: eui.Button;
	public shopBtn: eui.Button;
	public recycleText: eui.Label;
	public refreshBtn: eui.Button;
	public taskbtn_1: eui.Button;
	public taskbtn_2: eui.Button;
	public taskbtn_3: eui.Button;
	public yd_tips: eui.Group;
	public pet: eui.Group;
	public pet_tips_1: eui.Image;
	public pet_tips_2: eui.Image;
	public pet_tips_3: eui.Image;
	public pet_tips_4: eui.Image;
	public pet_tips_3_yd_1: eui.Image;
	public pet_tips_1_yd_1: eui.Image;
	public pet_tips_2_yd_1: eui.Image;
	public pet_tips2_1_yd_1: eui.Image;
	public yd_1: eui.Group;
	public shopBtnTips: eui.Button;
	public image2: eui.Image;
	public yd_2: eui.Group;
	public image1: eui.Image;
	public yd_3: eui.Group;
	public image: eui.Image;
	public image0: eui.Image;









	public starAn: egret.MovieClip;



	/* private dogLvLists=[

	]
 */


	public get skinKey() { return 'MainScene' }
	public get groupName() { return 'main_scene' }

	private teams = [];
	private doglists = [];
	constructor(data?) {
		super(data);
		if (data) {

		}
		this.percentHeight = 100;
	}

	dogPositions = []


	Events = []

	initEvents() {
		GDispatcher.addEvent(ABNetManager.ERROR, this.onError, this);
		this.mapBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_mapBtn, this);
		this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
		this.recordBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_recordBtn, this);
		this.shopBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shopBtn, this);
		this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
		this.refreshBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_refreshBtn, this);
		this.taskbtn_1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_1, this);
		this.taskbtn_2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_2, this);
		this.taskbtn_3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_3, this);

		GDispatcher.addEvent("doSummon", this.Events["doSummon"] = this.doSummon1, this)
		GDispatcher.addEvent("doRecycle", this.Events["doRecycle"] = this.doRecycle, this)
		GDispatcher.addEvent("cancelRecycle", this.Events["cancelRecycle"] = this.cancelRecycle, this)
		GDispatcher.addEvent("mapBtnAn", this.Events["mapBtnSAn"] = this.mapBtnSAn, this)
		//展示游戏锦囊
		GDispatcher.addEvent("showGameTask", this.Events["showGameTask"] = this.showGameTask, this)

		for (let i = 0; i < 12; i++) {
			this.doglists[i] = new DogItem()
			this.doglists[i].x = -8;
			this.doglists[i].y = -40;
			this["doglist_" + i].addChild(this.doglists[i])
		}

		this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegin, this)
		this.addEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this)
		this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMove, this)
		this.TouchScrollInit()
		//this.Events["updateIncome"] = setInterval(this.updateIncome.bind(this), 3000)
	}

	removeEvents() {
		GDispatcher.removeEvent(ABNetManager.ERROR, this.onError, this);
		this.recordBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_recordBtn, this);
		this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
		this.mapBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_mapBtn, this);
		this.shopBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shopBtn, this);
		this.refreshBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_refreshBtn, this);
		this.shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
		this.taskbtn_1.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_1, this);
		this.taskbtn_2.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_2, this);
		this.taskbtn_3.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_taskbtn_3, this);

		GDispatcher.removeEvent("doSummon", this.Events["doSummon"], this)
		GDispatcher.removeEvent("doRecycle", this.Events["doRecycle"], this)
		GDispatcher.removeEvent("cancelRecycle", this.Events["cancelRecycle"], this)
		GDispatcher.removeEvent("mapBtnAn", this.Events["mapBtnSAn"], this)
		//展示游戏锦囊
		GDispatcher.removeEvent("showGameTask", this.Events["showGameTask"], this)
		this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.touchBegin, this)
		this.removeEventListener(egret.TouchEvent.TOUCH_END, this.touchEnd, this)
		this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.touchMove, this)
		clearInterval(this.Events["updateIncome"])
	}


	onTap_teamBtn() {
		console.log("ce")
		this.enabled = false;
		NetManager.ins.getTeamInfo((succuss) => {
			this.enabled = true;
			if (!succuss) {
				return;
			}
			SceneCtrl.instance.change(ModuleTypes.TEAM_SCENE)
		}, window["CFG"].activityId)
	}


	mapBtnSAn() {
		this.enabled = true;
		this["mapBtnS"].play(0)
	}


	private targetDog;
	private targetCatch;

	private from;
	private to;

	private fromId;
	private toId;

	private catchIndex

	private tips_touchBegin(e){

	}
	private tips_touchMove(e){

	}
	private tips_touchEnd(e){

	}

	private touchBegin(e) {
		/* if (!this.isCanMove()) {
			return false;
		} */

		if(this.yd_tips.visible){
			return;
		}

		this.targetDog = null;
		for (let i = 0; i < 12; i++) {
			let target = this["doglist_" + i]
			if (target.canMove) {
				if (
					e.stageX >= target.x && e.stageX <= (target.x + target.width) &&
					e.stageY >= target.y + this.y && e.stageY <= (target.y + this.y + target.height)
				) {
					this.from = i
					this.setFromId(i)
					this.targetCatch = {
						x: target.x,
						y: target.y,
					}
					this.targetDog = target
					this.catchIndex = this.getChildIndex(this.targetDog);
					this.setChildIndex(this.targetDog, 40);
				}
			}
		}
		if (this.targetDog == null) {
			this.this_TouchBegin(e)
		}

	}

	setFromId(index) {
		for (let i = 0; i < this.petData.length; i++) {
			if (index == this.petData[i].holeIndex) {
				this.fromId = this.petData[i].id
			}
		}
	}

	setToId(index) {
		for (let i = 0; i < this.petData.length; i++) {
			if (index == this.petData[i].holeIndex) {
				this.toId = this.petData[i].id
			}
		}
	}

	private bgtexture: egret.Texture;
	private music_add_dog: egret.Sound
	private music_recycle: egret.Sound
	private music_food: egret.Sound
	private music_newdog: egret.Sound

	protected async preLoadRes() {
		//加载背景并设置背景图片
		this.bgtexture = await RES.getResAsync('main_Bg_jpg');
		// console.log('载背景并设置背景图片mainscene');

		var mcJson = await RES.getResAsync('main_star_an_json');
		var mcImg = await RES.getResAsync('main_star_an_png');
		var mcImg = await RES.getResAsync('main_star_an_png');

		this.music_add_dog = await RES.getResAsync("music_add_dog_mp3");
		this.music_recycle = await RES.getResAsync("music_recycle_mp3");
		this.music_food = await RES.getResAsync("music_food_mp3");
		this.music_newdog = await RES.getResAsync("music_newdog_mp3");

		//sound.play(0,1);

		var mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);

		this.starAn = new egret.MovieClip(mcFactory.generateMovieClipData());

		return new Promise(function (resolve, reject) {
			resolve();
		});
	}

	private isHover = false

	private touchMove(e) {

		/* 	if (!this.isCanMove()) {
				return false;
			} */

		
		if(this.yd_tips.visible){
			return;
		}

		if (this.targetDog == null) {
			this.this_TouchMove(e)
		} else if (this.targetDog) {
			this.targetDog.x = e.stageX - (80)
			this.targetDog.y = e.stageY - (60) - this.y
			var _x = this.bottomGroup.x + this.recycleBtn.x - this.bottomGroup.width / 2
			var _y = this.bottomGroup.y + this.y + this.recycleBtn.y - this.bottomGroup.height / 2
			if (
				e.stageX >= _x &&
				e.stageX <= _x + this.bottomGroup.width &&
				e.stageY >= _y &&
				e.stageY <= _y + this.bottomGroup.height
			) {
				console.log("进入回收区域")
				if (!this.isHover) {
					this.isHover = true;
					this["recycleHover"].play(0)
				}

			} else {
				if (this.isHover) {
					this.isHover = false;
					this["recycleOut"].play(0)
				}
			}

		}
	}

	//执行销毁
	doRecycle(holeIndex) {
		this.music_recycle.play(0, 1)
		NetManager.ins.getRecycle((succuss) => {
			if (!succuss) {
				this.enabled = true;
				this.updateDogList(false)
				return;
			}
			this.resetData(() => {
				this.enabled = true;
				this.updateIndex()
			})

		}, this.fromId, window["CFG"].activityId)
	}



	cancelRecycle() {
		this.updateDogList(false)
	}


	private touchEnd(e) {

		/* if (!this.isCanMove()) {
			return false;
		} */

		if(this.yd_tips.visible){
			return;
		}

		if (this.targetDog == null) {
			this.this_TouchEnd(e)
		} else if (this.isHover) {
			this.isHover = false;
			this["recycleOut"].play(0)
			console.log("执行回收")

			if (this.gameData.petList.length <= 5) {
				this.showToast("场上狗狗低于6只，不能再回收了")
				//this.updateDogList(false)
				egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x, y: this.targetCatch.y }, 500, egret.Ease.quartOut).call(() => {
					this.enabled = true;
				});
			} else {
				this.openRecyclePanel(this.from)
			}

			this.addChild(this.bottomGroup)

			this.enabled = true;
			this.targetDog = null;
			return false;
		}


		for (let i = 0; i < this.dogPositions.length; i++) {
			let target = this.dogPositions[i]
			if (
				e.stageX >= target.x && e.stageX <= (target.x + target.width) &&
				e.stageY >= target.y + this.y && e.stageY <= (target.y + this.y + target.height)
			) {
				if (this.targetDog) {
					this.setChildIndex(this.targetDog, this.catchIndex);
					this.enabled = false;
					this.to = i
					this.setToId(i)
					if (this.locationData.indexOf(this.to) == -1) {
						egret.Tween.get(this.targetDog).to({ x: this.dogPositions[i].x, y: this.dogPositions[i].y }, 500).call(() => {
							//移动位置
							this.doLocation()
						})
						this.targetDog = null;
						this.addChild(this.bottomGroup)
					} else {
						var lvFrom;
						var lvTo;
						for (let j = 0; j < this.petData.length; j++) {
							if (this.from == this.petData[j].holeIndex) {
								lvFrom = this.petData[j].level;
							}
							if (this.to == this.petData[j].holeIndex) {
								lvTo = this.petData[j].level;
							}
						}
						if (lvFrom == lvTo && this.from != this.to) {
							if (lvFrom < 10 || lvTo < 10) {
								egret.Tween.get(this.targetDog).to({ x: this.dogPositions[i].x, y: this.dogPositions[i].y }, 100).call(() => {
									//合并
									console.log(lvFrom)
									console.log(lvTo)

									var x = this["doglist_" + this.from].x
									egret.Tween.get(this["doglist_" + this.to]).to({ x: x - 50 }, 150).to({ x: x }, 150).call(() => {
									})
									egret.Tween.get(this["doglist_" + this.from]).to({ x: x + 50 }, 150).to({ x: x }, 150).call(() => {
										this.doMerge(lvFrom)
									})
								})
							} else {
								this.showToast("已达到最高等级！")
								egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x, y: this.targetCatch.y }, 500, egret.Ease.quartOut).call(() => {
									this.enabled = true;
								});
							}
							this.targetDog = null;
							this.addChild(this.bottomGroup)
						} else {
							egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x, y: this.targetCatch.y }, 500, egret.Ease.quartOut).call(() => {
								this.enabled = true;
							});
							this.targetDog = null;
							this.addChild(this.bottomGroup)
						}
					}
				}
				return
			}
		}
		if (this.targetDog) {
			this.enabled = false;
			egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x, y: this.targetCatch.y }, 500, egret.Ease.quartOut).call(() => {
				this.enabled = true;
			})
			this.targetDog = null;
			this.addChild(this.bottomGroup)
		}
	}

	stageYBegin = 0
	stageYBegin2 = 0
	stageYMove = 0
	stageYEnd = 0

	moveHeight = 0
	rHeight = 0

	TouchScrollInit() {
		var scaleN = this.width / window.innerWidth;
		var stageHeight = window.innerHeight * scaleN
		this.rHeight = 1624 - stageHeight
		console.log(this.rHeight)
		//this.y=-this.rHeight;
	}

	this_TouchBegin(e) {
		//this.rHeight
		console.log("this_TouchBegin")
		console.log(e.stageY)
		this.stageYBegin = e.stageY - this.y
		this.stageYBegin2 = e.stageY
		this.moveHeight = 0;
	}

	//下滑展示【游戏锦囊】页面
	showGameTask() {
		this.enabled = false;
		var tw = egret.Tween.get(this, { onChange: this.enterFrame.bind(this) });
		tw.to({ y: -this.rHeight }, 200, egret.Ease.circOut).call(() => {
			this.enabled = true;
		});
	}

	this_TouchMove(e) {
		//this.rHeight
		console.log("this_TouchMove")
		console.log(e.stageY)
		this.stageYMove = e.stageY
		this.y = this.stageYMove - this.stageYBegin
	}

	this_TouchEnd(e) {
		//this.rHeight
		console.log("this_TouchEnd")
		console.log(e.stageY)
		this.stageYEnd = e.stageY
		if (this.y > 0) {
			// this.y = 0
			var tw = egret.Tween.get(this, { onChange: this.enterFrame.bind(this) });
			tw.to({ y: 0 }, 200, egret.Ease.circOut);
		} else if (this.y < -this.rHeight) {
			//this.y=-this.rHeight
			var tw = egret.Tween.get(this, { onChange: this.enterFrame.bind(this) });
			tw.to({ y: -this.rHeight }, 200, egret.Ease.circOut);
		}

		this.moveHeight = this.stageYBegin2 - this.stageYEnd
		console.log("this.moveHeight")
		console.log(this.moveHeight)
	}

	enterFrame() {
		/*  this.jk_box.bottom=this.y+10
		 this.shareBox.bottom=this.y */
	}

	showToast(val) {
		//console.log(val)
		TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: val });
	}


	//更新收入+增加积分
	/* updateIncome() {
		this.dogRate()
		this.foodStocks += (this.yieldRate * 3);
		this.updateAllTextFromLocalCount()
		this["foodUpdate"].play(0)
	} */



	private addLocation

	locationData = []

	onTap_addDogBtn() {

		this.music_add_dog.play(0, 1)
		this.enabled = false;
		this.doSummonCount = 0
		if (this.gameData.petList.length >= 12) {
			this.enabled = true;
			this.showToast("空间不足，请合成或拖到右下角回收")
			return
		}
		//this.doSummon(this.homeData.summonLevel)
		this.doSummon(this.indexData.summonLevel)
	}


	doSummonCount = 0

	doSummon1(level) {
		this.doSummon(level)
	}

	//召唤狗狗
	doSummon(level) {
		if (!this.enabled) {
			console.log("等待上一次接口请求完成")
			return;
		}
		if (this.gameData.petList.length >= 12) {
			this.enabled = true;
			this.showToast("空间不足，请合成或拖到右下角回收")
			return
		}
		//if (this.homeData.summonConsume <= this.foodStocks) {
		for (let i = 0; i < 12; i++) {
			if (this.locationData.indexOf(i) == -1) {
				this.addLocation = i
				break;
			}
		}
		console.log(this.addLocation)
		this.enabled = false;
		NetManager.ins.getSummon((succuss) => {
			if (!succuss) {
				this.enabled = true;
				return;
			}
			setTimeout(() => {
				this.resetData(() => {
					console.log(DataManager.ins.getData(NetName.GET_SUMMON).data)
					this.enabled = true;
					this.updateIndex(true)
				})
				console.log("召唤成功")
			}, 50)

		}, level, window["CFG"].activityId, this.addLocation)
	}



	onTap_taskbtn_1() {
		this.enabled = false;
		NetManager.ins.signSuccess((succuss) => {
			this.enabled = true;
			if (!succuss) {
				return;
			}
			this.indexData.signFlag = true;
			this.taskbtn_1.enabled = false;
		}, window["CFG"].activityId)
	}

	onTap_taskbtn_2() {
		this.enabled = false;
		NetManager.ins.reportToRead((succuss) => {
			this.enabled = true;
			if (!succuss) {
				return;
			}
			console.log("跳转页面")
		}, window["CFG"].activityId)
	}

	onTap_taskbtn_3() {
		let data = {
			shareUrl: "",//链接
			shareTitle: "",//标题
			shareContent: "",//描述
			imgUrl: "" //图片
		}
		try {
			window["anShuqiForSqWebJS"].openAppSendShareData(JSON.stringify(data));
		} catch (e) {
			this.showToast('分享插件出错')
		}
	}

	onTap_shareBtn() {
		let data = {
			shareUrl: "",//链接
			shareTitle: "",//标题
			shareContent: "",//描述
			imgUrl: "" //图片
		}
		try {
			window["anShuqiForSqWebJS"].openAppSendShareData(JSON.stringify(data));
		} catch (e) {
			this.showToast('分享插件出错')
		}
	}


	private onError(net: any, desc: any, result): void {
		console.log(desc);
		console.log(result);
		var msg: string;
		var msgArr: any = window['errorMessage'];
		if (!isNaN(desc)) {
			msg = msgArr[desc] ? msgArr[desc] : '额哦，一个未知的错误';
		} else {
			msg = desc;
		}
		var code = result.code;
		/* if (code == "0800108") {
			this.showToast("场上狗狗低于6只，不能再回收了");
		}  */
	}

	firstTipsCoun = 0

	doRefreshRewardSuccess = false;

	protected onSkinComplete(): void {


		//最大等级
		this.maxLevel = 0
		//生产速率
		this.yieldRate = 0
		//粮食库存
		this.foodStocks = 0

		this.recycleIncome = 0

		this.firstTipsCoun = 0

		this.doRefreshRewardSuccess = false;

		this.indexData = DataManager.ins.getData(NetName.GET_INDEX).data;

		super.onSkinComplete();
		this.updateIndex()
		this.doRefreshReward((success) => {
			this.doRefreshRewardSuccess = success
			this.openWinFrist(0)
		})


		this.bg.texture = this.bgtexture;


		//setTimeout(() => {
		this.addChild(this.starAn);
		this.starAn.touchEnabled = false;
		this.starAn.gotoAndPlay(0);
		this.starAn.visible = false;

		this.isHover = false;


		//}, 2000);
	}

	openWinFrist(index) {

		//开奖弹窗
		if (this.indexData.winFlag != null && index == 0) {
			if (this.indexData.winFlag == true) {
				this.openPrizePanel(this.indexData.lastRank, this.indexData.prize)
			} else {
				this.openLosePanel(this.indexData.lastRank)
			}
			this.indexData.winFlag = null
		} else if (index == 0) {
			this.openWinFrist(1)
		}

		//打开新人奖励
		if (this.indexData.accessRewardCnt && index == 1) {
			this.indexData.accessRewardCnt = null
			this.openNewUserPrizePanel(this.indexData.accessRewardCnt)
		} else if (index == 1) {
			this.openWinFrist(2)
		}

		if (this.doRefreshRewardSuccess) {
			let _data = DataManager.ins.getData(NetName.GET_REWARD).data
			if (_data.readRewardCnt > 0 && index == 2) {
				//打开阅读新赠送萌宠数量弹窗
				this.openNewPetFromReadWin(_data.readRewardCnt)
			} else if (index == 2) {
				this.openWinFrist(3)
			}
			if (_data.newInviteSuccessCnt > 0 && index == 3) {
				//打开邀请新赠送萌宠数量弹窗
				this.openNewPetFromInviteWin(_data.newInviteSuccessCnt)
			} else if (index == 3) {
				this.openWinFrist(4)
			}
		} else if (index == 2 || index == 3) {
			this.openWinFrist(4)
		}



		//打开助力成功弹窗
		if (this.indexData.helpStatus && index == 4) {
			this.indexData.helpStatus = null
			this.openJoinSuccessPanel()
		} else if (index == 4) {
			if (this.indexData.helpStatus == false) {
				this.showToast(this.indexData.helpMsg);
			}
			this.openWinFrist(5)
		}

		if (index == 5) {
			//this.updateYdTips()
		}
	}

	onTap_refreshBtn() {
		this.doRefreshReward((success) => {
			this.doRefreshRewardSuccess = success
			this.openWinFrist(0)
		})
	}

	//刷新阅读邀请任务
	doRefreshReward(callBack) {
		this.enabled = false;
		Loading.instace.show()
		NetManager.ins.refreshReward((succuss) => {
			if (!succuss) {
				Loading.instace.hide()
				this.enabled = true;
				callBack(succuss)
				return;
			}
			NetManager.ins.getRewardStatus((succuss) => {
				this.enabled = true;
				Loading.instace.hide()
				callBack(succuss)
			}, window["CFG"].activityId, DataManager.ins.getData(NetName.REFRESH_REWARD).data, () => {
				return DataManager.ins.getData(NetName.GET_REWARD).data.result == 0;
			})

		}, window["CFG"].activityId)
	}

	getQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	};

	showStarAn(position) {
		this.starAn.visible = true;
		this.starAn.x = position.x - 50;
		this.starAn.y = position.y - 70;
		this.starAn.gotoAndPlay(0);
	}

	//home数据
	indexData
	//game数据
	gameData
	//狗狗列表输数据
	petData
	//回收收益
	recycleIncome


	updateIndex(state?) {

		this.gameData = DataManager.ins.getData(NetName.GET_GAMEZONE).data;

		if (this.indexData) {
			if (this.indexData.signFlag) {
				this.taskbtn_1.enabled = false;
			} else {
				this.taskbtn_1.enabled = true;
			}
		}

		if (this.gameData) {
			this.petData = this.gameData.petList
			if (state) {
				//如果state是真，则对最后一名效果添加入场动画
				this.updateDogList(true)
			} else {
				this.updateDogList(false)
			}

			this.updateAllTextFromHome()

			this.firstTipsCoun = 2;
		}

	}

	updateIndex2(state?) {
		this.gameData = DataManager.ins.getData(NetName.GET_GAMEZONE).data;
		if (this.gameData) {

			this.petData = this.gameData.petList

			if (state) {
				//如果state是真，则对最后一名效果添加入场动画
				this.updateDogList(true)
			} else {
				this.updateDogList(false)
			}
			this.updateAllTextFromHome()
		}
	}

	isCanMove() {
		let state = true;
		if (this.petData.length == 1) {
			if (this.petData[0].level == 1) {
				state = false;
			}
		}
		return state
	}

	//合并
	doMerge(currentLevel) {
		this.enabled = false;
		NetManager.ins.getMerge((succuss) => {
			if (!succuss) {
				this.enabled = true;
				this.updateIndex()
				return;
			}
			var prize
			if (DataManager.ins.getData(NetName.GET_MERGE).data.prize) {
				prize = DataManager.ins.getData(NetName.GET_MERGE).data.prize
			} else {
				prize = null
			}
			this.resetData(() => {
				setTimeout(() => {
					this.enabled = true;
					this.updateIndex()
					this.showStarAn({ x: this.dogPositions[this.to].x, y: this.dogPositions[this.to].y })
					this.maxLevel = this.gameData.maxLevel;
					if (!localStorage.maxLevel) {
						console.log("获得一直新狗")
						console.log(this.maxLevel)
						this.openNewPetShowPanel(this.maxLevel, this.gameData.petList.length, prize)
					} else {
						if (this.maxLevel > parseInt(localStorage.maxLevel)) {
							console.log("获得一直新狗")
							this.openNewPetShowPanel(this.maxLevel, this.gameData.petList.length, prize)
						}
					}
					localStorage.maxLevel = this.maxLevel
				}, 50)
			})
		}, this.fromId, this.toId, window["CFG"].activityId)
	}

	private resetData(callBack) {
		NetManager.ins.getGameZone((success) => {
			if (!success) {
				this.enabled = true;
				return
			}
			this.gameData = DataManager.ins.getData(NetName.GET_GAMEZONE).data;
			callBack()
		}, window["CFG"].activityId)
	}

	//修改位置
	doLocation() {
		this.enabled = false;
		if (this.from == this.to) {
			this.enabled = true;
			this.updateIndex()
			return;
		}

		NetManager.ins.getLocation((succuss) => {
			if (!succuss) {
				this.enabled = true;
				this.updateIndex()
				return;
			}
			this.resetData(() => {
				setTimeout(() => {
					this.enabled = true;
					this.updateIndex()
				}, 50)
			})
		}, this.fromId, this.to, window["CFG"].activityId)
	}



	//最大等级
	maxLevel = 0
	//生产速率
	yieldRate = 0
	//粮食库存
	foodStocks = 0

	updateAllTextFromHome() {
		if (this.gameData.maxLevel) {
			this.maxLevel = this.gameData.maxLevel;
			if (this.maxLevel === 0) {
				this.lvText.text = `LV.0`
			} else {
				this.lvText.text = `LV.${this.maxLevel}${DataConversion.dogLvLists[this.maxLevel - 1]}`
			}
		}
	}

	updateAllTextFromLocalCount() {
		if (this.maxLevel === 0) {
			this.lvText.text = `LV.0`
		} else {
			this.lvText.text = `LV.${this.maxLevel}${DataConversion.dogLvLists[this.maxLevel - 1]}`
		}
	}

	updateDogList(state) {
		//将位置添加到缓存数据
		this.locationData = [];
		for (let i = 0; i < this.petData.length; i++) {
			this.locationData.push(this.petData[i].holeIndex)
		}

		//
		if (this.dogPositions.length == 12) {
			for (let i = 0; i < 12; i++) {
				this["doglist_" + i].x = this.dogPositions[i].x;
				this["doglist_" + i].y = this.dogPositions[i].y;
				this["doglist_" + i].canMove = false;
			}
		} else {
			for (let i = 0; i < 12; i++) {
				this.dogPositions.push({ x: this["doglist_" + i].x, y: this["doglist_" + i].y, width: this["doglist_" + i].width, height: this["doglist_" + i].height })
			}
		}

		for (let i = 0; i < 12; i++) {
			this.doglists[i].visible = false
		}
		for (let i = 0; i < this.petData.length; i++) {
			this["doglist_" + this.petData[i].holeIndex].canMove = true;
			this.doglists[this.petData[i].holeIndex].visible = true;
			this.doglists[this.petData[i].holeIndex].setLv(this.petData[i].level)
			this.doglists[this.petData[i].holeIndex].setRate(`${DataConversion.doConversion(this.petData[i].rate * 3)}`)
		}

		if (state) {
			this.doglists[this.addLocation].firstAn()
		}


	}

	//狗狗产量气泡
	dogRate() {
		for (let i = 0; i < 12; i++) {
			this.addGold(i)
		}
	}

	addGold(i) {
		setTimeout(() => {
			if (this.doglists[i].visible) {
				this.music_food.play(0, 1)
			}
			this.doglists[i].addGold()
		}, 1400 * Math.random())
	}

	start(data?) {

	}

	protected onLoad(): void {
		this.initUI();
	}

	private initUI(): void {
		//初始化数据
		this.initData();

	}
	private initData(): void {
	}


	private onEnterFrame(): void {

	}


	//---------------------------------------------------分隔线-----------------------------------------------------
	//图鉴
	private onTap_mapBtn(): void {
		PanelCtrl.instance.btnDelay(this.mapBtn);
		PanelCtrl.instance.show(ModuleTypes.DOG_SHOW_PANEL);
	}
	//商店
	private onTap_shopBtn(): void {
		console.log(this.indexData.foodStocks)
		console.log(this.foodStocks)
		PanelCtrl.instance.btnDelay(this.shopBtn);
		NetManager.ins.shopYuji((success) => {
			if (success) {

				PanelCtrl.instance.show(ModuleTypes.SHOP_PANEL, this.foodStocks);
			} else {

			}
		}, window["CFG"].activityId);
	}

	//我的奖品记录
	private onTap_recordBtn(): void {
		PanelCtrl.instance.btnDelay(this.recordBtn);
		window.location.href = this.gotoRecord();
	}

	//规则按钮
	private onTap_ruleBtn(): void {
		PanelCtrl.instance.btnDelay(this.ruleBtn);
		PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
	}

	winStates = []
	wins = []

	/**
	 * 打开确定回收弹窗
	 * @param holeIndex 位置
	 */
	openRecyclePanel(holeIndex) {
		console.log(6666666)
		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {
			bgType: 1, type: 4, callBack: (iscancel: boolean) => {
				if (iscancel) {//点击了closeBtn
					GDispatcher.dispatchEvent("cancelRecycle");
				} else {
					//点击确认按钮
					GDispatcher.dispatchEvent("doRecycle", holeIndex);
				}
			}
		});
	}


	/**
	 * 产生了新的宠物弹窗
	 * @param level 等级
	 * @param dogCount 舞台上的狗狗数量
	 */
	openNewPetShowPanel(level, dogCount, prize) {
		//音效
		this.music_newdog.play(0, 1)
		let doMargeData = DataManager.ins.getData(NetName.GET_MERGE)
		if (doMargeData.data.prize) {
			console.log(doMargeData.data.prize.imgUrl)
		}
		PanelCtrl.instance.show(ModuleTypes.NEWPET_PANEL, {
			prize: prize,
			lv: level,
			callBack: (iscancel: boolean) => {

			}
		});

		/* PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {
			bgType: 2, type: 7, val1: level, actData: { x: 80, y: this.height - 80 }, callBack: (iscancel: boolean) => {
				if (iscancel) {
					//点击关闭按钮，图鉴按钮放大动画
					GDispatcher.dispatchEvent("mapBtnAn");
				} else {
					PanelCtrl.instance.show(ModuleTypes.SHARE_PANEL, { level: level, dNum: dogCount });
				}
			}
		}); */
	}


	/**
	 * 打开新人奖励
	 * @param accessRewardCnt 
	 */
	openNewUserPrizePanel(accessRewardCnt) {
		console.log("打开新人奖励")
		this.openWinFrist(2)



	}


	/**
	 * 排名开奖中奖
	 * @param lastRank 排名
	 * @param prize 奖品
	 */
	openPrizePanel(lastRank, prize) {
		console.log("排名开奖中奖")
		this.openWinFrist(1)
	}

	/**
	 * 排名开奖未中奖
	 * @param lastRank 排名
	 */
	openLosePanel(lastRank) {
		console.log("排名开奖未中奖")
		this.openWinFrist(1)
	}

	/**
	 * 助力成功
	 * @param data 
	 */
	openJoinSuccessPanel() {
		console.log("助力成功")
		this.openWinFrist(5)
	}

	/**
	 * 打开阅读新赠送萌宠数量弹窗
	 * @param readRewardCnt 
	 */
	openNewPetFromReadWin(readRewardCnt) {
		console.log("打开阅读新赠送萌宠数量弹窗")
		this.openWinFrist(3)
	}

	/**
	 * 打开邀请新赠送萌宠数量弹窗
	 * @param newInviteSuccessCnt 
	 */
	openNewPetFromInviteWin(newInviteSuccessCnt) {
		console.log("打开邀请新赠送萌宠数量弹窗")
		this.openWinFrist(4)
	}


	//获取我的奖品
	private gotoRecord(): string {
		let recordUrl: string;
		let oaId: number;
		if (DataManager.ins.customCfgData) {
			oaId = DataManager.ins.customCfgData.oaId;
			recordUrl = DataManager.ins.customCfgData.recordUrl;
		} else {
			oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
			recordUrl = window['recordUrl'];
		}

		if (recordUrl.indexOf('?') != -1) {
			recordUrl += '&origins=' + oaId + '00';
		} else {
			recordUrl += '?origins=' + oaId + '00';
		}
		// recordUrl += ',' + (window['plugId'] ? window['plugId'] : 4500) + '01';

		// for(let i = 0; i < window['plugIdArr'].length; i++){
		//     recordUrl += ',' + window['plugIdArr'][i] + '01';
		// }

		return recordUrl;
	}
}