import { _decorator, Component, Label, director, Node, Button, instantiate, Sprite, Prefab, v3, SpriteFrame } from 'cc';
import {tgxAudioMgr, tgxSceneUtil, tgxUIAlert, tgxUIMgr} from '../../core_tgx/tgx';
import { RoomEvent } from '../../module_basic/scripts/GameMgr';
import { UserMgr } from '../../module_basic/scripts/UserMgr';
import { SceneDef } from '../../scripts/SceneDef';
import { GamePlayerInfo } from './GamePlayerInfo';
import { AreanEvent, AreanNetMgr } from './AreanNetMgr';
import {SubGameMgr} from "db://assets/module_basic/scripts/SubGameMgr";
import { EMusicDefine } from '../../module_basic/scripts/MusicDefine';
import { EFightModel } from '../../module_basic/shared/protocols/public/arean/AreanTypeDef';
import { UserLocalCache } from '../../module_basic/scripts/UserLocalCache';
import {IUserData} from "db://assets/module_basic/shared/types/RoomData";
import {areanMgr} from "db://assets/module_arean/scripts/AreanManager";
import {resLoader} from "db://assets/core_tgx/base/utils/ResLoader";
import {ModuleDef} from "db://assets/scripts/ModuleDef";
import {CommonFun} from "db://assets/module_arean/scripts/CommonFun";
import {MsgUserComesToRoomPush} from "db://assets/module_basic/shared/protocols/public/MsgUserComesToRoomPush";
import {IDanCfg} from "db://assets/module_basic/shared/configs/interface/IDanCfg";
const { ccclass, property } = _decorator;

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

    //#endregion


    @property(Label)
    tips: Label = null!;

    @property(Button)
    btnReady: Button;

    @property(Node)
    watcherList: Node;

    @property(Label)
    lblRoomId: Label;

    @property([GamePlayerInfo])
    public players: GamePlayerInfo[] = [];

    //#endregion
    //#region 组件第一次激活前执行,也就是第一次执行 update 之前触发
    start() {
        if (!UserMgr.inst.uid) {
            tgxSceneUtil.loadScene(SceneDef.START);
            return;
        }
        tgxUIMgr.inst.closeAll();
        director.on(AreanEvent.ChangeHero,this._changeHeroResult.bind(this),this)
        if (UserLocalCache.inst.fightModel == EFightModel.Room) {
            this.lblRoomId.string = AreanNetMgr.inst.data.displayId;
        }
        else {
            this.lblRoomId.string = '';
        }
        for (let i = 0; i < this.players.length; i++) {
            let player = this.players[i];
            player.setUserId('');
            player.setSeatIndex(i);
        }
        let userList = AreanNetMgr.inst.data.userList;
        console.log("当前房间的所有玩家信息 === ",userList);
        for (let i = 0; i < AreanNetMgr.inst.data.userList.length; i++) {
            let userData : IUserData = AreanNetMgr.inst.data.userList[i];
            this.initUser(userData,false);
        }
        this.initWatcherList();
        this.updateCtrlUI();
        this.initEventListener();
        this.updateReadyBtn();
    }
    //#endregion
    private _getCurRoomPlayer(uid : string){
        let userData : IUserData[] = AreanNetMgr.inst.data.userList;
        return userData.find(p => p.uid == uid);
    }
    //#region 用户信息初始化
    initUser(userData: IUserData, isLeaves: boolean) {
        console.log('initUser:', userData);
        let play = this.players.find(p => p._userId == userData.uid);
        let u : IUserData = AreanNetMgr.inst.selfUser;
        if(!u) return;
        if ( u.uid == userData.uid) {
            console.log('我自己selfUser:', u);
            this.players[0].node.active = true;
            this.players[0].setUserId(userData.uid);
            this._getHeroSpine(userData.uid,this.players[0].icon,this.players[0].danIcon).then();
            this.players[0].setOpenChooseHero(this._openChooseHeroLayer.bind(this));
            // this.btnReady.node.active = u && u.playerId && !u.ready;
        }else{
            if (play) {
                if (isLeaves) {
                    play.setUserId('');
                } else {
                    play.setUserId(userData.uid);
                    this._getHeroSpine(userData.uid,play.icon,this.players[0].danIcon).then();
                }
            } else {
                // 房主
                if(userData.seatIndex === 0){
                    play = this.players[3];
                    play.updateBg()
                    play.updateHomeOwnerActive(true);
                }else{
                    play = this.players.find(p => p._userId == '' && p.seatIndex != 0);
                }
                if (!isLeaves) {
                    play.setUserId(userData.uid);
                    this._getHeroSpine(userData.uid,play.icon,this.players[0].danIcon).then();
                }
            }
        }
    }
    //#endregion

    //#region 开始注册监听事件
    initEventListener() {
        director.getScene().on(RoomEvent.NEW_USER_COMES, this.onNewUserComes, this);
        director.getScene().on(RoomEvent.USER_LEAVES, this.onUserLeaves, this);
        director.getScene().on(RoomEvent.WATCHER_LIST_CHANGED, this.initWatcherList, this);
        director.getScene().on(RoomEvent.User_Make_Room, this.onUserMakeRoom, this);
    }

    onUserMakeRoom(){
        console.log('转让房主')
        this.updateReadyBtn();
    }

    protected onDestroy(): void {
        director.on(AreanEvent.ChangeHero,this._changeHeroResult.bind(this),this)
    }
    //#endregion

    onNewUserComes(data: MsgUserComesToRoomPush) {
        console.log('有人加入:', data);
        if (data) {
            let userData : IUserData = this._getCurRoomPlayer(data.uid);
            if(!userData){
                console.warn("没有找到对应的玩家的信息,onNewUserComes",data.uid);
                return;
            }
            this.initUser(userData, false);
        }
        else {
            this.initWatcherList();
        }
    }

    onUserLeaves(data) {
        console.log('有人离开:', data);
        if (data.isPlayer) {
            let userData : IUserData = this._getCurRoomPlayer(data.uid);
            if(!userData){
                console.warn("没有找到对应的玩家的信息,onUserLeaves",data.uid);
                return;
            }
            this.initUser(userData, true);
        }
        else {
            this.initWatcherList();
        }
    }

    async initWatcherList() {
        this.watcherList.parent.active = false;
        let usersData = AreanNetMgr.inst.data?.userList;
        // if (!AreanNetMgr.inst.gameMode || !usersData.length) {
        //     return;
        // }

        this.watcherList.parent.active = true;

        for (let i = 0; i < this.watcherList.children.length; ++i) {
            this.watcherList.children[i].active = false;
        }

        let userIds = [];
        let c = this.watcherList.children[0];
        for (let i = 0; i < usersData.length; ++i) {
            let u = usersData[i];
            if (!u.playerId) {
                let newNode = instantiate(c);
                this.watcherList.addChild(newNode);
                userIds.push(u.uid);
            }
        }

        await UserMgr.inst.rpc_GetUserInfos(userIds);

        for (let i = 0; i < userIds.length; ++i) {
            let c = this.watcherList.children[i];
            c.active = true;
            let icon = c.children[0].getComponent(Sprite);
            UserMgr.inst.setUserIconAndName(userIds[i], icon);
        }
    }

    updateCtrlUI() {
        console.log('updateCtrlUI 用户列表', AreanNetMgr.inst.data);
        // if (AreanNetMgr.inst.gameMode == EFightModel.SOLO) {
        //     this.tips.string = '单人练习';
        // }
        // else if (AreanNetMgr.inst.gameMode == GameMode.AI) {
        //     this.tips.string = '人机对决';
        // }
        // else 
        if (AreanNetMgr.inst.isWatcher) {
            this.tips.string = '观战中...';
        }
        else if (AreanNetMgr.inst.data.userList.length < 8) {
            this.tips.string = '等待对手加入...'
        }
        // else if (AreanNetMgr.inst.isMyTurn) {
        //     this.tips.string = '该你击球...';
        // }
        else {
            this.tips.string = '对手击球...';
        }
    }

    protected updateReadyBtn() {
        let user = AreanNetMgr.inst.data.userList.find(p => p.uid == UserMgr.inst.uid);
        let str = "准备"
        if (user && user.seatIndex == 0) {
            str = "开始游戏"
        }
        this.btnReady.node.getChildByName("Label").getComponent(Label).string = str;
        this.btnReady.node.getChildByName("autoLab").active = user && user.seatIndex == 0;
        this.players[0].updateHomeOwnerActive(user && user.seatIndex == 0);
    }

    async onBtnEnterClicked() {
        tgxAudioMgr.inst.playCommonBtn(EMusicDefine.EFFECT_CLICK);
        let user = AreanNetMgr.inst.data.userList.find(p => p.uid == UserMgr.inst.uid);
        if (user && user.seatIndex == 0) {
            let res = await AreanNetMgr.inst.sendMsg_StartGame();
            if (!res.res.isStarted) {
                tgxUIAlert.show("开始游戏失败,有玩家没准备");
            }
            // tgxUIMgr.inst.showUI(UIBattleLoading)
            // //房主
            // let res = await AreanNetMgr.inst.sendMsg_StartGame();
            // if (!res.res.isStarted) {
            //     tgxUIAlert.show("开始游戏失败,有玩家没准备");
            // }else{
            // }
        } else {///不是房主
            SubGameMgr.gameMgr.rpc_Ready().then((ret=>{
                if(ret.isSucc){
                    this.btnReady.node.active = false;
                }
            }));
        }
    }

    async onBtnExitClicked() {
        tgxAudioMgr.inst.playCommonBtn(EMusicDefine.EFFECT_CLOSE);
        if (AreanNetMgr.inst.isPlayer && AreanNetMgr.inst.isPlaying) {
            tgxUIAlert.show('确定要退出吗?', true).onClick(async (ok: Boolean) => {
                if (ok) {
                    let ret = await AreanNetMgr.inst.rpc_LeaveRoom();
                    if (ret.isSucc) {
                        tgxSceneUtil.loadScene(SceneDef.LOBBY_AREAN);
                    }
                    else {
                        tgxUIAlert.show('不能离开');
                    }
                }
            });
        }
        else {
            let ret = await AreanNetMgr.inst.rpc_LeaveRoom();
            if (ret.isSucc || (ret.err.code == 'LOST_CONN' && ret.err.message == 'USER_LEAVE')) {
                tgxSceneUtil.loadScene(SceneDef.LOBBY_AREAN);
            }
            else {
                tgxUIAlert.show(ret.err.message);
            }
        }
    }

    private _openChooseHeroLayer() : void{
       
    }

    /** 英雄spine */
    private async _getHeroSpine(userId : string,icon: Sprite,danIcon: Sprite): Promise<void> {
  }



    private _changeHeroResult(data : {uid : string}) : void{

    }
}