import Scene from "../views/Scene";
import MyImage from "./MyImage";
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 { GTime } from "../../libs/tc/util/GTime";
import { TimeFormat } from "../../libs/tc/enum/TimeFormat";
import Panel from "../views/Panel";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import { Buried } from "../../libs/tw/util/Buried";
import ComponentBase from "../components/ComponentBase";
import GuidePanel from "../guidePanel/GuidePanel";
import { GCache } from "../../libs/tc/util/GCache";
import Loading from "../loading/Loading";
import { GetPrizeInfoData } from "../../libs/tw/data/plug/getPrizeInfo/GetPrizeInfoData";
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";

export default class MainScene extends Scene {

	public topGroup: eui.Group;
	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 bottomGroup: eui.Group;
	public addDogBtn: 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;



	/* 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=[]

	initEvents() {
		GDispatcher.addEvent(ABNetManager.ERROR, this.onError, this);
		this.addDogBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_addDogBtn, 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)
		setInterval(this.updateIncome.bind(this), 3000)
	}


	private targetDog;
	private targetCatch;

	private from;
	private to;

	private touchBegin(e){
		this.targetDog=null;
		/* console.log(e.stageX)
		console.log(e.stageY) */
		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)
				){
					//console.log("doglist_" + i)
					this.from=i
					this.targetCatch={
						x:target.x,
						y:target.y,
					}
					this.targetDog=target
					console.log(this.targetDog.canMove)
					
				}
			}
		}
		//console.log(e.stageX)
	}
	private touchMove(e){
		/* console.log(e.stageX)
		console.log(e.stageY) */
		if(this.targetDog){
			this.targetDog.x=e.stageX-(80)
			this.targetDog.y=e.stageY-(60)
		}
	}
	private touchEnd(e){
		//console.log(e)
		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.to=i
					egret.Tween.get(this.targetDog).to({x: this.dogPositions[i].x, y: this.dogPositions[i].y }, 500, egret.Ease.quartOut).call(()=>{
						if(this.locationData.indexOf(this.to)==-1){
							//移动位置
							console.log("移动位置")
							this.doLocation()
						}else{
							//合并
							//console.log("合并")

							var lvFrom;
							var lvTo;
							for(let j=0;j<this.dogData.length;j++){
								/* console.log("location:"+this.dogData[j].location)
								console.log("to:"+this.to)
								console.log("from:"+this.from) */
								console.log(this.dogData[j].location+":"+this.from)


								if(this.from==this.dogData[j].location){
									lvFrom=this.dogData[j].level;
									console.log(lvFrom)
								}
								if(this.to==this.dogData[j].location){
									lvTo=this.dogData[j].level;
									console.log(lvTo)
								}

								
							}
							if(lvFrom==lvTo){
								console.log(lvFrom)
								console.log(lvTo)
								console.log("合并有效")
								this.doMerge(1)
							}else{
								console.log("合并无效")
								egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x,y: this.targetCatch.y }, 500, egret.Ease.quartOut);
								this.targetDog=null;
							}
							
						}
						
					});
					this.targetDog=null;
				}
				return
			}
		}
		if(this.targetDog){
			/* this.targetDog.x=this.targetCatch.x
			this.targetDog.y=this.targetCatch.y */
			egret.Tween.get(this.targetDog).to({ x: this.targetCatch.x,y: this.targetCatch.y }, 500, egret.Ease.quartOut);
			this.targetDog=null;
		}
	}


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



	private addLocation

	locationData=[]

	onTap_addDogBtn() {
		this.enabled = false;

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

		NetManager.ins.getSummon((succuss) => {
			if (!succuss) {
				this.enabled = true;
				return;
			}
			NetManager.ins.getHome((succuss) => {
				this.enabled = true;
				if (!succuss) {
					return;
				}
				this.updateIndex(true)
			},  window["dailyMark"],window["activityId"])
			//alert()

			/* 
    public getHome(callback: Function, dailyMark: string,activityId){
			
			
			*/

		}, this.homeData.summonLevel, window["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;
		}

		PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, [msg], false);
	}
	removeEvents() {
		this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
		this.addDogBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_addDogBtn, this);
		GDispatcher.removeEvent(ABNetManager.ERROR, this.onError, this);
	}

	protected onSkinComplete(): void {
		super.onSkinComplete();
		NetManager.ins.getHome((succuss) => {
			if (!succuss) {
				return;
			}
			this.updateIndex()
		}, window["dailyMark"],window["activityId"])
	}

	//home数据
	homeData
	//组队数据
	teamData
	//狗狗列表输数据
	dogData

	updateIndex(state?) {
		console.log(DataManager.ins.getData(NetName.GET_HOME))
		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()
		}
	}

	doMerge(currentLevel){
		NetManager.ins.getMerge((succuss) => {
			if (!succuss) {
				return;
			}
			NetManager.ins.getHome((succuss) => {
				if (!succuss) {
					return;
				}
				this.updateIndex()
			}, window["dailyMark"],window["activityId"])
		},this.from,this.to,currentLevel,window["activityId"])
	}

	doLocation(){
		NetManager.ins.getLocation((succuss) => {
			if (!succuss) {
				return;
			}
			NetManager.ins.getHome((succuss) => {
				if (!succuss) {
					return;
				}
				this.updateIndex()
			}, window["dailyMark"],window["activityId"])
		},this.from,this.to)
	}

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

	updateAllTextFromHome() {
		if (this.homeData.maxLevel) {
			this.maxLevel = this.homeData.maxLevel;
			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() {
		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)
			}
		}
	}

	positionCatchs = []

	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++) {
			//if (this.dogData[i]) {
				this.addGold(i)
			//}
		}
	}

	addGold(i) {
		setTimeout(() => {
			this.doglists[i].addGold()
		}, 1400 * Math.random())
	}

	start(data?) {

	}

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

		this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
	}

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

	}
	private initData(): void {
	}


	private onEnterFrame(): void {

	}

}