import {
	_decorator,
	Animation,
	Button,
	Color,
	Component,
	director,
	instantiate,
	Prefab,
	RichText,
	Sprite,
	Vec3,
	Node,
	Label
} from "cc";
import { IAreanPlayer, IAreanUserTreasure, stage } from "db://assets/module_basic/shared/protocols/public/arean/AreanTypeDef";
import { EMusicDefine } from "db://assets/module_basic/Define/MusicDefine";
import { MsgAreanDanUpdatePush } from "db://assets/module_basic/shared/protocols/public/arean/MsgAreanDanUpdatePush";
import { UserMgr } from "db://assets/module_basic/scripts/UserMgr";
import { MsgAreanBattleRewardsPush } from "../../module_basic/shared/protocols/public/arean/MsgAreanBattleRewardsPush";
import { resLoader } from "../../core_tgx/base/utils/ResLoader";
import { tgxAudioMgr, tgxUIAlert } from "../../core_tgx/tgx";
import { areanMgr } from "../../module_arean/scripts/AreanManager";
import { AreanNetMgr, AreanEvent } from "../../module_arean/scripts/AreanNetMgr";
import { MsgAreanGameStatusPush } from "../../module_basic/shared/protocols/public/arean/MsgAreanGameStatusPush";
import { ModuleDef } from "../../scripts/ModuleDef";
import { settlementView } from "./settlementView";

const { ccclass, property } = _decorator;



@ccclass('BattleView')
export class BattleView extends Component {


	curTurn: number = 1;  //当前回合数
	curSeat: number = 0;  //当前玩家座位号
	remainingTime: number = 0;
	curStage: stage = stage.await;

	// 当前播放的背景音乐
	_curPlayBgm: string = "bgm_battle";
	hasSettlement: boolean = false;
	warningNum: number = 0;
	rewards: MsgAreanBattleRewardsPush = null;


	@property({ type: Prefab })
	roleItem: Prefab = null;
	@property({ type: Label })
	timerLabel: Label = null;
	@property({ type: Label })
	stageLabel: Label = null;
	@property({ type: Label })
	personLabel: Label = null;

	chooseJobBool: boolean = false;
	curTurnLable: RichText = null;
	cardList: Node = null;
	treasureList: Node = null;
	jobList: Node = null;
	btnSurrender: Button = null;
	btnExit: Button = null;
	chooseJobView: Node = null;

	private minRoleId: number = 1;
	private maxRoleId: number = 5;

	// 添加相机引用属性
	@property({ type: Node })
	private camera: Node = null;

	private localPlayer: Node = null;
	isInit: boolean = false;



	start() {
		areanMgr.BattleView = this;

		console.log("储存的玩家数据", AreanNetMgr.inst.playerMap);
		tgxAudioMgr.inst.play(EMusicDefine.MUSIC_BGM_BATTLE, 1, ModuleDef.BASIC);
		director.on(AreanEvent.BattleReportPush, this.playBattleReport, this);
		director.on(AreanEvent.PlayerStatus, this.initPlayerStatus, this);
		director.on(AreanEvent.BattleStagePush, this.refreshBattleStage, this);
		director.on(AreanEvent.SelectCardList, this.SelectCardList, this);
		director.on(AreanEvent.SelectTreasureList, this.refreshTreasureList, this);
		director.on(AreanEvent.UpdateBattleResult, this._updateRewards, this);
	}





	protected onDestroy() {
		// Remove event listeners
		director.off(AreanEvent.BattleReportPush, this.playBattleReport, this);
		director.off(AreanEvent.PlayerStatus, this.initPlayerStatus, this);
		director.off(AreanEvent.BattleStagePush, this.refreshBattleStage, this);
		director.off(AreanEvent.SelectCardList, this.SelectCardList, this);
		director.off(AreanEvent.SelectTreasureList, this.refreshTreasureList, this);
		director.off(AreanEvent.UpdateBattleResult, this._updateRewards, this);

		// Play hall BGM
		tgxAudioMgr.inst.play(EMusicDefine.MUSIC_BGM_HALL, 1, ModuleDef.BASIC);
	}




	update(dt: number): void {
		if (!this.isInit && Object.keys(AreanNetMgr.inst.playerMap).length > 7) {
			this.isInit = true;
			this.initPlayerStatus();
		}
	}





