using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

namespace MPStudio
{
    public class RollingMoney : MonoBehaviour
    {
        public Text numberText; // UI Text组件
        public float duration = 1f; // 动画时长（秒）

        private long _currentIntValue = 0; // 实际存储的整数值
        private long _targetIntValue = 0;
        
        private Coroutine _rollingCoroutine;

        protected void Start()
        {
            ReadMoney();
            numberText.text = DollarFormat(_currentIntValue);
        }

        public void ReadMoney()
        {
            _currentIntValue = SaveManager.Inst.testData.money;
            _targetIntValue = _currentIntValue;
        }

        public void WriteMoney()
        {
            _targetIntValue = _currentIntValue;//有點多餘還是寫上
            SaveManager.Inst.testData.money = _currentIntValue;
            
            SaveManager.Inst.SaveTestData();
        }

        public void AddMoney(long addVal)
        {
            //long newVal = this._currentIntValue + addVal;
            this._targetIntValue += addVal;
            UpdateNumber(this._targetIntValue);//多餘了但是不影響
        }

        public bool ReduceMoney(long reduceVal)
        {
            //考虑到动态的钱不应该拿来计算呢。非动态cur和target相等，动态target是更多的。为了稳定不支持动态扣减。就是这样才不会多扣钱
            if ((this._targetIntValue - reduceVal) >= 0)
            {
                this._targetIntValue -= reduceVal;
                UpdateNumber(this._targetIntValue);
                return true;
            }
            return false;
        }

        // 外部调用此方法更新目标值
        public void UpdateNumber(long newValue)
        {
            _targetIntValue = newValue;

            // 如果已有动画在运行，先停止，這裡需要置空_rollingCoroutine嗎
            
            if (_rollingCoroutine != null)
            {
                StopCoroutine(_rollingCoroutine);
            }
            _rollingCoroutine = StartCoroutine(RollInteger());
        }
        
        public string DollarFormat(long num)
        {
            var str = string.Format("{0:N}", num);
                return str.Replace(".00", "");
        }

        IEnumerator RollInteger()
        {
            //print("start newRollInteger");
            long startValue = _currentIntValue;
            float elapsed = 0f;

            while (elapsed < duration)
            {
                elapsed += Time.deltaTime;
                // 插值计算显示值，但实际存储仍为整数
                float displayValue = Mathf.Lerp(startValue, _targetIntValue, elapsed / duration);
                numberText.text =DollarFormat(  Mathf.RoundToInt(displayValue)); // 四舍五入显示
                yield return null;
            }

            // 确保最终值精确
            _currentIntValue = _targetIntValue;
            numberText.text = DollarFormat(_currentIntValue);
            WriteMoney();
        }

        // 获取当前实际值（避免动画未结束时读取中间值）
        public long GetMoney()
        {
            return _currentIntValue;
        }
    }
}