using AdamSync;
using AdamThinkDevicesData;
using PData;
using RDate;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Tenkoku.Core;
using UnityEngine;
using UnityEngine.UI;
using static InterfaceManager;

public class GameManager : MonoSingleton<GameManager>
{
    public SyncPlayerTransform playerTransformPrefab;
    public SyncPlayerTransform currentSpt;
    public Transform redSpawnPos;
    public Transform blueSpawnPos;
    public List<ulong> userIds = new List<ulong>();
    public TenkokuModule tenkokuModule;
    public List<ModelInfo> modelsInfo = new List<ModelInfo>();
    public Transform dviceContent;
    public DragController wrjDrag;
    public DragController ldDrag;
    public DragController hpDrag;
    public DragController wxdDrag;
    public DragController ppDrag;
    public DragController wbDrag;
    public GameObject Teacher;
    public GameObject student;
    public GameObject posture;
    public int wrjCount;
    public List<SyncPlayerTransform> players = new List<SyncPlayerTransform>();


    public DragController[] wrjDrags;

    public Mastermanagement mastermanagement;

    public Button postureBtn;
    public Button teacherBtn;

    // Start is called before the first frame update
    private void Awake()
    {
        postureBtn.onClick.AddListener(() =>
        {
            ChangeView(0);
        });
        teacherBtn.onClick.AddListener(() =>
        {
            ChangeView(2);
        });
        SyncCreateRoom.getroomusersRequset += OnGetRoomUsers;
        SyncCreateRoom.send2roomRequset += OnRoomInfo;
        SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
        spt.SetPlayerInfo(ulong.Parse(GlobalFlag.currentUser.user_id), GlobalFlag.currentUser.login_name, ulong.Parse(GlobalFlag.roomID), true);
        currentSpt = spt;
        ToolsBootstrap.Instance.SetCameraInfo(spt);
        //0 red  layer ==11 ,  1 blue  layer ==12
        if (UIBootstrap.Instance.GetRoleByIDPracticeId(GlobalFlag.practiceSeatId) == "0")
        {
            spt.transform.position = redSpawnPos.position;
            spt.transform.eulerAngles = redSpawnPos.eulerAngles;
            spt.gameObject.SetActive(true);
            spt.GetComponent<Camera>().cullingMask = ~(1 << 12);
            //spt.GetComponent<Camera>().cullingMask = ~(1 << 15);
            AdamThinkDevicesData.DataItem diTemp = UIBootstrap.Instance.GetDeviceByName("蜂群无人机");
            if (diTemp.device_count > 0)
            {
                wrjCount = diTemp.device_count;
                for (int i = 0; i < wrjDrags.Length; i++)
                {
                    wrjDrags[i].isPlayer = true;
                    wrjDrags[i].deviceID = UIBootstrap.Instance.GetDeviceByName("蜂群无人机").id;
                }
            }
            for (int i = 0; i < diTemp.list_para.Count; i++)
            {
                if (diTemp.list_para[i].para_name.Contains("光学侦察能力") && diTemp.list_para[i].para_value == "1")
                {
                    wrjDrags[0].gameObject.SetActive(false);
                }
            }
        }
        else
        {
            for (int i = 0; i < dviceContent.childCount; i++)
            {
                Destroy(dviceContent.GetChild(i).gameObject);
            }
            spt.transform.position = blueSpawnPos.position;
            spt.transform.eulerAngles = blueSpawnPos.eulerAngles;
            spt.gameObject.SetActive(true);
            spt.GetComponent<Camera>().cullingMask = ~(1 << 11);
            if (UIBootstrap.Instance.GetDeviceByName("探测雷达").device_count > 0)
            {
                for (int i = 0; i < UIBootstrap.Instance.GetDeviceByName("探测雷达").device_count; i++)
                {
                    DragController ld = Instantiate(ldDrag, dviceContent);
                    ld.deviceID = UIBootstrap.Instance.GetDeviceByName("探测雷达").id;
                    mastermanagement.dragControllers.Add(ld);
                }
            }
            if (UIBootstrap.Instance.GetDeviceByName("激光火控平台").device_count > 0)
            {
                for (int i = 0; i < UIBootstrap.Instance.GetDeviceByName("激光火控平台").device_count; i++)
                {
                    DragController hp = Instantiate(hpDrag, dviceContent);
                    hp.deviceID = UIBootstrap.Instance.GetDeviceByName("激光火控平台").id;
                    mastermanagement.dragControllers.Add(hp);
                }
            }
            if (UIBootstrap.Instance.GetDeviceByName("地面无线电干扰").device_count > 0)
            {
                for (int i = 0; i < UIBootstrap.Instance.GetDeviceByName("地面无线电干扰").device_count; i++)
                {
                    DragController wxd = Instantiate(wxdDrag, dviceContent);
                    wxd.deviceID = UIBootstrap.Instance.GetDeviceByName("地面无线电干扰").id;
                    mastermanagement.dragControllers.Add(wxd);
                }
            }
            if (UIBootstrap.Instance.GetDeviceByName("微波武器").device_count > 0)
            {
                for (int i = 0; i < UIBootstrap.Instance.GetDeviceByName("微波武器").device_count; i++)
                {
                    DragController wxd = Instantiate(wbDrag, dviceContent);
                    wxd.deviceID = UIBootstrap.Instance.GetDeviceByName("微波武器").id;
                    mastermanagement.dragControllers.Add(wxd);
                }
            }
            if (UIBootstrap.Instance.GetDeviceByName("频谱探测").device_count > 0)
            {
                for (int i = 0; i < UIBootstrap.Instance.GetDeviceByName("频谱探测").device_count; i++)
                {
                    DragController wxd = Instantiate(ppDrag, dviceContent);
                    wxd.deviceID = UIBootstrap.Instance.GetDeviceByName("频谱探测").id;
                    mastermanagement.dragControllers.Add(wxd);
                }
            }
        }
        ///04 student 03 teacher
        if (GlobalFlag.currentUser.role_code == "04")
        {
            Teacher.gameObject.SetActive(false);
            student.gameObject.SetActive(true);
            GlobalFlag.isStartRehearsing = (UIBootstrap.Instance.GetRoomStateById(GlobalFlag.roomID) == 1);
            Debug.Log($"<color=red>isStartRehearsing={ GlobalFlag.isStartRehearsing}</color>");
            if (GlobalFlag.isStartRehearsing)
            {
                spt.GetComponent<Camera>().cullingMask = -1;
            }
        }
        if (GlobalFlag.currentUser.role_code == "03")
        {
            Teacher.gameObject.SetActive(true);
            student.gameObject.SetActive(false);
            spt.GetComponent<Camera>().cullingMask = -1;
        }
        if (GlobalFlag.currentUser.role_code == "02")
        {
            Teacher.gameObject.SetActive(false);
            student.gameObject.SetActive(false);
            posture.gameObject.SetActive(true);
            spt.GetComponent<Camera>().cullingMask = -1;
        }
        spt.GetComponent<Camera>().cullingMask &= ~(1 << 15);

        tenkokuModule.mainCamera = spt.transform;
        AddPlayers(spt);
        DeviceManager.Instance.OnInit();
        DeviceManager.Instance.isStartRehearsing = GlobalFlag.isStartRehearsing;
    }


