import { _decorator, instantiate, Node, Prefab, Size, Tween, tween, UITransform, Vec2, Vec3 ,Animation, EventTouch, Button, sp, Enum, Label, Toggle, Sprite, SpriteFrame, v3, utils, ProgressBar} from 'cc';
import { BaseView } from '../../../framework/layer/BaseView';
import { Framework } from '../../../framework/Framework';
import { FrameworkConf } from '../../../framework/config/FrameworkConf';
import { AudioID } from '../../../framework/config/AudioConf';
import { AsyncQueue, NextFunction } from '../../../framework/queue/AsyncQueue';
import { Hero } from './node/Hero';
import { Enemy } from './node/Enemy';
import { Hurt } from './node/Hurt';
import { BattleNodeBase } from './node/BattleNodeBase';

import { BattleControl } from './control/BattleControl';
import { BattleUtil } from './data/BattleUtil';
import { BattleEventManager } from './base/BattleEventManager';
import { BattleEventData_EnemyBorn, BattleEventData_EnemyBuff, BattleEventData_EnemyDie, BattleEventData_EnemyHurt, BattleEventData_EnemyMove, BattleEventData_HeroAction, BattleEventData_HeroAttack, BattleEventData_Over, BattleEventTarget, BattleEventType, EnemyActionType, TowerUUID } from './base/BattleEventUtil';
import { MapConf } from './conf/MapConf';
import { isValid } from 'cc';
import { HeroDataPool, HeroRaceSacle } from './data/HeroData';
import { StringUtil } from '../../../framework/util/StringUtil';
import { MaterialUtil } from '../../../framework/util/MaterialUtil';
import { BattlesConf } from './conf/BattlesConf';
import { GameEvent } from '../../data/GameEvent';
import { LoginManager, LoginMgr } from '../../common/LoginManager';
import { MailManager } from '../../manager/MailManager';
import { ViewID } from '../../../framework/config/LayerConf';
import { MailData } from '../../data/MailData';
import { RoleManager } from '../../manager/RoleManager';
import { RoleData } from '../../data/RoleData';
import { BattleData, BattleLayoutPos, BattleLayoutScale, BattleOptsBase, BattleOptsKill, BattleOptsMerge, BattleOptsMove, BattleOptsNew, BattleOptsRemove, BattleOptsType } from '../../data/BattleData';
import { BattleManager } from '../../manager/BattleManager';
import { UserData } from '../../data/UserData';
import { ResultUI } from './node/ResultUI';
import { ChangeChapter } from './node/ChangeChapter';
import { RewardChapter } from './node/RewardChapter';
import { FightRole } from '../../common/InterfaceAddEnum';

//地图比例尺 1:70
let mapScale = 72;
let basePoint = {x:-325,y:-70}
let baseOffset = {x:0,y:0}

//地图格子转坐标
let MapDataPosToView = (x:number,y:number) => {
	let XX = (x+baseOffset.x) * mapScale + basePoint.x;
	let YY = (y+baseOffset.y) * mapScale + basePoint.y;
	return new Vec3(XX, YY, 0);
	//return new Vec3(x * mapScale + basePoint.x, y * mapScale + basePoint.y, 0);
}

//地图速度转换
let MapDataSpeedToView = (x:number,y:number) => {
	let XX = x * mapScale * BattleUtil.FrameRate;
	let YY = y * mapScale * BattleUtil.FrameRate;
	return new Vec2(XX, YY,);
	//return new Vec3(x * mapScale + basePoint.x, y * mapScale + basePoint.y, 0);
}

const { ccclass, property } = _decorator;

//可操作格子:背包格子和战斗格子
export interface PosData {
	//格子节点
	node: Node,
	//格子上的英雄
	hero: Node,
	//格子是否锁
	bLock: boolean,
	//格子下标
	posIndex: number,
	pos: Vec3,
	//地图编号
	posNumber: number
}


@ccclass('TowerUI')
export class TowerUI extends BaseView {


	@property({ type: Sprite, tooltip: "地图" })
	mapSprite: Sprite = null;
	@property({ type: Label, tooltip: "地图名字" })
	mapName: Label = null;

	@property({ type: Node, tooltip: "攻击位" })
	attackNode: Node = null;
	@property({ type: Node, tooltip: "背包位" })
	bagNode: Node = null;
	@property({ type: Node, tooltip: "减血数字根节点" })
	hurtNode: Node = null;
	// 攻击位
	attackPosList: PosData[] = [];
	//根据posID获取做的索引
	attackPosMap: Map<number,PosData> = new Map();
	//背包位
	bagPosList: PosData[] = [];

	heroList: Node[] = [];
	@property({type:[Node],tooltip:"升级效果"})
	levelUpEffect:Node[] = []

	@property({ type: [Prefab], tooltip: "敌人" })
	ememyModelList: Prefab[] = [];
	enemyPool: Map<number,Node[]> =  new Map();
	enemyMap: Map<number,Node> = new Map(); 
	enemyWaitTime: number = 0;

	@property({ type: [Prefab], tooltip: "受伤数字" })
	hurtModelList: Prefab[] = [];
	hurtPool: Node[] = [];
	hurtList: Node[] = [];

	@property({ type:Node, tooltip: "所有角色根节点" })
	roleNode: Node = null;

	@property({ type:Node, tooltip: "攻击范围" })
	radiusNode: Node = null;

	@property({ type:[Node], tooltip: "统计节点" })
	countList: Node[] = [];
	@property({ type:[Node], tooltip: "boss节点" })
	bossList: Node[] = [];
	@property({ type: Label, tooltip: "精力统计" })
	powerLabel: Label = null;

	@property({ type: ProgressBar, tooltip: "关卡进度" })
	battlesProgressBar: ProgressBar = null;
	@property({ type: [Label], tooltip: "当前管卡展示" })
	levelValue: Label[] = []

	@property({ type: Node, tooltip: "结算" })
	resultNode: Node = null;

