using DG.Tweening;
using UnityEngine;
using XGame.Framework.Interfaces;

namespace FL.Battle.Vfxs
{
    internal class VfxActionMove : IVfxAction
    {
        public Vector3 from;
        public Vector3 to;
        /// <summary>
        /// 单位:毫秒
        /// </summary>
        public int duration;
        private Tween _tween;

        void IReference.Clear()
        {
            _tween?.Kill();
            _tween = null;
        }
        public void Start(Transform transform, bool isFoword, System.Action callback)
        {
            //transform.DOPlayForward();
            // 贝塞尔曲线运动
            transform.position = from;
            var timeScale = Random.Range(0.2f, 0.8f);
            var linePoint = Vector3.Lerp(from, to, timeScale);
            var dir = Vector3.Cross(to - from, Vector3.forward).normalized; //运动方向的法线
            // 沿Y轴上下运动时算出来z值为零，直接把x值赋值给z进行偏移
            if (dir.z == 0)
                dir.z = dir.x;
            var disOffset = Random.Range(-3f, 3f);
            var center = linePoint + dir * disOffset;
            var totalTime = duration * 0.001f;
            var timeTween = DOTween.To(() => 0, (t) =>
            {
                var tNormal = t / totalTime;
                transform.position = from.BezierPoint(center, to, tNormal);
                if (isFoword)
                {
                    var tempDir = (to - transform.position).normalized;
                    var rot = Vector3.zero;
                    rot.z = Vector3.Angle(tempDir, Vector3.up);
                    transform.localEulerAngles = rot;
                    //if (tempDir != Vector3.zero)
                    //{
                    //    transform.forward = tempDir;
                    //}
                }
            }, totalTime, totalTime);
            timeTween.SetEase(Ease.OutQuad);
            _tween = timeTween;
            timeTween.onComplete = () =>
            {
                _tween = null;
                callback?.Invoke();
            };
        }
        void IVfxAction.Start(Transform transform)
        {
            Start(transform, true, null);
        }
    }
}
