using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

namespace DuckHunter
{
    public class Dog : MonoBehaviour
    {
        public static Dog Instance;
        private RectTransform _rectTransform;
        DragonBones.UnityArmatureComponent armature;
        private Transform leftHand;
        private Transform rightHand;
        private Transform[] objectInHands = { null, null, null };
        static Vector2 DefaultAanchoredPosition = Vector2.down * 100;

        void Start()
        {
            Instance = this;
            armature = GetComponentInChildren<DragonBones.UnityArmatureComponent>();
            armature.AddEventListener(DragonBones.EventObject.COMPLETE, OnAnimationEventHandler);
            _rectTransform = transform as RectTransform;
            _rectTransform.anchoredPosition = DefaultAanchoredPosition;
            PlayIdle();
            //生成左右手掌的节点，用于拿起鸭子
            var lo = new GameObject();
            lo.transform.SetParent(transform.Find("dog/shoubi3"));
            leftHand = lo.transform;
            leftHand.localPosition = new Vector3(-0.332f, 0.251f);
            var ro = new GameObject();
            ro.transform.SetParent(transform.Find("dog/shoubi4"));
            rightHand = ro.transform;
            rightHand.localPosition = new Vector3(0.332f, 0.251f);
        }

        private void OnAnimationEventHandler(string type, DragonBones.EventObject eventObject)
        {
            // PlayIdle();
            // Debug.Log(string.Format("animationName:{0},eventType:{1},eventName:{2}", eventObject.animationState.name, type, eventObject.name));
        }

        void OnDestroy()
        {
            if (Instance == this) Instance = null;
        }

        void Update()
        {
            if (objectInHands[0]) objectInHands[0].position = leftHand.position;
            if (objectInHands[1]) objectInHands[1].position = rightHand.position;
        }

        void PlayIdle()
        {
            PlayAnimation("idle");
        }

        void PlayChaoFeng()
        {
            PlayAnimation("chaofeng");
        }

        void PlayKaiXin()
        {
            PlayAnimation("kaixin");
        }

        string _lastAnimationName = null;
        void PlayAnimation(string animationName)
        {
            if (animationName == _lastAnimationName) return;
            _lastAnimationName = animationName;
            if (animationName == "idle")
            {
                armature.animation.GotoAndStopByProgress("chaofeng", 0);
                return;
            }
            if (animationName == "chaofeng")
            {
                armature.animation.Play(animationName, 0);
                AudioManager.Instance.PlayDogTaunt(gameObject);
            }
            if (animationName == "kaixin")
            {
                armature.animation.Play(animationName, 0);
                AudioManager.Instance.PlayDogHappy(gameObject);
            }
        }

        [System.NonSerialized] public bool isShowing = false;
        void Show()
        {
            isShowing = true;


            Vector3 myPos = _rectTransform.position;
            float topPointY = transform.parent.Find("TopCenterPoint").position.y;
            RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(myPos.x, topPointY), Vector2.down);
            foreach (var item in hits)
            {
                if (item.collider.name == "BottomCollider")
                {
                    _rectTransform.position = new Vector2(_rectTransform.position.x, item.point.y);
                    break;
                }
            }
            _rectTransform.anchoredPosition += Vector2.down * 170;
            float startAnchoredPositionY = _rectTransform.anchoredPosition.y;

            //_rectTransform.anchoredPosition = new Vector2(_rectTransform.anchoredPosition.x, 30);
            Sequence sequence = DOTween.Sequence();
            sequence.Append(_rectTransform.DOAnchorPosY(startAnchoredPositionY + 145, 0.5f));
            sequence.AppendInterval(0.5f);
            sequence.Append(_rectTransform.DOAnchorPosY(startAnchoredPositionY, 0.5f));
            sequence.AppendCallback(() =>
            {
                isShowing = false;
                if (_lastAnimationName == "kaixin") ClearObjectInHands();
                _rectTransform.anchoredPosition = DefaultAanchoredPosition;
                PlayIdle();
            });
        }

        int _handleDuckCount = 0;
        bool _needKaixin = false;
        public void OnEvent(SensitiveEventType eventType, params object[] args)
        {
            _handleDuckCount++;
            if (eventType == SensitiveEventType.DuckHit)
            {
                _needKaixin = true;

                Duck duck = args[0] as Duck;
                AddDuckToHands(duck);
                //把狗弄到鸟下落的位置
                _rectTransform.position = new Vector2(duck.transform.position.x, 0);
                //避免狗太靠边
                //Vector3 lc = _rectTransform.localPosition;
                //float pw = (_rectTransform.parent as RectTransform).rect.width;
                //float minX = -pw / 2 + 200;
                //float maxX = pw / 2 - 200;
                //if (lc.x < minX) lc.x = minX;
                //else if (lc.x > maxX) lc.x = maxX;
                //_rectTransform.localPosition = lc;

                float xMin =  _rectTransform.parent.Find("DogSideL").position.x;
                float xMax = _rectTransform.parent.Find("DogSideR").position.x;
                _rectTransform.position = new Vector2(Mathf.Clamp(_rectTransform.position.x, xMin, xMax), _rectTransform.position.y);
            }
            else if (eventType == SensitiveEventType.DuckGetAway)
            {

            }

            if (_handleDuckCount == GameManager.Instance.theDuckCountWaitingForDogHandle)
            {
                GameManager.Instance.theDuckCountWaitingForDogHandle = _handleDuckCount = 0;
                if (_needKaixin)
                {
                    _needKaixin = false;
                    PlayKaiXin();
                    Show();
                }
                else
                {
                    PlayChaoFeng();
                    Show();
                }
            }
        }

        void AddDuckToHands(Duck duck)
        {
            for (int i = 0; i < objectInHands.Length; i++)
            {
                if (objectInHands[i]) continue;
                objectInHands[i] = duck.transform;
                duck.PlayDeadForDogHand(i == 0 ? -1 : 1);
                break;
            }
        }
        void ClearObjectInHands()
        {
            for (int i = 0; i < objectInHands.Length; i++)
            {
                if (!objectInHands[i]) continue;
                if (objectInHands[i].gameObject) Destroy(objectInHands[i].gameObject);
                objectInHands[i] = null;
            }
        }

        public enum SensitiveEventType
        {
            DuckHit,
            DuckGetAway,
        }
    }
}
