using System;
using System.Collections;
using NBC;
using UnityEngine;

namespace NBF
{
    public class FPlayerUseGear : MonoBehaviour
    {
        /// <summary>
        /// 可用的
        /// </summary>
        public bool Usable { get; private set; }

        public int UseGearId { get; private set; }
        public FPlayer Player { get; set; }

        public FRod Rod;
        public FReel Reel;
        public FHook Hook;
        public FFloat Bobber;
        public FBait Bait;
        public FLure Lure;
        public FWeight Weight;
        public FLine Line;


        public Transform GearParent { get; private set; }

        private void Start()
        {
            Player = GetComponentInParent<FPlayer>();
            var obj = new GameObject(Player.Data.PlayerID.ToString());
            GearParent = obj.transform;
            GearParent.SetParent(SceneSettings.Instance.GearNode);
            GearParent.localPosition = Vector3.zero;
            GearParent.position = Player.transform.position;
        }

        public void Update()
        {
            if (CheckGear())
            {
                StartCoroutine(CreateOrHideGear());
            }
        }

        private bool CheckGear()
        {
            var nowGearId = 0;
            if (Player != null && Player.Data != null && Player.Data.currentGear != null)
            {
                nowGearId = Player.Data.currentGear.GetUnitId();
            }

            if (UseGearId != nowGearId)
            {
                UseGearId = nowGearId;
                return true;
            }

            return false;
        }


