using Games.Events;
using Games.Fellow;
using Games.LogicObj;
using Games.SkillModle;
using GCGame.Table;
using Module.Log;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class PetSkillButton : SkillButtonBase, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    // 技能cd数值精度 - 处理一个因为cd数值不精确导致的误判
    public const float cooldownPercision = 0.001f;

    private bool _allowInput;
    private GameObject _cdEffectClone;

    private Image _comboTimer;

    private float _cooldownRatio; // 冷却时间

    public GameObject cdEffectObj;
    public GameObject comboTimerObj;
    public Image LockImage; //技能未开启

    //技能开启需要个提示
    public int skillIndex;
    public Image skillCDImage; //技能CD蒙版
    public Image skillIcon; //技能图标

    // 当前操作技能按钮的手指Id
    public int? CurrentFingerId { get; private set; }

    public void SetSkillIndex(int SkillIndex)
    {
        skillIndex = SkillIndex;
        Fellow fellow = GameManager.gameManager.PlayerDataPool.FellowContainer.GetRealFightPet();
        if (fellow == null)
        {
            Clear();
            return;
        }
        OwnSkillData ownSkillData = fellow.GetSkillData(SkillIndex);
        if (ownSkillData == null || ownSkillData.IsValid() == false)
        {
            Clear();
            return;
        }

        LockImage.gameObject.SetActive(false);
        skillIcon.gameObject.SetActive(true);
        LoadAssetBundle.Instance.SetImageSprite(skillIcon, ownSkillData.ComboBaseTable.Icon);
    }

    public bool AllowInput
    {
        get { return _allowInput; }
        set
        {
            if (_allowInput != value)
            {
                _allowInput = value;
                CleanSkillSelect();
            }
        }
    }

    public void Clear()
    {
        comboTimerObj.SetActive(false);
        CleanSkillSelect();
        if (LockImage != null)
            LockImage.gameObject.SetActive(true);
        if (skillCDImage != null)
            skillCDImage.gameObject.SetActive(false);
        if (skillIcon != null)
            skillIcon.gameObject.SetActive(false);
    }

    private void Awake()
    {
        CurrentFingerId = null;
        _comboTimer = comboTimerObj.transform.Find("FillImage").GetComponent<Image>();
        comboTimerObj.SetActive(false);
    }

    private void Start()
    {
        EventDispatcher.Instance.Add(Games.Events.EventId.LockSkillInput, OnSkillInputUpdate);
        EventDispatcher.Instance.Add(Games.Events.EventId.ProcessInputBlock, OnProcessInputBlock);
        OnSkillInputUpdate(null);
    }

    private void OnDestroy()
    {
        EventDispatcher.Instance.Remove(Games.Events.EventId.LockSkillInput, OnSkillInputUpdate);
        EventDispatcher.Instance.Remove(Games.Events.EventId.ProcessInputBlock, OnProcessInputBlock);
    }

    private void OnSkillInputUpdate(object args)
    {
        AllowInput = GameManager.gameManager.PlayerDataPool.AllowSkillInput;
    }

    private void OnProcessInputBlock(object args)
    {
        var block = (bool)args;
        if (block)
            CleanSkillSelect();
    }

    private void Update()
    {
        if (skillIndex >= 0 && AllowInput)
        {
            Fellow fellow = GameManager.gameManager.PlayerDataPool.FellowContainer.GetRealFightPet();
            if (fellow != null)
            {
                OwnSkillData ownSkillData = fellow.GetSkillData(skillIndex);
                if (ownSkillData != null && ownSkillData.IsValid())
                {
                    ownSkillData.UpdateCombo();
                    var cdTime = ownSkillData.CurrentCooldown;
                    var totalCd = ownSkillData.Cooldown;
                    if (Mathf.Abs(cdTime) < cooldownPercision)
                        cdTime = 0f;
                    if (cdTime > 0f)
                        if (totalCd > 0)
                            SetCdRatio(cdTime / totalCd);
                        else
                            SetCdRatio(0f);
                    else
                        SetCdRatio(0f);
                }
            }
        }
    }

    private void SetCdRatio(float ratio)
    {
        // 仅在Ratio有所改变的状况下有响应
        if (_cooldownRatio != ratio)
        {
            _cooldownRatio = ratio;
            if (ratio > 0f)
            {
                skillCDImage.gameObject.SetActive(true);
                skillCDImage.fillAmount = ratio;
            }
            else
            {
                skillCDImage.gameObject.SetActive(false);
                if (_cdEffectClone == null)
                    _cdEffectClone = CloneEffectObj(cdEffectObj);
                _cdEffectClone.SetActive(true);
            }
        }
    }

    #region  点击相关的事件处理

    public void OnDrag(PointerEventData eventData)
    {

    }

    public void OnPointerDown(PointerEventData eventData)
    {
        if (skillIndex >= 0 && AllowInput && ProcessInput.Instance != null && !ProcessInput.Instance.isBlocked)
            if (CurrentFingerId == null)
            {
                var mainPlayer = Singleton<ObjManager>.GetInstance().MainPlayer;
                if (mainPlayer == null)
                {
                    LogModule.ErrorLog("MainPlayer is Null");
                }
                else
                {
                    Fellow fellow = GameManager.gameManager.PlayerDataPool.FellowContainer.GetRealFightPet();
                    if (fellow != null)
                    {
                        OwnSkillData ownSkillData = fellow.GetSkillData(skillIndex);
                        if (ownSkillData != null && ownSkillData.IsValid())
                        {
                            var castable = mainPlayer.CheckSkillCastable(ownSkillData.SkillBaseTable, ownSkillData.SkillExTable, ownSkillData.IsCooldownFinish());
                            switch (castable)
                            {
                                case SkillCastableCheckResult.Success:
                                case SkillCastableCheckResult.FailOtherSkill:
                                    CurrentFingerId = eventData.pointerId;
                                    break;
                                case SkillCastableCheckResult.FailCooldown:
                                    mainPlayer.SendNoticMsg(false, "#{1245}");
                                    break;
                                case SkillCastableCheckResult.FailSelect:
                                    mainPlayer.SendNoticMsg(false, "#{1250}");
                                    break;
                            }
                        }
                    }
                }
            }
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (LockImage.gameObject.activeSelf)
        {
            GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{20172}"));
        }

        if (CurrentFingerId == eventData.pointerId)
        {
            CurrentFingerId = null;
            if (skillIndex >= 0)
            {
                Fellow fellow = GameManager.gameManager.PlayerDataPool.FellowContainer.GetRealFightPet();
                if (fellow != null)
                {
                    OwnSkillData ownSkillData = fellow.GetSkillData(skillIndex);
                    if (ownSkillData != null && ownSkillData.IsValid())
                    {
                        var mainPlayer = Singleton<ObjManager>.Instance.MainPlayer;
                        if (mainPlayer != null)
                            if (mainPlayer.IsDisableControl())
                            {
                                //组队跟随,不响应技能报错
                                if (GameManager.gameManager.PlayerDataPool.IsFollowTeam)
                                    GUIData.AddNotifyData(StrDictionary.GetClientDictionaryString("#{5128}"));
                                // 暂时没有混乱中报错的机制
                            }
                            else
                            {
                                CG_PET_USESKILL cG_PET_USESKILL = (CG_PET_USESKILL)PacketDistributed.CreatePacket(MessageID.PACKET_CG_PET_USESKILL);
                                cG_PET_USESKILL.SetSkillId(ownSkillData.SkillId);
                                cG_PET_USESKILL.SetPosX(-1);
                                cG_PET_USESKILL.SetPosZ(-1);
                                cG_PET_USESKILL.SetTargetId(-1);
                                cG_PET_USESKILL.SendPacket();
                                //ChangeSkill();
                            }
                    }
                }
            }
        }
    }

    private void ChangeSkill()
    {
        var nextIndex = skillIndex == 0 ? 1 : 0;
        Fellow fellow = GameManager.gameManager.PlayerDataPool.FellowContainer.GetRealFightPet();
        if (fellow == null)
            return;
        OwnSkillData ownSkillData = fellow.GetSkillData(nextIndex);
        if (ownSkillData == null || ownSkillData.IsValid() == false)
            return;
        SetSkillIndex(nextIndex);
    }

    /// <summary>
    ///     强制停止当前使用中的技能
    /// </summary>
    private void CleanSkillSelect()
    {
        if (CurrentFingerId != null)
        {
            CurrentFingerId = null;
        }
    }

    #endregion
}