using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace WS
{
    [ObjectSystem]
    public class MapControllerUpdateSystem : UpdateSystem<MapController>
    {
        public override void Update(MapController self)
        {
            //正面布局
            if (FacadeComponent.Instance.GetController<MapController>() != null)
            {
                self.playerPos = Player.Inst.transform.position;
                float angle = Mathf.DeltaAngle(
                    self.VRCameraRotY,
                    Player.Inst.hmdTransform.localEulerAngles.y
                );
                float num = Mathf.Abs(angle) / self.angle;
                if (num > 1)
                {
                    self.VRCameraRotY += (int)num * 2 * self.angle * Mathf.Sign(angle);
                    if (self.VRCameraRotY > 360)
                    {
                        self.VRCameraRotY -= 360;
                    }
                    Vector3 uiToPlayer = self.GetUITranfrom().position - self.playerPos;
                    self.startDir =
                        Quaternion.Euler(0, Mathf.Sign(angle) * 2 * self.angle, 0) * uiToPlayer;
                    self.uiRot = Quaternion.Euler(
                        70,
                        self.GetUITranfrom().rotation.eulerAngles.y
                            + 2 * self.angle * Mathf.Sign(angle),
                        0
                    );
                }
                else
                {
                    if (self.startRotY != Player.Inst.transform.localEulerAngles.y)
                    {
                        self.GetUITranfrom().LookAt(self.playerPos);
                        float angleValue = Mathf.DeltaAngle(
                            self.startRotY,
                            Player.Inst.transform.localEulerAngles.y
                        );
                        self.startDir = Quaternion.Euler(0, angleValue, 0) * self.startDir;
                        float uiAngle = self.uiRot.eulerAngles.y + angleValue;
                        if (uiAngle >= 180)
                        {
                            uiAngle -= 360;
                        }
                        self.uiRot = Quaternion.Euler(new Vector3(70, uiAngle, 0));
                        self.startRotY = Player.Inst.transform.localEulerAngles.y;
                    }
                    else
                    {
                        self.uiRot = self.GetUITranfrom().localRotation;
                    }
                }
                self.uiPos = self.startDir + self.playerPos;
                self.SetViewPos(self.uiPos / self.canvasScale, self.uiRot);
            }
        }
    }

    public class MapController : Controller<MapView, MapModel>
    {
        /// <summary> 限制角度 </summary>
        public float angle = 90;

        /// <summary> VR相机Y轴旋转 </summary>
        public float VRCameraRotY;

        /// <summary> Y轴距离 </summary>
        public float uiDistanceY = 380;

        /// <summary> Z轴距离 </summary>
        public float uiDistanceZ = 450;

        /// <summary> ui到玩家的向量 </summary>
        public Vector3 startDir;

        /// <summary> UI位置 </summary>
        public Vector3 uiPos;

        /// <summary> UI旋转 </summary>
        public Quaternion uiRot;

        /// <summary> 画布缩放(用于计算世界坐标) </summary>
        public float canvasScale = 0.001f;

        /// <summary> 玩家位置 </summary>
        public Vector3 playerPos;

        /// <summary> 玩家初始旋转 </summary>
        public float startRotY;

        protected override void BindingViewModel()
        {
            _Model.Bind(_View.ReturnBtn, OnReturnBtnClick);
        }

        public override void OpenView()
        {
            base.OpenView();
            MapListAddListener();
            VRCameraRotY = 0;
            startRotY = 0;
            GameManager.Instance.ProcessManager.OnEndProcessCallback += OnProcessComplete;
            var playerPos = Player.Inst.transform.position;

            if (GameManager.Instance.Data.Pattern == PatternType.漫游)
            {
                _View.ReturnBtn.gameObject.SetActive(true);
                SetBtnStatus((int)Enum.Parse(typeof(SceneName), SceneComponent.Instance.ThisScene));
            }
            else
            {
                _View.ReturnBtn.gameObject.SetActive(false);
            }
            uiPos = playerPos / canvasScale + new Vector3(0, uiDistanceY, uiDistanceZ);
            uiRot = Quaternion.Euler(new Vector3(70, 0, 0));
            _View.SetPosition(uiPos, uiRot);
            startDir = _View.UIGameObject.transform.position - playerPos;
        }

        public override void Dispose()
        {
            GameManager.Instance.ProcessManager.OnEndProcessCallback += OnProcessComplete;
            base.Dispose();
        }

        private void OnReturnBtnClick()
        {
            //SceneComponent.Instance.LoadScene(
            //    SceneName.发电机层.ToString(),
            //    () =>
            //    {
            //        ChoosePopController choosePop =
            //            FacadeComponent.Instance.CreateController<ChoosePopController>();
            //        choosePop.OpenView();
            //        GameObject startPoint = GameObject.Find("StartPoint");
            //        Player.Inst.transform.position = startPoint.transform.position;
            //        Player.Inst.transform.rotation = startPoint.transform.rotation;
            //        CloseView();
            //    }
            //);
        }

        public void SetViewPos(Vector3 pos, Quaternion quaternion)
        {
            _View.SetPosition(pos, quaternion);
        }

        /// <summary> 获取UI的Transform </summary>
        public Transform GetUITranfrom()
        {
            return _View.UIGameObject.transform;
        }

        public void SetView(SceneName sceneName, UnityAction action)
        {
            _Model.OnCompleteCallBack = action;
            SetBtnStatus((int)sceneName - 1);
        }

        public void OnProcessComplete()
        {
            CloseView();
        }

        /// <summary>
        /// 设置按钮状态
        /// </summary>
        /// <param name="sceneIndex">按钮索引</param>
        public void SetBtnStatus(int sceneIndex)
        {
            var buttons = _View.MapList.GetComponentsInChildren<Button>();
            for (int i = 0; i < buttons.Length; i++)
            {
                if (GameManager.Instance.Data.Pattern != PatternType.漫游)
                {
                    buttons[i].interactable = i == sceneIndex;
                }
                buttons[i].transform.GetChild(0).gameObject.SetActive(i == sceneIndex);
            }
        }

        /// <summary> 每个按钮注册回调 </summary>
        private void MapListAddListener()
        {
            var buttons = _View.MapList.GetComponentsInChildren<Button>();

            for (int i = 0; i < buttons.Length; i++)
            {
                int index = i;
                string sceneName;
                string pointName = null;

                if (GameManager.Instance.Data.Pattern == PatternType.漫游)
                {
                    if (index == 1)
                    {
                        sceneName = WanderScene.发电机层_漫游.ToString();
                        pointName = "StartPoint_进场交通洞";
                    }
                    else
                    {
                        sceneName = Enum.GetName(typeof(WanderScene), index + 1);
                        pointName = "StartPoint";
                    }
                }
                else
                {
                    if (index == 1)
                    {
                        sceneName = SceneName.发电机层.ToString();
                    }
                    else
                    {
                        sceneName = Enum.GetName(typeof(SceneName), index + 1);
                    }
                }
                buttons[index].onClick.AddListener(async () =>
                {
                    await SceneComponent.Instance.LoadSceneAsync(sceneName);
                    Game.Scene.GetComponent<TeleportPointController>().RefreshTeleport();
                    if (GameManager.Instance.Data.Pattern == PatternType.漫游)
                    {
                        //漫游高亮
                        SetBtnStatus(index);
                        GameObject startPoint = GameObject.Find(pointName);
                        Player.Inst.transform.position = startPoint.transform.position;
                        Player.Inst.transform.rotation = startPoint.transform.rotation;
                    }
                    else
                    {
                        SceneDataSaveComponent.Instance.LoadScene(sceneName);
                        _Model.OnCompleteCallBack?.Invoke();
                        CloseView();
                    }
                });
            }
        }
    }

    public class MapView : View
    {
        public GameObject MapList;
        public Button ReturnBtn;

        public override void LoadInit()
        {
            ShowModeType = ViewShowModeType.World;
            ReferenceCollector rc = UIGameObject.GetComponent<ReferenceCollector>();
            MapList = rc.Get<GameObject>("MapList");
            ReturnBtn = rc.GetComponent<Button>("ReturnBtn");
        }
    }

    public class MapModel : Model
    {
        public UnityAction OnCompleteCallBack;

        public override void InitProperty() { }
    }
}