        public IEnumerator CreateOrHideGear()
        {
            if (Player.PlayerAnimatorCtrl.ItemInHands)
            {
                Player.PlayerAnimatorCtrl.ItemInHands = false;
            }

            if (Rod != null)
            {
                yield return HideGear();
            }

            yield return new WaitForSeconds(0.1f);
            if (Player.Data == null || Player.Data.currentGear == null) yield break;

            var parent = GearParent;
            parent.position = Player.transform.position;

            var data = Player.Data.currentGear;
            var rodConfig = data.rod.Config;
            var cloneObj = rodConfig.Instantiate(parent, Vector3.zero, Player.MainArm.RodContainer.rotation);
            if (cloneObj == null)
            {
                yield break;
            }

            Rod = cloneObj.GetComponent<FRod>();
            if (Rod == null)
            {
                Rod = cloneObj.AddComponent<FRod>();
            }


            if (Rod)
            {
                Rod.transform.localPosition = Vector3.zero;
                Rod.transform.rotation = Player.MainArm.RodContainer.rotation;

                if (rodConfig.ring > 0)
                {
                    var ringConfig = GameRings.Get(rodConfig.ring);
                    var ringObject = ringConfig.Instantiate(Rod.transform);
                    ringObject.SetActive(false);
                    Rod.SetRing(ringObject.GetComponent<RodRingAsset>());
                }
            }
            else
            {
                yield break;
            }

            if (data.line != null)
            {
                var linePrefab = data.line.Config.Instantiate(parent);
                Line = linePrefab.GetComponent<FLine>();
            }

            if (data.reel != null)
            {
                var reelPrefab = data.reel.Config.Create(parent);
                Reel = reelPrefab.GetComponent<FReel>();
            }

            if (data.bobber != null)
            {
                var bobberPrefab = data.bobber.Config.Create(parent);
                Bobber = bobberPrefab.GetComponent<FFloat>();
            }

            if (data.hook != null)
            {
                var hookPrefab = data.hook.Config.Create(parent);
                Hook = hookPrefab.GetComponent<FHook>();
            }

            if (data.bait != null)
            {
                var baitPrefab = data.bait.Config.Create(parent);

                if (baitPrefab.TryGetComponent<FBait>(out var bait))
                {
                    Bait = bait;
                }
            }

            if (data.lure != null)
            {
                var baitPrefab = data.lure.Config.Create(parent);
                if (baitPrefab.TryGetComponent<FLure>(out var lure))
                {
                    Lure = lure;
                }
            }


            if (data.weight != null)
            {
                var weightPrefab = data.weight.Config.Instantiate(parent);
                Weight = weightPrefab.GetComponent<FWeight>();
            }

            Debug.LogError("CreateOrHideGear");
            yield return 1;
            Rod.Initialize(Player, data.rod);
            Rod.CreateFishingHandler();

            if (Line)
            {
                Line.Initialize(Player, data.line);


                if ((bool)Rod.lineHandler.obiRopeSegment_1)
                {
                    Rod.lineHandler.obiRopeSegment_1.GetComponent<MeshRenderer>().material =
                        Line.lineMat;
                }

                if ((bool)Rod.lineHandler.obiRopeSegment_2)
                {
                    Rod.lineHandler.obiRopeSegment_2.GetComponent<MeshRenderer>().material =
                        Line.lineMat;
                }

                if ((bool)Rod.lineHandler.obiRopeSegment_3)
                {
                    Rod.lineHandler.obiRopeSegment_3.GetComponent<MeshRenderer>().material =
                        Line.lineMat;
                }
            }

            if (Reel)
            {
                // Reel.maxReelStrength = data.reel.Config.strength;
                // Reel.reelingSpeed = 0.5f; //slotsEquip.reel.currentSpeed;
                Reel.reelingDrag = 0.699f; //slotsEquip.reel.currentDrag;
                Reel.transform.SetParent(Rod.rodAsset.ReelConnector);
                Reel.transform.localPosition = Vector3.zero;
                Reel.transform.localEulerAngles = Vector3.zero;
                // Reel.reelAsset.szpulaObject.GetComponent<MeshRenderer>().material = Line.szpulaMat;
                Reel.Initialize(Player, data.reel);
            }

            if (Bobber)
            {
                Bobber.floatDisplacement = data.bobber.Config.displacement;
                // if ((double)slotsEquip.ffloat.lastSetGroundValue > 0.2)
                // {
                //     Bobber.newDeepth = slotsEquip.ffloat.lastSetGroundValue;
                // }

                Bobber.newDeepth = 0.5f;

                Bobber.Initialize(Player, data.bobber);
                Bobber.transform.position = Rod.lineHandler.LineConnector_1.transform.position;
                Bobber.gameObject.GetComponent<ConfigurableJoint>().connectedBody =
                    Rod.lineHandler.LineConnector_1.GetComponent<Rigidbody>();
            }


            if (Hook)
            {
                Hook.Initialize(Player, data.hook);

                Hook.transform.position = Rod.lineHandler.LineConnector_2.transform.position;
                Hook.transform.rotation = Rod.lineHandler.LineConnector_2.transform.rotation; // 确保旋转也同步
                var target = Rod.lineHandler.LineConnector_2.GetComponent<Rigidbody>();
                var joint = Hook.gameObject.GetComponent<ConfigurableJoint>();
                // // 关键设置：关闭自动锚点计算，手动设置锚点
                // joint.autoConfigureConnectedAnchor = false;
                // joint.anchor = Vector3.zero; // 以 Hook 自身中心为锚点
                // joint.connectedAnchor = Vector3.zero; // 以目标物体的中心为锚点
                joint.connectedBody = target;
                // // 强制物理引擎立即更新变换（避免1帧延迟）
                // Physics.SyncTransforms();
                // joint.autoConfigureConnectedAnchor = false;
                // joint.anchor = Vector3.zero;
                // joint.connectedAnchor = Vector3.zero;
                Rod.LureHookWaterDisplacement = Hook.GetComponent<FWaterDisplacement>();
            }

            if (Bait)
            {
                Bait.Initialize(Player, data.bait);
                Bait.transform.position = Hook.hookAsset.baitConnector.position;
                Bait.transform.SetParent(Hook.hookAsset.baitConnector);
            }

            if (Lure)
            {
                Lure.Initialize(Player, data.bait);
                Lure.transform.position = Rod.lineHandler.LineConnector_1.transform.position;
                Lure.gameObject.GetComponent<ConfigurableJoint>().connectedBody =
                    Rod.lineHandler.LineConnector_1.GetComponent<Rigidbody>();
                Rod.LureHookWaterDisplacement = Lure.GetComponent<FWaterDisplacement>();
            }

            if (Weight)
            {
                Weight.weight = data.weight.Config.weight;
                Weight.Initialize(Player, data.weight);
            }
            // Player.PlayerAnimatorCtrl.ItemInHands = true;

            Player.PlayerAnimatorCtrl.ItemInHands = true;
            Player.PlayerAnimatorCtrl.ThrowMode = ThrowModeEnum.Spin;
            Player.PlayerAnimatorCtrl.ItemType = HandItemType.SpinRod;
            if (data.Type == GearType.Pole)
            {
                Player.PlayerAnimatorCtrl.ItemType = HandItemType.HandRod;
                Player.PlayerAnimatorCtrl.ThrowMode = ThrowModeEnum.Float;
            }

            yield return 1; //等待1帧
            Rod.transform.SetParent(Player.MainArm.RodContainer);
            Rod.transform.localPosition = Vector3.zero;
            Rod.transform.rotation = Player.MainArm.RodContainer.rotation;
            // yield return 1; //等待1帧
            // Rod.lineHandler.SetStartPosition();
            // yield return 5; //等待1帧
            // Rod.lineHandler.SetStartPosition2();
            Usable = true;
        }

        public IEnumerator HideGear()
        {
            Usable = false;

            yield return new WaitForSeconds(0.5f);
            DestroyGear();
        }

        private void DestroyGear()
        {
            if (Rod != null)
            {
                if (Rod.lineHandler != null)
                {
                    Destroy(Rod.lineHandler.gameObject);
                }

                Destroy(Rod.gameObject);
            }

            if (Reel != null)
            {
                Destroy(Reel.gameObject);
            }

            if (Hook != null)
            {
                Destroy(Hook.gameObject);
            }

            if (Bobber != null)
            {
                Destroy(Bobber.gameObject);
            }

            if (Bait != null)
            {
                Destroy(Bait.gameObject);
            }

            if (Lure != null)
            {
                Destroy(Lure.gameObject);
            }

            if (Weight != null)
            {
                Destroy(Weight.gameObject);
            }

            if (Line != null)
            {
                Destroy(Line.gameObject);
            }
        }
    }
}