	@property({ type: Node, tooltip: "章节切换" })
	changeChapterNode: Node = null;

	@property({ type: Node, tooltip: "章节奖励" })
	rewardChapterNode: Node = null;

	//关卡id
	battlesID: number = 1;

	bStart = false;
	// waitTime = 5;
	touchStart: Node = null;
	//记录连击
	touchEndIndex = -1;
	touchEndTime = 0;
	gameTime = 0;

	//当前精力
	private powerCur = 180;
	//最大精力
	private powerMax = 180

	//伤害统计  key:typeID value:伤害值
	private damageCountData:Map<number,number> = new Map();
	private damageUpdateTime = 0;

	private bossIndexMap:Map<number,number> = new Map();

	battleControl: BattleControl = null;
	//当前动画下标
	levelUpEffectIndex = 0;
	//是否自动合成
	isAutoMerge = false;
	//英雄处理-------
	//英雄模型加载数量
	loadHeroModelNum: number = 0;
	//英雄模型加载数量上限
	loadHeroModelNumMax: number = -1;
	heroModelMap:Map<number,Prefab> = new Map();
	heroPool: Map<number,Node[]> = new Map();
	//出战角色
	fightRole:FightRole = [0,0,0,0]
	//锁定格子
	lockBagPosNumber = 6;
	lockAttackPosNumber = 8;

	//操作指令集  记录下来发给服务器
	operateList:Array<BattleOptsBase> = [];

	//战斗结束动画是否回调
	bBattleOverAnimBack:boolean = false;
	//战斗结束消息是否回调
	bBattleOverMessageBack:boolean = false;

	protected onLoad() {
		super.onLoad();
		this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
		this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
		this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
		this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
		for (let i = 0; i < this.levelUpEffect.length; i++) {
		    this.levelUpEffect[i].getComponent(sp.Skeleton).setCompleteListener(()=>{
				this.levelUpEffect[i].active = false;
			})
		}
		
		
		this.battleControl = BattleControl.GetInstance()
		BattleEventManager.instance.addEvent(BattleEventTarget.Update, this.updateDataEvent.bind(this), TowerUUID);

		Framework.event.addEvent(GameEvent.BossUpdate, this.bossUpdate.bind(this),this)
		
		
		this.initPool()
	}

	protected onDestroy() {
		BattleEventManager.instance.removeEvent(TowerUUID)
	}

	protected update(dt: number): void {
		this.updateSiblingIndex()
		if(this.bStart){


			this.gameTime += dt;
			let nowFrame = Math.floor(this.gameTime/BattleUtil.FrameTime)
			if(nowFrame > this.battleControl.map.curTurn){

				//
				while(nowFrame > this.battleControl.map.curTurn+1){
					//需要移动的对象做瞬时计算  //目前只有敌人,以后会有子弹或者其他会移动的
					this.enemyMap.forEach(element => {
						element.getComponent(Enemy).battleUpdate(BattleUtil.FrameTime)
					});
					this.battleControl.update();
					if(this.battleControl.isBattleEnd){
						break;
					}

				}

				this.enemyMap.forEach(element => {
					element.getComponent(Enemy).battleUpdate(BattleUtil.FrameTime)
				});
				this.battleControl.update();
			}

			this.damageUpdateTime += dt;
			if(this.damageUpdateTime > 0.1){
				this.damageUpdateTime = 0;
				this.updateDamageCount()
			}
			
		}
		else{
			// if(this.waitTime > 0){
			// 	this.waitTime -= dt;
			// }
			// else{
			// 	this.bStart = true;
			// }
		}

		if(this.touchEndTime > 0){
			this.touchEndTime -= dt;
			if(this.touchEndTime <= 0){
				this.touchEndIndex = -1;
			}
		}
	}


