using FL.Battle;
using FL.Battle.Vfxs;
using Spine.Unity;
using TMPro;
using UnityEngine;
using XGame.Database;
using XGame.Framework.Map;
using XGame.Framework.ObjectCollection;

namespace FL.Map
{
    public class PartnerEntityView : BattleEntityView<PartnerEntityVM>, IAttackContext, ISkillContext, ISpineContext, IVfxContext
    {
        public void FindTarget(int skillId)
        {
            EventSingle.Instance.Notify(EventDefine.GameMainMapFindTarget, new FindTargetArgs()
            {
                entityId = Entity.EntityId,
                entityType = EEntityType.Monster,
                range = Entity.Attr.AtkRange,
                skillId = skillId,
            });
        }

        #region IAttackContext
        Transform IAttackContext.ActionRoot => VM.ActionRoot;
        #endregion
        #region ISpineContext
        SkeletonAnimation ISpineContext.Skeleton => VM.Skeleton;
        #endregion
        #region IVfxContext
        Transform IVfxContext.WorldTr => null;
        Transform IVfxContext.CenterTr => VM.Tr;
        Transform IVfxContext.CastTr => VM.VfxRoot;
        #endregion
        protected override void OnStateChanged()
        {
            if (Entity.State == EEntityState.Idle)
            {
                //var random = Random.Range(0, 100) % 2;
                GetComponent<SpineComponent>().Play(ActionName.idle);
            }
            VM.NameText.text = Entity.Attr.Name;
            VM.StateText.text = Entity.State.ToString();
        }
        /// <summary>
        /// 随从的身体镜像，所有武器默认向左，玩家左边的武器镜像翻转朝右
        /// </summary>
        public void BodyMirror()
        {
            var scale = Vector3.one * PartnerTableRepo.Get(Entity.TableId).Size;
            scale.z = 1;
            if (LocalPosition.x < 0)
            {
                scale.x *= -1;
            }
            VM.Skeleton.transform.localScale = scale;
        }
    }

    public class PartnerEntityVM : EntityViewModel
    {
        public TextMeshPro NameText { get; private set; }
        public TextMeshPro StateText { get; private set; }
        public Transform ActionRoot { get; private set; }
        public SkeletonAnimation Skeleton { get; private set; }
        public Transform VfxRoot { get; private set; }
        protected override void OnInit(IObjectCollector collector)
        {
            NameText = collector.GetComponent<TextMeshPro>("NameText");
            StateText = collector.GetComponent<TextMeshPro>("StateText");
            ActionRoot = collector.GetGameObject("ActionRoot").transform;
            Skeleton = collector.GetComponent<SkeletonAnimation>("Skeleton");
            VfxRoot = collector.GetGameObject("VfxRoot").transform;
        }
    }
}