	refreshBattleStage(data: MsgAreanGameStatusPush) {
		//console.log("刷新阶段", data);


		this.remainingTime = data.remainingTime;
		this.timerLabel.string = data.remainingTime + "";
		this.curTurn = data.battleRounds;


		//this.stageTimer.active = data.remainingTime >=0;
		//阶段开始
		let stageLabel = this.stageLabel.string;

		// data.stageId === stage.card ? tgxAudioMgr.inst.play(EMusicDefine.SMUSIC_BGM_SELECT_CARD,1,ModuleDef.BASIC) :

		switch (data.stageId) {
			case stage.career:

				if (this.stageLabel.string != "选择职业") {
					stageLabel = "选择职业";
					if (this.getLocalPlayerData().bloodVolume > 0) {
						this.refreshJobList(this.getLocalPlayerData().heroId);
					}

				}

				break;
			case stage.card:
				if (this.stageLabel.string != "选择卡牌") {
					stageLabel = "选择卡牌";

					if (this.getLocalPlayerData().bloodVolume > 0) {


						this.refreshCardList();
						if (this._curPlayBgm !== 'bgm_select_card') {
							this._curPlayBgm = 'bgm_select_card';
							tgxAudioMgr.inst.play(EMusicDefine.MUSIC_BGM_SELECT_CARD, 1, ModuleDef.BASIC);
						}


					}
				}


				break;
			case stage.battle:
				if (this.stageLabel.string != "战斗阶段") {
					stageLabel = "战斗阶段";

					this.updatePlayerLocalData();

					if (this._curPlayBgm !== 'bgm_battle') {
						this._curPlayBgm = 'bgm_battle';
						tgxAudioMgr.inst.play(EMusicDefine.MUSIC_BGM_BATTLE, 1, ModuleDef.BASIC);
					}

				}

				break;
			case stage.equip:
				if (this.stageLabel.string != "选择装备") {
					stageLabel = "选择装备";

					if (this.getLocalPlayerData().bloodVolume > 0) {
					}
				}


				break;
			case stage.treasure:

				if (this.stageLabel.string != "选择圣物") {

					stageLabel = "选择圣物";
					if (this.getLocalPlayerData().bloodVolume > 0) {
						this.refreshTreasureList(this.getLocalPlayerData().selectTreasureList);
					}
				}



				break;
			case stage.await:
				break;
			case stage.afterCard:

				if (this.stageLabel.string != "即将开战") {
					stageLabel = "即将开战";
				}



				break;
			default:
				break;
		}


		//战斗结束
		if (this.curStage == stage.battle && data.stageId != stage.battle) {
			for (let i = 0; i < 8; i++) {
			}

			if (!this.hasSettlement && (this.deadCount() >= 7 || this.getLocalPlayerData().bloodVolume <= 0)) {

				this.showSettlementView(this.getLocalPlayerData().rank);
			}
		}

		//选择职业结束
		if (this.curStage == stage.career && data.stageId != stage.career && !this.chooseJobBool) {

			this.onClickChooseJob(0, 0, true);
		}

		this.curStage = data.stageId;
		this.stageLabel.string = stageLabel;
		this.curTurnLable.string = this.curTurn + "";






	}
	updatePlayerLocalData() {
		// Update the local player data from AreanNetMgr
		const localPlayer = this.getLocalPlayerData();
		// Add implementation as needed
	}

	playBattleReport() {

		//玩家移动,被击杀
	}





	SelectCardList() {

		this.refreshCardList();
	}

	refreshCardList() {

		let data = AreanNetMgr.inst.playerMap[this.getLocalPlayerId()].selectCardList;


		for (let i = 0; i < data.length; i++) {
			let card = data[i];
			let cardItem = this.cardList.children[i];
			cardItem.active = true;

			let index = i;
			cardItem.off("click");
			cardItem.on("click", () => {

				AreanNetMgr.inst.sendMsg_SelectCard(index);

			})
		}
	}



	private _refreshTreasureList(data: IAreanUserTreasure[], isCustom: boolean = false): void {
		this.refreshTreasureList(data, isCustom)
	}

	refreshTreasureList(data: IAreanUserTreasure[], isCustom: boolean = false) {

		this.stageLabel.string = "选择圣物";
		if (this._curPlayBgm !== 'bgm_select_card') {
			this._curPlayBgm = 'bgm_select_card';
			tgxAudioMgr.inst.play(EMusicDefine.MUSIC_BGM_SELECT_CARD, 1, ModuleDef.BASIC);
		}

		for (let i = 0; i < data.length; i++) {
			let d = data[i];
			let cardItem = this.treasureList.children[i];
			cardItem.active = true;

			let index = i;
			cardItem.off("click");
			cardItem.on("click", () => {
				AreanNetMgr.inst.sendMsg_SelectTreasure(index);
				for (let i = 0; i < this.treasureList.children.length; i++) {
					this.treasureList.children[i].getComponent(Button).interactable = false;
					this.treasureList.children[i].getComponent(Sprite).color = new Color(150, 150, 150, 255);
				}
				cardItem.getComponent(Sprite).color = new Color(255, 255, 255, 255);
			})
		}
	}