	private updateDataEvent(event){
		if(this.battleControl.isBattleEnd && event.eventType!=BattleEventType.Over){
			console.log("结束")
			return
		} 
		switch(event.eventType){
			case BattleEventType.EnemyBorn:{
				let enemyData = event as BattleEventData_EnemyBorn;
				this.addEnemy(enemyData);
				break;
			}
			case BattleEventType.EnemyMove:{
				let enemyData = event as BattleEventData_EnemyMove;
				// console.log("移动",enemyData.ID,enemyData.speedVector.x,enemyData.speedVector.y)
				if(this.enemyMap.has(enemyData.ID)){
					let enemy = this.enemyMap.get(enemyData.ID);
					enemy.getComponent(Enemy).speedVector = MapDataSpeedToView(enemyData.speedVector.x, enemyData.speedVector.y);
				}
				break;
			}
			case BattleEventType.EnemyHurt:{
				let enemyData = event as BattleEventData_EnemyHurt;
				//console.log("移动",enemyData.ID,enemyData.hurt,enemyData.status)
				if(this.enemyMap.has(enemyData.targetID)){
					let enemy = this.enemyMap.get(enemyData.targetID);
					enemy.getComponent(Enemy).hurt(enemyData.hurt);
					this.addHurt(enemy.position,enemyData.hurt)
				}

				this.setDamageCount(enemyData.typeID,enemyData.hurt)
				break;
			}
			case BattleEventType.EnemyDie:{
				// console.log("死亡",event)
				let enemyData = event as BattleEventData_EnemyDie;

				if(this.enemyMap.has(enemyData.ID)){
					let enemy = this.enemyMap.get(enemyData.ID);
					enemy.getComponent(Enemy).die(()=>{
							this.enemyMap.delete(enemyData.ID);
							let typeID = enemy.getComponent(Enemy).typeID
							if(this.enemyPool.has(typeID)){
								let pool = this.enemyPool.get(typeID);
								pool.push(enemy);
							}
							else {
								this.enemyPool.set(typeID,[enemy]);
							}
							
						}
					);
				}
				//记录击杀敌人的操作
				let otps:BattleOptsKill = {
					count:1,
					type:BattleOptsType.Kill,
					typeID:enemyData.typeID
				}
				this.operateList.push(otps);
				break;
			}
			case BattleEventType.EnemyBuff:{
				let enemyData = event as BattleEventData_EnemyBuff;
				if(this.enemyMap.has(enemyData.ID)){
					let enemy = this.enemyMap.get(enemyData.ID);
					//enemy.getComponent(Enemy).addbuff(enemyData.buff);
				}
				break;
			}
			case BattleEventType.HeroAction:{
				// console.log("攻击动作",event)
				let attackData = event as BattleEventData_HeroAction;
				if(this.attackPosMap.has(attackData.posID)){
					let posData = this.attackPosMap.get(attackData.posID);
					let enemy = this.enemyMap.get(attackData.targetID);
					if( posData && posData.hero){
						let hero = posData.hero.getComponent(Hero);
						if(enemy){
							hero.attack(enemy)
							// enemy.getComponent(Enemy).hurt(attackData.hurt);
							// this.addHurt(enemy.position,attackData.hurt)
						}
						else{
							hero.stand()
						}
						// this.setDamageCount(hero.typeID,attackData.hurt)
					}
				}
				break;
			}

			case BattleEventType.HeroAttack:{
				// console.log("攻击",event)
				let attackData = event as BattleEventData_HeroAttack;
				if(this.attackPosMap.has(attackData.posID)){
					let posData = this.attackPosMap.get(attackData.posID);
					let enemy = this.enemyMap.get(attackData.targetID);
					if( posData && posData.hero){
						let hero = posData.hero.getComponent(Hero);
						if(enemy){
							// hero.attack(enemy)
							enemy.getComponent(Enemy).hurt(attackData.hurt);
							this.addHurt(enemy.position,attackData.hurt)
							this.setDamageCount(hero.typeID,attackData.hurt)
						}
						// else{
						// 	hero.stand()
						// }
					}
				}
				break;
			}
			case BattleEventType.Over:{
				let attackData = event as BattleEventData_Over;
				this.attackPosMap.forEach((posData, posID) => {
					if(posData.hero){
						posData.hero.getComponent(Hero).stand()
					}
				})
				this.enemyMap.forEach((enemy, enemyID) => {
					enemy.getComponent(Enemy).stand()
				})
					
				let winStr = attackData.bWin ? "胜利" : "失败";
				this.touchCancel();
				console.log(winStr)
				this.bBattleOverAnimBack = false
				this.bBattleOverMessageBack = false
				
				let battlesConf = BattlesConf.data[this.battlesID];
				if(attackData.bWin &&(this.battlesID==battlesConf.BossProcess)){
					this.changeChapterNode.getComponent(ChangeChapter).show(()=>{
						this.bBattleOverAnimBack = true
						if(this.bBattleOverMessageBack){
							this.restartBattle(this.battlesID)
						}
					});
				}
				else{
					this.resultNode.getComponent(ResultUI).show(attackData.bWin,()=>{
						this.bBattleOverAnimBack = true
						if(this.bBattleOverMessageBack){
							this.restartBattle(this.battlesID)
						}
					})
				}
		

				let layout = {}
				for(let index = 0; index < this.bagPosList.length; index++){
					let posData = this.bagPosList[index]
					let key = BattleLayoutPos[index]
					layout[key] = 0
					if(posData.hero){
						let heroData = posData.hero.getComponent(Hero)
						let value = heroData.level + heroData.raceID *BattleLayoutScale
						if(key){
							layout[key] = value
						}
					}
					
				}

				//战场占位数量跟背包一样
				for(let index = 0; index < BattleUtil.BagListSize; index++){
					let posData = this.attackPosList[index]
					let key = BattleLayoutPos[index+BattleUtil.BagListSize]
					if(key){
						if(posData && posData.hero){
							let heroData = posData.hero.getComponent(Hero)
							let value = heroData.level + heroData.raceID *BattleLayoutScale
							layout[key] = value
						}
						else{
							layout[key] = 0
						}
					}
				}

				BattleManager.sendBattleDuplicateMsg(this.battlesID,attackData.bWin,layout,this.operateList,()=>{
					if(attackData.bWin)
						if(this.battlesID == 20){
							
						}
						else{
							this.battlesID++
						}
					else{
						if(this.battlesID%5 != 1){
							this.battlesID--
						}
					}


					this.bBattleOverMessageBack = true
					if(this.bBattleOverAnimBack){
						this.restartBattle(this.battlesID)
					}
				},()=>{
					this.bBattleOverMessageBack = true
					if(this.bBattleOverAnimBack){
						this.restartBattle(this.battlesID)
					}
				})

				
				
				
				break;
			}
		}

	}
	onTouchStart(event: EventTouch) {
		if (this.touchStart) {
			this.resetHeroPos(this.touchStart)
		}
		// 获取触点对应节点

		let posData = this.getItemBaseByPosition(event.getLocation());
		if(posData && posData.hero){
			let hero = posData.hero.getComponent(Hero);
			if(hero.isLock){
				return;
			}
			Framework.audio.playEffect(AudioID.Click);
			this.touchStart = posData.hero;
			hero.stand() 
			this.touchStart.setSiblingIndex(30);
			let index = posData.posIndex - BattleUtil.BagListSize
			if(index >= 0){
				this.battleControl.removeHeroInPos(index)
			}
		}
		
	}
	// 触摸移动
	onTouchMove(event: EventTouch) {
		if (this.touchStart ) {
			this.touchStart .setPosition(this.roleNode.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(event.getUILocation().x, event.getUILocation().y)))
			let posData = this.getItemBaseByPosition(event.getLocation());
			if(posData&&(posData.posIndex >= BattleUtil.BagListSize)){
				this.radiusNode.position = v3(this.touchStart.position.x,this.touchStart.position.y);
				this.radiusNode.active = true;
				this.setRadius(this.touchStart.getComponent(Hero).radius)
			}
			else{
				this.radiusNode.active = false;
			
			}
		}
		else{
			this.radiusNode.active = false;
		}
	}
	onTouchEnd(event: EventTouch) {
		this.radiusNode.active = false;
		if (this.touchStart) {
			let posData = this.getItemBaseByPosition(event.getLocation());
			let touchEnd:Node = null
			if(posData){
				if(posData.hero == this.touchStart){
					if(this.touchEndIndex == posData.posIndex){
						this.touchEndIndex = -1
						if(posData.posIndex < BattleUtil.BagListSize){
							this.removeHeroPos(this.touchStart,true)
							this.touchStart = null;
							return;
						}
					}
					else{
						this.touchEndIndex = posData.posIndex
						this.touchEndTime = 1
					}
				}
				else{
					if(posData.hero){
						let hero = posData.hero.getComponent(Hero);
						if(hero && hero.isLock){
							this.resetHeroPos(this.touchStart)
							this.touchStart = null;
							return;
						}
					}
					
					touchEnd = posData.hero;
					this.touchEndIndex = -1
				}
			}
			else{
				this.resetHeroPos(this.touchStart)
				this.touchStart = null;
				this.touchEndIndex = -1
				return 
			}
			if(touchEnd){
				let endHero = touchEnd.getComponent(Hero)
				let startHero = this.touchStart.getComponent(Hero)
				if(endHero.typeID == startHero.typeID && endHero.level == startHero.level){
					this.mergeHero(this.touchStart, touchEnd)
				}
				else{
					this.changeHeroPos(this.touchStart, touchEnd)
				}

			}
			else{
				this.setHeroPos(this.touchStart, posData.posIndex)
			}
			this.touchStart = null;
		}
	}

	onTouchCancel(event: EventTouch) {
		this.touchCancel()
	}

	touchCancel() {
		this.radiusNode.active = false;
		if (this.touchStart) {
			this.resetHeroPos(this.touchStart)
			this.touchStart = null;
		}
	}

	//根据世界坐标获取item  排除手上的
	private getItemBaseByPosition(pos: Vec2):PosData {
		let FindArr = this.bagPosList

		let bag =  FindArr.find(t => {
			if(t.bLock) return false
			if(t.hero && t.hero != this.touchStart){
				return t.hero.getComponent(Hero).hitTest(pos)
			}
			return t.node.getComponent(UITransform).hitTest(pos)
		});

		if (bag ) return  bag

		FindArr = this.attackPosList

		let attack =  FindArr.find(t => {
			if(t.hero && t.hero != this.touchStart){
				return t.hero.getComponent(Hero).hitTest(pos)
			}
			return t.node.getComponent(UITransform).hitTest(pos)
		});

		return attack;
	}
	//炸弹效果播放结束
	bombSpineOver() {
		
	}

	//UI开打时会调用,如果有初始化代码应该放到此函数
	onOpen(args) {

		
		

		let battlesConf = BattlesConf.data[BattleData.duplicate.max_process]
		if(battlesConf){
			if(battlesConf.BossProcess > BattleData.duplicate.max_process){
				this.battlesID = BattleData.duplicate.max_process + 1
				this.bStart = true
			}
			else{
				this.changeChapterNode.getComponent(ChangeChapter).show(
					()=>{
						this.restartBattle(this.battlesID+1)
					}
				);
				//只考虑换章节,暂不考虑数据错乱
				this.battlesID = BattleData.duplicate.max_process
				this.changeChapterNode.active = true
				this.bStart = false
			}
		}
		else{
			//没数据就认为是第一关
			this.bStart = true
			this.battlesID = 1
		}

		this.battleControl.init(this.battlesID)
		this.init();

	}
	//UI关闭时会调用,该函数在onDestroy前调用
	onClose() {
		
	}

	//框架管理UI层级时会调用,可根据UI情况修改
	onShow() {
		super.onShow();
	}

	//框架管理UI层级时会调用,可根据UI情况修改
	onHide() {
		super.onHide();
	}

	init() {

		
		let posID = 0;
		let roleTransform = this.roleNode.getComponent(UITransform)
		let bagChildren = this.bagNode.children
		for (let i = 0; i < BattleUtil.BagListSize; i++) {
			let node = bagChildren[i];
			let pos = roleTransform.convertToNodeSpaceAR(node.getWorldPosition())
			let posData: PosData = {
				node: node,
				hero: null,
				bLock: false,
				posIndex: posID,
				pos: pos,
				posNumber: -1
			}
			this.bagPosList.push(posData);
			posID++;
			
		}

		this.reset()

		
	}

	reset(){

		let battleConf = BattlesConf.data[this.battlesID.toString()]
		if(!battleConf){
			console.log("战斗配置错误")
			return
		}

		this.lockAttackPosNumber = BattleUtil.AttackListSize-battleConf.Unlock
		
		let mapConf = MapConf.data[this.battleControl.mapID.toString()]
		if(!mapConf){
			console.log("地图配置错误")
			return
		}
		let offset = mapConf.OffsetArray
		if(offset){
			baseOffset.x = offset[0]||0
			baseOffset.y = offset[1]||0
		}
		else{
			baseOffset.x = 0
			baseOffset.y = 0
		}
		let attackChildren = this.attackNode.children
		let attackNode = this.attackNode.children[0]
		// this.attackPosList = []
		this.attackPosMap.clear()

		for (let i = 0; i < BattleUtil.BagListSize; i++) {
			let posData = this.bagPosList[i];
			if(i < BattleUtil.BagListSize-this.lockBagPosNumber){
				posData.node.getChildByName("lock").active = false
				posData.bLock = false
			}
			else{
				posData.bLock = true
				posData.node.getChildByName("lock").active = true
			}
		}

		let heroData = HeroDataPool.getObject();
		for (let i = 0; i < BattleUtil.BagListSize; i++) {
			let bagPos = this.bagPosList[i];
			if(bagPos.hero){
				let value = BattleData.layout[i];
				let battleLayoutData = BattleManager.getDataWithLayoutValue(value)
				bagPos.hero.position = bagPos.pos;
				let hero = bagPos.hero.getComponent(Hero);
				
				heroData.init(RoleData.getRoleDataByID(battleLayoutData.typeID),battleLayoutData.level,-1)
				hero.resetData(heroData);
			}
		}
		for (let i = 0; i < BattleUtil.AttackListSize; i++) {
			let node = attackChildren[i];
			if(!node){
				node = instantiate(attackNode)
				this.attackNode.addChild(node)
			} 

			let posNumber = this.battleControl.getPosIDByIndex(i)
			if(posNumber != -1){
				node.active = true;
				let mapDataPos = this.battleControl.getPosition(posNumber)
				let pos = MapDataPosToView(mapDataPos.x,mapDataPos.y)
				node.position = pos
				let posData: PosData = this.attackPosList[i]
				if(i < BattleUtil.AttackListSize-this.lockAttackPosNumber){
					node.getChildByName("lock").active = false
					if(!posData){
						posData = {
							node: node,
							hero: null,
							bLock: false,
							posIndex: BattleUtil.BagListSize+i,
							pos: new Vec3(pos.x, pos.y, 0),
							posNumber: posNumber
						}
						this.attackPosList.push(posData);
					}
					else{

						posData.posIndex = BattleUtil.BagListSize+i;
						posData.pos = new Vec3(pos.x, pos.y, 0);
						posData.posNumber = posNumber;
						if(posData.hero){
							let value = BattleData.layout[i+BattleUtil.BagListSize];
							let battleLayoutData = BattleManager.getDataWithLayoutValue(value)
							posData.hero.position = posData.pos;
							let hero = posData.hero.getComponent(Hero);
							
							heroData.init(RoleData.getRoleDataByID(battleLayoutData.typeID),battleLayoutData.level,posNumber)
							hero.resetData(heroData);
						}
					}
					this.attackPosMap.set(posNumber, posData);
				}
				else{
					if(posData){
						if(posData.hero){
							posData.hero.removeFromParent();
						}
						this.attackPosList.splice(i);
					}
					node.getChildByName("lock").active = true
				}
			}
			else {
				node.active = false;
			}
			
		}
		HeroDataPool.putObject(heroData);

		let path = "texture/tower/"+mapConf.Background+"/spriteFrame"

		this.load("package",path, SpriteFrame, (res: SpriteFrame) => {
			this.mapSprite.spriteFrame = res
		})
		let processe = BattlesConf.data[this.battlesID].Process
		this.mapName.string = StringUtil.getLanguageData(mapConf.Name,[processe])

		tween(this.battlesProgressBar).to(0.5, { progress: ((processe-1)%5)/4 }).start()
		let curValue = processe-((processe-1)%5)
		for (let i = 0; i < 5; i++) {
			let node = this.levelValue[i];
			node.string = (curValue+i).toString()
		}
		


		// this.bStart = false;
		// this.waitTime = 5;
		this.operateList = [];
		this.gameTime = 0;
		this.powerCur = UserData.status.food
		this.radiusNode.active = false;
		this.damageCountData.clear()
		this.resultNode.active = false
		this.updateDamageCount()
		this.powerLabel.string = `${this.powerCur}/${this.powerMax}`;
	}




	private initPool() {
		//初始化池
		let queue = new AsyncQueue();

		queue.pushMulti("InitPool", async (next: NextFunction, params: any, args: any) => {

			Framework.tips.setTipsNode("package", "prefab/ui/tips/tips_flash", "Label", () => {
				next && next();
			});

		});

		queue.complete = () => {
			//this._loginEx();
		};

		queue.play();

		//this._loginEx();
		this.loadHeroModel()
	}


	//添加一个新英雄
	addHero() {
		
		if(this.loadHeroModelNum < this.loadHeroModelNumMax){
			console.log("英雄没加载完成");
			return;
		}
		let posID = -1;
		if(this.powerCur <= 0){
			console.log("没有精力了");
			return;
		}

		for (let i = 0; i < BattleUtil.BagListSize; i++) {
			let bagPos = this.bagPosList[i];
			if(!bagPos.bLock && bagPos.hero == null){
				posID = this.bagPosList[i].posIndex;
				break;
			}
		}
		if(posID == -1) {
			console.log("没有空位了");
			return;
		}
		
		//添加英雄


		let heroIndex = Math.floor(Math.random() * this.loadHeroModelNum)%this.loadHeroModelNum;
		let heroID = this.fightRole[heroIndex];
		if(heroID == 0){
			for(let i = 0; i < this.fightRole.length; i++){
				heroID = this.fightRole[i];
				if(heroID != 0){
					break;
				}
			}
		}
		let heroData = HeroDataPool.getObject();
		heroData.init(RoleData.getRoleDataByID(heroID),1,1)
		
		let node:Node = null;
		if(this.heroPool[heroID] == null){
			this.heroPool[heroID] = [];
		}
		else {
			if(this.heroPool[heroID].length > 0){
				node = this.heroPool[heroID].pop();
			}
		}
		if(node == null){
			node = instantiate(this.heroModelMap.get(heroID));
			node.parent = this.roleNode;
			this.heroList.push(node);
		}
		
		let hero = node.getComponent(Hero);
		hero.resetData(heroData);
		HeroDataPool.putObject(heroData);
		
		hero.posIndex = posID;
		let posData = this.bagPosList[posID];
		if(!posData){
			return;
		}
		posData.hero = node;
		
		node.position = posData.pos;

		//记录添加英雄操作
		let otps:BattleOptsNew ={
			type:BattleOptsType.New,
			pos:BattleLayoutPos[posData.posIndex],
			level:1,
			raceID:Math.floor(heroData.typeID/HeroRaceSacle),
		
		} 
		this.operateList.push(otps);

		console.log("添加英雄", node.position);
		this.powerLabel.string = `${this.powerCur}/${this.powerMax}`;
		this.powerCur--;
		
		this.checkMerge(node);

	}
	/**
	 * 添加一个已有数据的英雄
	 * @param typeID 类型
	 * @param level 等级
	 * @param posIndex 所处位置下标
	 * @returns 
	 */
	addHeroWithData( typeID:number,level:number, posIndex:number) {

		//添加英雄
		if(this.loadHeroModelNum < this.loadHeroModelNumMax){
			console.log("英雄没加载完成");
			return;
		}

		// let heroIndex = Math.floor(Math.random() * this.loadHeroModelNum)%this.loadHeroModelNum;
		let heroID = typeID;
		let heroData = HeroDataPool.getObject();
		heroData.init(RoleData.getRoleDataByID(heroID),level,1)
		
		let posData = this.bagPosList[posIndex];
		
		if(!posData){
			posData = this.attackPosList[posIndex-BattleUtil.BagListSize];
			this.battleControl.addHeroInPos(heroData.typeID,heroData.level,posIndex - BattleUtil.BagListSize)
		}
		if(!posData){
			return;
		}

		let heroNode = posData.hero;
		if(heroNode){
			this.heroList.splice(this.heroList.indexOf(heroNode), 1)
			this.heroPool[heroNode.getComponent(Hero).typeID].push(heroNode)
			heroNode.getComponent(Hero).clearData();
		}
		let node:Node = null;
		if(this.heroPool[heroID] == null){
			this.heroPool[heroID] = [];
		}
		else {
			if(this.heroPool[heroID].length > 0){
				node = this.heroPool[heroID].pop();
			}
		}
		if(node == null){
			node = instantiate(this.heroModelMap.get(heroID));
			node.parent = this.roleNode;
			this.heroList.push(node);
		}
		
		let hero = node.getComponent(Hero);
		hero.resetData(heroData);
		HeroDataPool.putObject(heroData);
		
		hero.posIndex = posIndex;
		
		posData.hero = node;
		
		let scale = posIndex > BattleUtil.BagListSize-1 ? 1.2 : 1;
		node.scale = v3(scale,scale,1);

		node.position = posData.pos;

		

	}

	checkMerge(node:Node) {
		let hero = node.getComponent(Hero);
		if(!hero) {
			return;
		}
		let bFind = false;
	    if(this.isAutoMerge && !hero.isLock && hero.posIndex < BattleUtil.BagListSize){
			for (let i = 0; i < this.attackPosList.length; i++) {
			    let dstPosData = this.attackPosList[i];
				if(dstPosData.hero != null && dstPosData.hero != node){
					let dstHero = dstPosData.hero.getComponent(Hero);
				    if((!dstHero.isLock) && dstHero.typeID == hero.typeID && dstHero.level == hero.level){
						if(this.mergeHero(node, dstPosData.hero)){
							bFind = true;
							break;

						}
				    }
				}
			}

			if(!bFind){
				for (let i = 0; i < BattleUtil.BagListSize; i++) {
					let dstPosData = this.bagPosList[i];
					if(dstPosData.hero != null && dstPosData.hero != node){
						let dstHero = dstPosData.hero.getComponent(Hero);
						if((!dstHero.isLock) && dstHero.typeID == hero.typeID && dstHero.level == hero.level){
							if(this.mergeHero(node, dstPosData.hero))
								break;
						}
					}
				}
				
			}
			
		}

		
	}

	//合并英雄
	mergeHero(srcNode:Node, dstNode:Node) {
		let dstHero = dstNode.getComponent(Hero);
		if(dstHero.isLock){
			return false;
		}
		dstHero.isLock = true;
		// srcNode.setSiblingIndex(BattleUtil.BagListSize+this.attackPosList.length)
		srcNode.getComponent(Hero).flyTo(dstNode.position,()=>{
			if(isValid(dstHero)){
				dstHero.isLock = false;
				dstHero.levelUp()
				if(dstHero.posIndex >= BattleUtil.BagListSize){
					let index = dstHero.posIndex - BattleUtil.BagListSize;
					this.battleControl.levelUp(index)
				}
				this.levelUpEffectIndex = this.levelUpEffectIndex++%this.levelUpEffect.length;

				this.levelUpEffect[this.levelUpEffectIndex].position = dstNode.position
				this.levelUpEffect[this.levelUpEffectIndex].active = true
				this.levelUpEffect[this.levelUpEffectIndex].getComponent(sp.Skeleton).setAnimation(0, "animation", false)
				this.removeHeroPos(srcNode)
				this.checkMerge(dstNode)
			}
		})

		//记录合并英雄操作
		let opts:BattleOptsMerge = {
			type:BattleOptsType.Merge,
			srcPos:BattleLayoutPos[srcNode.getComponent(Hero).posIndex],
			targetPos:BattleLayoutPos[dstHero.posIndex],
		}
		this.operateList.push(opts)
		
		return true;
	}

	addEnemy(eventData: BattleEventData_EnemyBorn) {
		//添加敌人
		let node:Node = null;
		if(this.enemyPool.has(eventData.typeID) && this.enemyPool.get(eventData.typeID).length > 0){
			node = this.enemyPool.get(eventData.typeID).pop();
		}
		else {
			node = instantiate(this.ememyModelList[eventData.typeID-1]);
			node.parent = this.roleNode;
		}
		
		node.setSiblingIndex(0)
		node.getComponent(Enemy).resetData(eventData.typeID,eventData.ID,MapDataPosToView(eventData.position.x,eventData.position.y),eventData.life,eventData.lifeMax)
		node.getComponent(Enemy).startMove("move1")

		this.enemyMap.set(eventData.ID,node);
		
		
	}

	onClickAddHero() {
		Framework.audio.playEffect(AudioID.Click);
		this.addHero();
	}
	//重置坐标
	resetHeroPos(heroNode:Node) {
		let hero = heroNode.getComponent(Hero)
		if(!hero) {
			return;
		}
		let posID = hero.posIndex;
		if(posID != -1){
			if(posID < BattleUtil.BagListSize)
				heroNode.position = this.bagPosList[posID].pos;
			else if(posID < BattleUtil.BagListSize + this.attackPosList.length){
				heroNode.position = this.attackPosList[posID - BattleUtil.BagListSize].pos;
				this.battleControl.addHeroInPos(hero.typeID,hero.level,posID - BattleUtil.BagListSize)
			}
		}
	}

	//设置新坐标
	setHeroPos(hero:Node,newPosIndex:number) {
		let posIndex = hero.getComponent(Hero).posIndex;
		if(posIndex != -1){
			if(posIndex < BattleUtil.BagListSize){
				this.bagPosList[posIndex].hero = null;
				// console.log("setHeroPos1",posID)
			}else if(posIndex < BattleUtil.BagListSize + this.attackPosList.length){
				this.attackPosList[posIndex - BattleUtil.BagListSize].hero = null;
				// console.log("setHeroPos2",posID)
				
				
			}
		}
		else{
			console.error("setHeroPos error",posIndex)
			return;
		}

		if(newPosIndex != -1){
			if(newPosIndex < BattleUtil.BagListSize){
				this.bagPosList[newPosIndex].hero = hero;
				hero.position = this.bagPosList[newPosIndex].pos;
				hero.scale = new Vec3(1,1,1);
			}
			else if(newPosIndex < BattleUtil.BagListSize + this.attackPosList.length){
				let index = newPosIndex - BattleUtil.BagListSize;
				this.attackPosList[index].hero = hero;
				hero.position = this.attackPosList[index].pos;
				let heroObj = hero.getComponent(Hero)
				this.battleControl.addHeroInPos(heroObj.typeID,heroObj.level,index)
				hero.scale = new Vec3(1.2,1.2,1);
			}
			hero.getComponent(Hero).posIndex = newPosIndex
		}
		else{
			console.log("hero move error")
			return
		}

		//记录交换操作
		let opts:BattleOptsMove = {
			type: BattleOptsType.Move,
			targetPos: BattleLayoutPos[newPosIndex],
			srcPos: BattleLayoutPos[posIndex],
		}
		this.operateList.push(opts)
		
	}

	/**
	 * 移除英雄
	 * @param hero 节点 
	 * @param bOtps 是否记录此次移除操作
	 */
	removeHeroPos(hero:Node,bOtps:boolean = false) {
		let posIndex = hero.getComponent(Hero).posIndex;
		if(posIndex != -1){
			this.heroList.splice(this.heroList.indexOf(hero), 1)
			this.heroPool[hero.getComponent(Hero).typeID].push(hero)
			hero.getComponent(Hero).clearData();
			if(posIndex < BattleUtil.BagListSize){	
				this.bagPosList[posIndex].hero = null;
				// console.log("removeHeroPos1",posID)
			}else if(posIndex < BattleUtil.BagListSize + this.attackPosList.length){
				this.attackPosList[posIndex - BattleUtil.BagListSize].hero = null;
				// console.log("removeHeroPos2",posID)
				this.battleControl.removeHeroInPos(posIndex - BattleUtil.BagListSize)
			}

			if(bOtps){
				let otps:BattleOptsRemove = {
					pos:BattleLayoutPos[posIndex],
					type:BattleOptsType.Remove
				}
				this.operateList.push(otps)
			}
		}
	}

	//交换位置
	changeHeroPos(hero1:Node,hero2:Node) {
		let posIndex1 = hero1.getComponent(Hero).posIndex;
		let posIndex2 = hero2.getComponent(Hero).posIndex;
		hero1.getComponent(Hero).posIndex = posIndex2
		hero2.getComponent(Hero).posIndex = posIndex1

		
		if(posIndex1 != -1){
			if(posIndex1 < BattleUtil.BagListSize){
				hero2.position = this.bagPosList[posIndex1].pos;
				this.bagPosList[posIndex1].hero = hero2;
				hero2.scale = new Vec3(1,1,1);
			}
			else if(posIndex1 < BattleUtil.BagListSize + this.attackPosList.length){
				hero2.position =  this.attackPosList[posIndex1 - BattleUtil.BagListSize].pos;
				let index = posIndex1 - BattleUtil.BagListSize;
				this.attackPosList[index].hero = hero2;
				let heroObj = hero2.getComponent(Hero)
				this.battleControl.addHeroInPos(heroObj.typeID,heroObj.level,index)
				hero2.scale = new Vec3(1.2,1.2,1);
			}
			hero2.getComponent(Hero).stand()
		}

		if(posIndex2 != -1){
			if(posIndex2 < BattleUtil.BagListSize){
				hero1.position = this.bagPosList[posIndex2].pos;
				this.bagPosList[posIndex2].hero = hero1;
				hero1.scale = new Vec3(1,1,1);
			}
			else if(posIndex2 < BattleUtil.BagListSize + this.attackPosList.length){
				hero1.position =  this.attackPosList[posIndex2 - BattleUtil.BagListSize].pos;
				let index = posIndex2 - BattleUtil.BagListSize;
				this.attackPosList[index].hero = hero1;
				let heroObj = hero1.getComponent(Hero)
				this.battleControl.addHeroInPos(heroObj.typeID,heroObj.level,index)
				hero1.scale = new Vec3(1.2,1.2,1);
			}
			hero1.getComponent(Hero).stand()

			
		}

		
			//记录交换操作
			let opts:BattleOptsMove = {
				type: BattleOptsType.Move,
				targetPos: BattleLayoutPos[posIndex2],
				srcPos: BattleLayoutPos[posIndex1],
			}
			this.operateList.push(opts)
	}

	addHurt(pos:Vec3,value:number){
		// console.log("addHurt",value)
		let node:Node = null;
		if(this.hurtPool.length > 0){
			node = this.hurtPool.pop();
		}
		else {
			node = instantiate(this.hurtModelList[0]);
			node.parent = this.roleNode;
		}
		
		node.position = pos;
		this.hurtList.push(node);
		node.getComponent(Hurt).hurt(value,()=>{
			this.hurtList.splice(this.hurtList.indexOf(node), 1)
			this.hurtPool.push(node)
		})
	}


	updateSiblingIndex() {
		let children = this.roleNode.children
		children.sort((a, b) => {
			let battleNodeA = a.getComponent(BattleNodeBase);
			let battleNodeB = b.getComponent(BattleNodeBase);
			if (!battleNodeA || !battleNodeB) {
				return 0;
			}
			let priorityA = battleNodeA.priority
			let priorityB = battleNodeB.priority
			if (priorityA != priorityB) {
				return priorityA - priorityB;
			}
			if(this.touchStart == b){
				return -1;
			}
			if(this.touchStart == a){
				return 1;
			}
			//特殊状态
			if(battleNodeB.isLock){
				return -1;
			}
			if(battleNodeA.isLock){
				return 1;
			}
			if (a.position.y != b.position.y) {
				return b.position.y - a.position.y;
			}
			else {
				a.position.x - b.position.x
			}
		});
		for (let i = 0; i < children.length; i++) {
			
			children[i].setSiblingIndex(i);
		}
	}


	setRadius(radius:number){
	    this.radiusNode.scale = v3(0.4*radius,0.4*radius,1)
	}


	updateDamageCount(){
		let num = 0
		let allEnemyHP = this.battleControl.allEnemyHP
		this.damageCountData.forEach((value,typeID)=>{
			let countNode = this.countList[num]
			if(num < this.countList.length){

				this.countList[num].active = true
			}
			if(countNode){
				let headSprite = countNode.getChildByName("head").getComponent(Sprite)
				let valueLabel = countNode.getChildByName("number")
				let progress = countNode.getChildByName("progress").getComponent(UITransform)
				MaterialUtil.getHeadByID(typeID,headSprite)
				//headSprite.getComponent(Sprite).spriteFrame = this.headSprite[typeID]
				valueLabel.getComponent(Label).string = StringUtil.bigNumberToStr(value)

				let progressWidth = value/allEnemyHP*84
				if(progressWidth > 84){
					progressWidth = 84
				}
				progress.setContentSize(progressWidth,20)


			}


			num++
		})

		for(let i = num;i<this.countList.length;i++){
			this.countList[i].active = false
		}
	}

	setDamageCount(typeID:number,value:number){
		let valueOld = this.damageCountData.get(typeID) || 0
		this.damageCountData.set(typeID,value+valueOld)
	}

	private onTouchButton(event: Event, customStr) {
		let target: any = event.target;
		if (target.name == 'mask') {
			Framework.layer.close(this);
		} else if (target.name == 'hanghui_btn') {
			RoleManager.getNewRole()
		} else if (target.name == 'hero_btn') {
			Framework.layer.open(ViewID.HeroList);
		} else if (target.name == 'material_btn') {
			Framework.layer.open(ViewID.HeroFate);
		} else if (target.name == 'mail_btn') {
			MailManager.sendGetMailMsg({ ids: [MailData.getMaxMailId(0), MailData.getMaxMailId(1)] }, () => {
				Framework.layer.open(ViewID.MailMain);
			})
		}else if (target.name == 'title_bg'){
			this.rewardChapterNode.getComponent(RewardChapter) .show();
		}
	}

	//{typeID:number,value:number}
	private bossUpdate(data:EnemyActionType){
		switch(data){
			case EnemyActionType.Born:
				
				break;
			case EnemyActionType.Die:
				
				break;
			case EnemyActionType.Hurt:
				
				break;
			case EnemyActionType.Move:
				
				break;
		}
	}

	private loadHeroModel(){
		let fightRole = RoleData.fightRole
		this.fightRole = fightRole
		this.loadHeroModelNum = 0
		this.loadHeroModelNumMax = 0
		fightRole.forEach(element => {

			if(element > 0 ){
				this.loadHeroModelNumMax ++
				if(!this.heroModelMap.has(element)){
					let url = "prefab/ui/tower/hero/role"+element
					this.load("package",url,Prefab,(prefab:Prefab)=>{
						this.heroModelMap.set(element,prefab)
						this.loadHeroModelNum++
						if(this.loadHeroModelNum == this.loadHeroModelNumMax){
							this.resetBattleLayout()
						}
					})
				}
				else{
					this.loadHeroModelNum++
				}
			}
			
			
		});

	}


	private resetBattleLayout(){

		//添加初始英雄
		for (let i = 0; i < BattleData.layout.length; i++) {
			let value = BattleData.layout[i];
			if(value > 0){
				let battleLayoutData = BattleManager.getDataWithLayoutValue(value)
				this.addHeroWithData(battleLayoutData.typeID,battleLayoutData.level,i)
			}
		}
	}


	//重新开始第x关
	private restartBattle(battlesID){
		this.enemyMap.forEach((enemy, enemyID) => {
			enemy.getComponent(Enemy).clearData();
			this.enemyMap.delete(enemyID);
			let typeID = enemy.getComponent(Enemy).typeID
			if(this.enemyPool.has(typeID)){
				this.enemyPool.get(typeID).push(enemy);
			}
			else {
				this.enemyPool.set(typeID,[enemy]);
			}
		})
		this.battlesID = battlesID;
		this.battleControl.reset(this.battlesID)
		this.reset()  

		for(let index = 0; index < this.attackPosList.length; index++){
			let hero  = this.attackPosList[index].hero;
			if(hero){
				hero.position = this.attackPosList[index].pos;
				let heroObj = hero.getComponent(Hero)
				this.battleControl.addHeroInPos(heroObj.typeID,heroObj.level,index)
			}
		}

		this.bStart = true;
	}
}