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";
export default class MainScene extends Scene {

	public bg: eui.Image;
	public topGroup: eui.Group;
	public recordBtn: eui.Button;
	public ruleBtn: eui.Button;
	public lvText: eui.Label;
	public foodCountText: eui.Label;
	public teamCountText: eui.Label;
	public yieldRateText: eui.Label;
	public team_0: eui.Group;
	public team_1: eui.Group;
	public team_2: eui.Group;
	public team_3: eui.Group;
	public team_4: eui.Group;
	public team_5: eui.Group;
	public teamBtn: eui.Rect;
	public bottomGroup: eui.Group;
	public mapBtn: eui.Button;
	public shopBtn: eui.Button;
	public addDogBtn: eui.Button;
	public recycleBtn: eui.Button;
	public recycleText: eui.Label;
	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 yd_dogMerge: eui.Group;
	public yd_bg: eui.Image;
	public rect: eui.Rect;
	public image: eui.Image;
	public yd_dogAdd: eui.Group;
	public image0: eui.Image;
	public ydDogAddBtn: eui.Rect;







	public starAn: egret.MovieClip;



	/* private dogLvLists=[

	]
 */
	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.addDogBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_addDogBtn, this);
		this.ydDogAddBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ydDogAddBtn, 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.teamBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_teamBtn, this);

		GDispatcher.addEvent("doSummon", this.Events["doSummon"] = this.doSummon, 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("mapBtnAn", this.Events["mapBtnSAn"] = this.mapBtnSAn, this)

		for (let i = 0; i < 6; i++) {
			this.teams[i] = new FriendItem()
			this.teams[i].x = 0;
			this.teams[i].y = 0;
			this["team_" + i].addChild(this.teams[i])
		}

		for (let i = 0; i < 12; i++) {
			this.doglists[i] = new DogItem()
			this.doglists[i].x = -8;
			this.doglists[i].y = -60;
			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.Events["updateIncome"] = setInterval(this.updateIncome.bind(this), 3000)
	}

	removeEvents() {
		GDispatcher.removeEvent(ABNetManager.ERROR, this.onError, this);
		this.addDogBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_addDogBtn, this);
		this.ydDogAddBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ydDogAddBtn, 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.teamBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_teamBtn, 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)
		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")
		NetManager.ins.getTeamInfo((succuss) => {
			if (!succuss) {
				return;
			}
			SceneCtrl.instance.change(ModuleTypes.TEAM_SCENE)
		})
	}


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

	onTap_ydDogAddBtn() {
		this.addDogBtn.dispatchEventWith(egret.TouchEvent.TOUCH_TAP)
		this.yd_dogAdd.visible = false;
		egret.Tween.get(this.addDogBtn).to({ scaleX: 0.9, scaleY: 0.9 }, 100).to({ scaleX: 1, scaleY: 1 }, 100).call(() => { });
	}


	private targetDog;
	private targetCatch;

	private from;
	private to;

	private catchIndex

	private touchBegin(e) {

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

		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 && e.stageY <= (target.y + target.height)
				) {
					this.from = i
					this.targetCatch = {
						x: target.x,
						y: target.y,
					}
					this.targetDog = target
					this.catchIndex = this.getChildIndex(this.targetDog);
					this.setChildIndex(this.targetDog, 40);
				}
			}
		}
	}



	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');

		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.targetDog) {
			this.yd_dogMerge.visible = false;
			this.targetDog.x = e.stageX - (80)
			this.targetDog.y = e.stageY - (60)
			var _x = this.bottomGroup.x + this.recycleBtn.x - this.bottomGroup.width / 2
			var _y = this.bottomGroup.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(location) {
		this.music_recycle.play(0, 1)
		NetManager.ins.getRecycle((succuss) => {
			if (!succuss) {
				this.enabled = true;
				return;
			}
			this.recycleIncome = DataManager.ins.getData(NetName.GET_RECYCLE).data.recycleIncome

			this.recycleText.text = DataConversion.doConversion(this.recycleIncome);
			this["recycleTextAn"].play(0)

			this.resetData(DataManager.ins.getData(NetName.GET_RECYCLE).data)
			this.enabled = true;
			this.updateIndex()
		}, location, window["CFG"].activityId)
	}

	cancelRecycle() {
		this.updateDogList(false)
	}


	private touchEnd(e) {

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

		if (this.isHover) {
			this.isHover = false;
			this["recycleOut"].play(0)
			console.log("执行回收")

			if(this.homeData.dogs.length<5){
				this.showToast("场上狗狗低于5只，不能再回收了")
				//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.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 && e.stageY <= (target.y + target.height)
			) {
				if (this.targetDog) {
					this.setChildIndex(this.targetDog, this.catchIndex);
					this.enabled = false;
					this.to = 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;
					} else {
						var lvFrom;
						var lvTo;
						for (let j = 0; j < this.dogData.length; j++) {
							if (this.from == this.dogData[j].location) {
								lvFrom = this.dogData[j].level;
							}
							if (this.to == this.dogData[j].location) {
								lvTo = this.dogData[j].level;
							}
						}
						if (lvFrom == lvTo && this.from != this.to) {
							if (lvFrom < 30 || lvTo < 30) {
								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;
						} 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;
						}
					}
				}
				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;
		}
	}

	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;
		if (this.homeData.summonConsume <= this.homeData.foodStocks) {
			this.doSummon(this.homeData.summonLevel)
		} else {
			this.openNoCreditsPanel()
		}
	}

	//召唤狗狗
	doSummon(level) {
		for (let i = 0; i < 12; i++) {
			if (this.locationData.indexOf(i) == -1) {
				this.addLocation = i
				break;
			}
		}
		console.log(this.addLocation)

		NetManager.ins.getSummon((succuss) => {
			if (!succuss) {
				return;
			}
			this.enabled = true;
			this.resetData(DataManager.ins.getData(NetName.GET_SUMMON).data)
			this.updateIndex(true)

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

	private onError(net: any, code: any): void {
		console.log(code);
		var msg: string;
		var msgArr: any = window['errorMessage'];
		if (!isNaN(code)) {
			msg = msgArr[code] ? msgArr[code] : '额哦，一个未知的错误';
		} else {
			msg = code;
		}
		console.log("")
	}

	protected onSkinComplete(): void {


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

		this.recycleIncome = 0


		super.onSkinComplete();
		this.updateIndex()
		this.openWinFrist(0)

		this.bg.texture = this.bgtexture;

		this.yd_dogMerge.visible = false;
		this.yd_dogAdd.visible = false;

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

		this.isHover = false;

		this.yd_bg.mask = this.rect;

		//}, 2000);
	}

	openWinFrist(index){
		if (!this.homeData.subscribe&&index==4) {
			this.openHowToGetPrizePanel()
		}else{
			this.openWinFrist(5)
		}

		if (this.homeData.dailyBonus&&index==0) {
			this.openPrizePanel(this.homeData.dailyBonus)
		}else{
			this.openWinFrist(1)
		}

		if (this.homeData.hasNewMember&&index==3) {
			this.openOfflineFriendPanel(this.teamData.length)
		}else{
			this.openWinFrist(4)
		}

		if (this.homeData.offlineDuration&&index==5) {
			this.openOfflinePanel(this.homeData.offlineProfit, this.homeData.offlineDuration, this.homeData.maxValidOffLineSecond)
		}else{
			this.openWinFrist(5)
		}

		if (this.homeData.newBonus&&index==2) {
			this.openNewUserPrizePanel(this.homeData.newBonus)
		}else{
			this.openWinFrist(3)
		}

		if(this.getQueryString("shareCode")&&index==1){
			NetManager.ins.joinTeam((success)=>{
				if(!success){
					return
				}
				this.openJoinSuccessPanel(DataManager.ins.getData(NetName.JOINTEAM).data)
			},this.getQueryString("shareCode"),window["CFG"].activityId)
		}else{
			this.openWinFrist(2)
		}
	}

	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 - 130;
		this.starAn.y = position.y - 120;
		this.starAn.gotoAndPlay(0);
	}

	//home数据
	homeData
	//组队数据
	teamData
	//狗狗列表输数据
	dogData
	//回收收益
	recycleIncome

	updateIndex(state?) {
		this.homeData = DataManager.ins.getData(NetName.GET_HOME).data;
		if (this.homeData) {

			this.teamData = this.homeData.team
			this.dogData = this.homeData.dogs

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

			this.updateAllTextFromHome()

			if (this.dogData.length == 2) {
				if (this.dogData[0].level == 1 && this.dogData[1].level == 1 && this.dogData[0].location < 2 && this.dogData[1].location < 2) {
					//首次达到两只等级为1的狗
					if (!localStorage.firstDogGet) {
						localStorage.firstDogGet = "1"
						this.yd_dogMerge.visible = true;
						this["ydMerge"].play(0)
						this["ydMerge"].items.forEach((item) => {
							item.tween.loop = true;
						})
					}
				}
			}


			if (this.dogData.length <= 1) {
				let ybState = 1
				if (this.dogData.length == 1) {
					if (this.dogData[0].level == 1) {
						ybState = 2
					}
				} else {
					ybState = 3
				}
				if (ybState == 2) {
					console.log("场景中只有一个等级1的狗")
					if (!localStorage.firstDogAdd1) {
						localStorage.firstDogAdd1 = "1"
						this.yd_dogAdd.visible = true;
						this["ydAddDog"].play(0)
						this["ydAddDog"].items.forEach((item) => {
							item.tween.loop = true;
						})
					}
				}
				if (ybState == 3) {
					console.log("场景中没有一只狗")
					if (!localStorage.firstDogAdd2) {
						localStorage.firstDogAdd2 = "1"
						this.yd_dogAdd.visible = true;
						this["ydAddDog"].play(0)
						this["ydAddDog"].items.forEach((item) => {
							item.tween.loop = true;
						})
					}
				}
			}
		}
	}

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

	//合并
	doMerge(currentLevel) {
		this.enabled = false;
		NetManager.ins.getMerge((succuss) => {
			if (!succuss) {
				this.enabled = true;
				return;
			}
			this.resetData(DataManager.ins.getData(NetName.GET_MERGE).data)
			this.enabled = true;
			this.updateIndex()
			console.log(this.to)
			console.log(this.dogPositions)
			this.showStarAn({ x: this.dogPositions[this.to].x, y: this.dogPositions[this.to].y })
		}, this.from, this.to, currentLevel, window["CFG"].activityId)
	}

	private resetData(Data) {
		this.homeData.dogs = Data.dogs;
		this.homeData.foodStocks = Data.foodStocks;
		this.homeData.maxLevel = Data.maxLevel;
		this.homeData.yieldRate = Data.yieldRate;
		this.homeData.summonLevel = Data.summonLevel;
		this.homeData.summonConsume = Data.summonConsume;
	}

	//修改位置
	doLocation() {
		this.enabled = false;
		NetManager.ins.getLocation((succuss) => {
			if (!succuss) {
				this.enabled = true;
				return;
			}
			this.enabled = true;
			this.resetData(DataManager.ins.getData(NetName.GET_LOCATION).data)
			this.updateIndex()
		}, this.from, this.to)
	}

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

	updateAllTextFromHome() {
		if (this.homeData.maxLevel) {
			this.maxLevel = this.homeData.maxLevel;
			if (!localStorage.maxLevel) {
				console.log("获得一直新狗")
				this.openNewDogShowPanel(this.maxLevel, this.homeData.dogs.length)
			} else {
				if (this.maxLevel > parseInt(localStorage.maxLevel)) {
					console.log("获得一直新狗")
					this.openNewDogShowPanel(this.maxLevel, this.homeData.dogs.length)
				}
			}
			localStorage.maxLevel = this.maxLevel
			if (this.maxLevel === 0) {
				this.lvText.text = `LV.0`
			} else {
				this.lvText.text = `LV.${this.maxLevel}${this.dogLvLists[this.maxLevel - 1]}`
			}
		}

		if (this.homeData.yieldRate) {
			this.yieldRate = this.homeData.yieldRate;
			this.yieldRateText.text = `+${DataConversion.doConversion(this.yieldRate)}/秒`
		}

		if (this.homeData.foodStocks) {
			this.foodStocks = this.homeData.foodStocks
			this.foodCountText.text = `${DataConversion.doConversion(this.foodStocks)}`
		}

		if (this.homeData.team) {
			this.teamCountText.text = `${this.homeData.team.length}人`
		}

		if (this.homeData.team) {
			this.teamCountText.text = `${this.homeData.team.length}人`
		}

		if (this.homeData.summonConsume && this.homeData.summonLevel) {
			this.addDogBtn.label = `LV.${this.homeData.summonLevel}消耗${DataConversion.doConversion(this.homeData.summonConsume)}狗粮`
		}
	}

	updateAllTextFromLocalCount() {
		if (this.maxLevel === 0) {
			this.lvText.text = `LV.0`
		} else {
			this.lvText.text = `LV.${this.maxLevel}${this.dogLvLists[this.maxLevel - 1]}`
		}
		//this.lvText.text = `LV.${this.maxLevel}${this.dogLvLists[this.maxLevel - 1]}`
		this.yieldRateText.text = `+${DataConversion.doConversion(this.yieldRate)}/秒`
		this.foodCountText.text = `${DataConversion.doConversion(this.foodStocks)}`
	}


	updateTeam() {
		for (let i = 0; i < 6; i++) {
			if (this.teamData[i]) {
				this.teams[i].setLoadVal((24 * 60 - this.teamData[i].remainingTime) / (24 * 60) * 100)
				this.teams[i].setState(true)
				this.teams[i].setImgUrl(this.teamData[i].avatar)
			} else {
				this.teams[i].setState(false)
			}
		}
	}




	updateDogList(state) {


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

		//
		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;
			}
		} 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.dogData.length; i++) {
			this["doglist_" + this.dogData[i].location].canMove = true;
			this.doglists[this.dogData[i].location].visible = true;
			this.doglists[this.dogData[i].location].setLv(this.dogData[i].level)
			this.doglists[this.dogData[i].location].setRate(`${DataConversion.doConversion(this.dogData[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.homeData.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 {

			}
		});
	}

	//我的奖品记录
	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 newBonus 新人奖励（狗粮）
	 */
	openNewUserPrizePanel(newBonus) {
		console.log("新人奖励（狗粮）:" + newBonus)
		this.wins[2]=PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {bgType:0, type:0, val1:newBonus});
		this.winStates[2]=true;
	}

	/**
	 * 产生了新的狗狗弹窗
	 * @param level 等级
	 * @param dogCount 舞台上的狗狗数量
	 */
	openNewDogShowPanel(level, dogCount) {

		//音效
		this.music_newdog.play(0, 1)

		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {
			bgType: 2, type: 7, val1: 3, 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 offlineProfit 离线收益
	 * @param offlineDuration 离线时间
	 * @param maxValidOffLineSecond 最大离线时间(秒)
	 */
	openOfflinePanel(offlineProfit, offlineDuration,maxValidOffLineSecond) {
		console.log("离线收益:" + offlineProfit)
		console.log("最大离线时间:" + offlineDuration)
		this.wins[5]=PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { bgType: 3, type: 8, val1: offlineDuration, val2: offlineProfit, val3: maxValidOffLineSecond });
		this.winStates[5]=true;
	}

	/**
	 * 打开离线后新增好友界面
	 * @param teamLength 队伍数量
	 */
	openOfflineFriendPanel(teamLength: number) {
		console.log("队伍数量:" + teamLength)
		this.wins[3]=PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {bgType:1, type:3, val1:teamLength, callBack:(iscancel:boolean)=>{
			if(!iscancel){
				//打开队伍界面
				this.onTap_teamBtn();
			}
		}});
		this.winStates[3]=true;
	}

	/**
	 * 打开公众号每日福利【获得狗粮】弹窗
	 * @param dailyBonus 每日福利狗粮
	 */
	openPrizePanel(dailyBonus: number) {
		console.log("每日福利狗粮:" + dailyBonus)
		 this.wins[0]=PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {bgType:2, type:6, val1:dailyBonus});
		 this.winStates[0]=true;
	}

	/**
	 * 打开公众号每日福利提示弹窗
	 */
	openHowToGetPrizePanel() {
		console.log("打开公众号每日福利提示弹窗:")
		this.wins[4]=PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, { bgType: 0, type: 2 });
		this.winStates[4]=true;
	}

	/**
	 * 打开狗粮不足弹窗
	 */
	openNoCreditsPanel() {
		console.log("狗粮不足")
		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, {
			bgType: 0, type: 1, callBack: (iscancel: boolean) => {
				if (!iscancel) {
					//调用邀请好友方法
				}
			}
		});
	}

	/**
	 * 打开确定回收弹窗
	 * @param location 位置
	 */
	openRecyclePanel(location) {
		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", location);
				}
			}
		});
	}

	/**
	 * 助力成功
	 * @param data 
	 */
	openJoinSuccessPanel(data){
		var text =`汪星卫队又扩充力量啦\n送你${data}狗粮作为感谢`;
		this.wins[1]=PanelCtrl.instance.show(ModuleTypes.JOIN_PANEL,text);
		this.winStates[1]=false;
	}
			


	//获取我的奖品
	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;
	}
}