	refreshJobList(heroId: number) {

		this.node.getComponent(Animation).play("showJobView");
		this.chooseJobView.active = true;

		for (let i = 0; i < 3; i++) {
			let jobItem = this.jobList.children[i];
			jobItem.active = true;


			let index = i;
			jobItem.on("click", () => {

				this.onClickChooseJob(index, 0, true);
				this.playwarning("");
			})
		}


	}


	onClickChooseJob(index: number, jobId: number, send: boolean = false) {
		{


			this.node.getComponent(Animation).play("chooseJob");
			if (send) {
				setTimeout(() => {
					AreanNetMgr.inst.sendMsg_SelectCareer(jobId);
					//console.log("当前玩家的信息 === ", AreanNetMgr.inst._playerMap)

					this.getLocalPlayerData().careerId = jobId;
					this.chooseJobBool = true;
				}, 1000);
			}
		}
	}

	// 获取玩家座位号
	getLocalPlayerData(): IAreanPlayer {
		let data = AreanNetMgr.inst.selfPlayer;
		return data;
	}

	getLocalPlayerId() {
		return AreanNetMgr.inst.selfPlayer.playerId;
	}



	initPlayerStatus() {
		this.createRoles();
	}


	private async createRoles() {
		// 先创建本地玩家
		const localPlayerX = 0;  // 本地玩家的初始位置
		const localPlayerZ = 51;

		// 创建其他玩家
		for (let i = 1; i < Object.keys(AreanNetMgr.inst.playerMap).length; i++) {
			// 随机位置:X轴-10到9,Z轴50-53
			const x = Math.random() * 19 - 10;  // -10到9
			const z = Math.random() * 3 + 50;   // 50到53

			// 随机角色ID(1-5)
			const roleId = Math.floor(Math.random() * (this.maxRoleId - this.minRoleId + 1)) + this.minRoleId;
			const roleIdStr = roleId.toString().length < 3 ? '0'.repeat(3 - roleId.toString().length) + roleId : roleId.toString();

			const prefab: Prefab = resLoader.get(`common/role/Character${roleIdStr}`,Prefab,ModuleDef.Arean);
			if (prefab) {
				let role = instantiate(prefab);
				this.node.addChild(this.node);
				role.setPosition(new Vec3(x, 0, z));
				role.setRotationFromEuler(0, 180, 0);
			}

		}
	}

	onClickBtnQuit() {
		tgxUIAlert.show(`是否确认退出 ? `, true).onClick(async b => {
			if (b) {
				AreanNetMgr.inst.sendMsg_exit();
			}
		});
	}

	onClickBtnSurrender() {
		tgxUIAlert.show(`这就投了 ? `, true).onClick(async b => {
			if (b) {
				AreanNetMgr.inst.sendMsg_surrender();
			}
		});

	}


	showSettlementView(rank: number) {
		this.hasSettlement = true;
		this.btnSurrender.node.active = false;
		this.btnExit.node.active = true;
		const path = 'res/Prefebs/settlementView';
		let sp: Prefab = resLoader.get(path, Prefab, ModuleDef.Arean);
		let node = instantiate(sp);
		this.node.addChild(node);
		node.getComponent(settlementView).setData(rank);


	}




	playwarning(text: string) {

		setTimeout(() => {
			const path = 'res/Prefebs/warningTips';
			let sp: Prefab = resLoader.get(path, Prefab, ModuleDef.Arean);
			let node = instantiate(sp);
			this.node.addChild(node);
			node.getChildByPath("node/text").getComponent(RichText).string = text;
			setTimeout(() => {
				node.removeFromParent();
				this.warningNum--;
			}, 2000);
		}, this.warningNum * 500);
		this.warningNum++;

	}

	deadCount() {
		let dieNum = 0;
		for (const key in AreanNetMgr.inst.playerMap) {
			let data = AreanNetMgr.inst.playerMap[key];
			if (data.bloodVolume <= 0) dieNum++;
		}

		return dieNum;
	}


	_updateRewards(data: MsgAreanBattleRewardsPush) {
		this.rewards = data;
		let node = this.node.getChildByName("settlementView");
		if (node && this.rewards.uid == UserMgr.inst.uid) {
			node.getComponent(settlementView).updateRewards(this.rewards.items);
		}
	}

}