    public void Start()
    {
        SetWeatherValue();
        SetModelValue();
        string msg = "getroomusers ";
        _ = SyncCreateRoom.SendMessageAsync(msg);
    }


    private void Update()
    {
        if (UIBootstrap.Instance.GetRoleByIDPracticeId(GlobalFlag.practiceSeatId) == "0" && Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo, 1000))
            {
                if (hitInfo.collider.tag == "WRJ")
                {
                    UnmannedAerialVehicleUI.Instance.unmannedAerialVehicleManage = hitInfo.collider.GetComponent<UnmannedAerialVehicleManage>();
                }
            }
        }
    }

    /// <summary>
    /// 切换视图
    /// </summary>
    /// <param name="index"></param>
    public void ChangeView(int index)
    {
        Teacher.gameObject.SetActive(index == 0);
        student.gameObject.SetActive(index == 1);
        posture.gameObject.SetActive(index == 2);
    }

    public void AddPlayers(SyncPlayerTransform s)
    {
        if (!players.Contains(s))
        {
            players.Add(s);
        }
        if (!userIds.Contains(s.userID))
            userIds.Add(s.userID);
    }

    public void RemovePlayer(ulong playerID)
    {
        for (int i = 0; i < players.Count; i++)
        {
            if (players[i].userID == playerID)
            {
                Destroy(players[i].gameObject);
                players.RemoveAt(i);
                userIds.Remove(playerID);
            }
        }
    }

    public void OnRoomInfo(string msg)
    {
        StopCoroutine(WaitSpawn(msg));
        StartCoroutine(WaitSpawn(msg));
    }

    private IEnumerator WaitSpawn(string msg)
    {
        yield return new WaitForSeconds(0.5f);
        string[] data = msg.Split(',');
        switch (data[0])
        {
            case "online":
                ulong userId = ulong.Parse(data[1]);
                if (!userIds.Contains(userId))
                {
                    SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
                    //0 red  1 blue
                    if (UIBootstrap.Instance.GetRoleByIDPracticeId(GlobalFlag.practiceSeatId) == "0")
                    {
                        spt.gameObject.transform.position = redSpawnPos.position;
                        spt.gameObject.transform.eulerAngles = redSpawnPos.eulerAngles;
                    }
                    else
                    {
                        spt.gameObject.transform.position = blueSpawnPos.position;
                        spt.gameObject.transform.eulerAngles = blueSpawnPos.eulerAngles;
                    }
                    spt.gameObject.SetActive(true);
                    spt.SetPlayerInfo(userId, data[2], ulong.Parse(data[3]), false);
                    //spt.GetComponent<Camera>().cullingMask &= ~(1 << 15);
                    AddPlayers(spt);
                }
                break;
            case "StartDeduction":
                CheckRoomState();
                break;
            case "蜂群无人机":
                SpawnDevice(wrjDrag.prefabItem, data);
                break;
            case "地面无线电干扰":
                SpawnDevice(wxdDrag.prefabItem, data);
                break;
            case "探测雷达":
                SpawnDevice(ldDrag.prefabItem, data);
                break;
            case "激光火控平台":
                SpawnDevice(hpDrag.prefabItem, data);
                break;
            case "频谱探测":
                SpawnDevice(ppDrag.prefabItem, data);
                break;
            case "微波武器":
                SpawnDevice(wbDrag.prefabItem, data);
                break;
            case "Stop":
                GlobalFlag.isStartRehearsing = false;
                for (int i = 0; i < DeviceManager.Instance.devices.Count; i++)
                {
                    DeviceManager.Instance.devices[i].isStartRehearsing = false;
                }

                break;
            case "EndDeduction":
                GlobalFlag.isStartRehearsing = false;
                for (int i = 0; i < DeviceManager.Instance.devices.Count; i++)
                {
                    DeviceManager.Instance.devices[i].isStartRehearsing = false;
                }
                break;
            case "offline":

                break;
            default:
                break;

        }
    }


    public async void CheckRoomState()
    {
        RoomState roomState = await AsyncWebReq.Post<RoomState>(Url_UpdateRoomState + GlobalFlag.roomID + "&state=1", null);

        Debug.Log($"<color=red>GamemanagerRoomState={ roomState.message}</color>");
        if (roomState.message == "success")
        {
            GlobalFlag.isStartRehearsing = true;
            for (int i = 0; i < DeviceManager.Instance.devices.Count; i++)
            {
                DeviceManager.Instance.devices[i].isStartRehearsing = true;
            }
            if (GlobalFlag.currentUser.role_code == "04")
            {
                currentSpt.GetComponent<Camera>().cullingMask = -1;
                currentSpt.GetComponent<Camera>().cullingMask &= ~(1 << 15);
            }
        }
    }


    //}
    /// <summary>
    /// 获取别的客户端生成得设备
    /// </summary>
    /// <param name="devicePrefab"></param>
    /// <param name="data"></param>
    /// <param name="deviceID"></param>
    public async void SpawnDevice(GameObject devicePrefab = null, string[] deviceInfo = null)
    {
        DeviceData deviceData = await AsyncWebReq.Get<DeviceData>(Url_QueryPracticeDevice + GlobalFlag.roomID + "&PracticeSubjectId=" + GlobalFlag.practiceSubjectID);
        if (devicePrefab != null && deviceInfo != null)
        {
            for (int i = 0; i < deviceData.data.Count; i++)
            {
                if (deviceData.data[i].id == deviceInfo[7])
                {
                    SpawnDevice(devicePrefab, deviceData.data[i], deviceInfo);
                }
            }
        }
        else
        {
            for (int i = 0; i < deviceData.data.Count; i++)
            {
                switch (deviceData.data[i].device_name)
                {
                    case "蜂群无人机":
                        SpawnDevice(wrjDrag.prefabItem, deviceData.data[i]);
                        break;
                    case "地面无线电干扰":
                        SpawnDevice(wxdDrag.prefabItem, deviceData.data[i]);
                        break;
                    case "探测雷达":
                        SpawnDevice(ldDrag.prefabItem, deviceData.data[i]);
                        break;
                    case "激光火控平台":
                        SpawnDevice(hpDrag.prefabItem, deviceData.data[i]);
                        break;
                    case "频谱探测":
                        SpawnDevice(ppDrag.prefabItem, deviceData.data[i]);
                        break;
                    case "微波武器":
                        SpawnDevice(wbDrag.prefabItem, deviceData.data[i]);
                        break;
                }
            }
        }

    }

    public void SpawnDevice(GameObject obj, AdamThinkDevicesData.DataItem data, string[] tran = null)
    {
        GameObject device = Instantiate(obj);
        if (tran != null)
        {
            device.transform.position = new Vector3(float.Parse(tran[1]), float.Parse(tran[2]), float.Parse(tran[3]));
            device.transform.eulerAngles = new Vector3(float.Parse(tran[4]), float.Parse(tran[5]), float.Parse(tran[6]));
        }
        else
        {
            string[] deviceTran = data.r1.Split(',');

            device.transform.position = new Vector3(float.Parse(deviceTran[0]), float.Parse(deviceTran[1]), float.Parse(deviceTran[2]));
            device.transform.eulerAngles = new Vector3(float.Parse(deviceTran[3]), float.Parse(deviceTran[4]), float.Parse(deviceTran[5]));
        }
        if (!string.IsNullOrEmpty(data.r2) || data.r2 != "")
        {
            int wrjModelCount = int.Parse(data.r2);
            UnmannedAerialVehicleManage uavm = device.GetComponent<UnmannedAerialVehicleManage>();
            if (uavm)
            {
                uavm.wrjModel = (WRJModel)wrjModelCount;
                device.name = uavm.wrjModel.ToString();
            }
        }

        Debug.Log($"<color=yellow>是否是player{data.r3 == GlobalFlag.currentUser.user_id}</color>");
        device.GetComponent<EquipmentCommon>().FillInTheData(data.list_para);
        device.GetComponent<EquipmentCommon>().deviceID = data.id;
        if (data.r3 == GlobalFlag.currentUser.user_id)
        {
            device.GetComponent<EquipmentCommon>().isPlayer = true;
        }
        if (device.GetComponent<UnmannedAerialVehicleManage>())
            device.GetComponent<UnmannedAerialVehicleManage>().SetTipsColor();
    }

    private void OnGetRoomUsers(string obj)
    {
        if (!string.IsNullOrWhiteSpace(obj))
        {
            string[] data = obj.Split(';');
            for (int i = 0; i < data.Length; i++)
            {
                int index = i;
                string[] userInfo = data[index].Split(',');
                if (!userIds.Contains(ulong.Parse(userInfo[0])))
                {
                    SyncPlayerTransform spt = Instantiate(playerTransformPrefab);
                    //0 red  1 blue
                    if (UIBootstrap.Instance.GetRoleByIDPracticeId(GlobalFlag.practiceSeatId) == "0")
                    {
                        spt.gameObject.transform.position = redSpawnPos.position;
                        spt.gameObject.transform.eulerAngles = redSpawnPos.eulerAngles;
                    }
                    else
                    {
                        spt.gameObject.transform.position = blueSpawnPos.position;
                        spt.gameObject.transform.eulerAngles = blueSpawnPos.eulerAngles;
                    }
                    spt.SetPlayerInfo(ulong.Parse(userInfo[0]), userInfo[1], ulong.Parse(userInfo[2]), false);
                    spt.gameObject.SetActive(true);
                    AddPlayers(spt);
                }
            }
        }
        //Debug.Log($"<color=yellow>OnGetRoomUsers={obj}</color>");
        SpawnDevice();
        string msg = $"send2room online,{ulong.Parse(GlobalFlag.currentUser.user_id)},{GlobalFlag.currentUser.login_name},{ulong.Parse(GlobalFlag.roomID)}";
        _ = SyncCreateRoom.SendMessageAsync(msg);
    }



    public void SetWeatherValue()
    {
        SenceInfo currentSceneInfo = new SenceInfo();
        currentSceneInfo = UIBootstrap.Instance.currentSceneInfo.data;
        tenkokuModule.weather_RainAmt = Mathf.Lerp(0f, 1f, float.Parse(currentSceneInfo.EnvRain));
        tenkokuModule.weather_SnowAmt = Mathf.Lerp(0f, 1f, float.Parse(currentSceneInfo.EnvSnow));
        tenkokuModule.weather_WindAmt = Mathf.Lerp(0f, 1f, float.Parse(currentSceneInfo.EnvWindSpeed));
        tenkokuModule.weather_WindDir = Mathf.Lerp(0f, 360f, float.Parse(currentSceneInfo.EnvWindDir));
        tenkokuModule.weather_OvercastAmt = Mathf.Lerp(0f, 1f, 1 - (float.Parse(currentSceneInfo.EnvLight) / 10));
        tenkokuModule.weather_humidity = Mathf.Lerp(0f, 1f, 1 - (float.Parse(currentSceneInfo.EnvWu) / 100));
    }



    public void SetModelValue()
    {
        string info = UIBootstrap.Instance.currentSceneInfo.data.DeviceContent;
        //Debug.Log(info);
        if (info.Length > 0 && !string.IsNullOrWhiteSpace(info))
        {
            modelsInfo = Jsonanalyze.FromJson<List<ModelInfo>>(info);
            for (int i = 0; i < modelsInfo.Count; i++)
            {
                GameObject obj = Resources.Load<GameObject>(modelsInfo[i].str);
                GameObject go = Instantiate(obj);
                go.transform.position = new Vector3(float.Parse(modelsInfo[i].x.ToString()), float.Parse(modelsInfo[i].y.ToString()), float.Parse(modelsInfo[i].z.ToString()));
            }
        }
    }



    private void OnDisable()
    {
        Debug.Log("OnDisable GameManager");
        Leaverroom();
    }



    private void Leaverroom()
    {
        SyncCreateRoom.getroomusersRequset -= OnGetRoomUsers;
        SyncCreateRoom.send2roomRequset -= OnRoomInfo;
        //string _msg = "leaveroom ";
        //_ = AdamSync.SyncCreateRoom.SendMessageAsync(_msg);
    }

}

[Serializable]
public class ModelInfo
{
    public string str;
    public double x;
    public double y;
    public double z;
}