using System;
using System.Collections.Generic;
using SGModule.Common.Helper;
using UnityEngine;
using UnityEngine.Events;

namespace SGModule.NetKit {
    public static class ErrorLogKit {
        private static readonly Dictionary<string, Dictionary<string, bool>> _statusDic = new();
        private static bool _isErrorLoggingEnabled = true;

        /// <summary>
        ///     初始化方法
        /// </summary>
        /// <param name="isErrorLoggingEnabled">是否开启错误日志上报</param>
        public static void Init(bool isErrorLoggingEnabled) {
            _isErrorLoggingEnabled = isErrorLoggingEnabled;
        }

        /// <summary>
        ///     发送错误日志
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="stackTrace"></param>
        /// <param name="attribution"></param>
        public static void Send(string level, string message, string stackTrace, string attribution = "organic") {
            if (!_isErrorLoggingEnabled) {
                return;
            }

            // 如果只需要日期部分，可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化
            var currentDate = DateTime.Now;
            var formattedDate = currentDate.ToString("yyyy_MM_dd_HH_mm");

            var md5Str = MD5Helper.GetStringMD5(message + stackTrace);

            if (!_statusDic.ContainsKey(formattedDate)) {
                _statusDic.Add(formattedDate, new Dictionary<string, bool>());
            }

            if (_statusDic[formattedDate].ContainsKey(md5Str)) {
                return;
            }

            _statusDic[formattedDate].Add(md5Str, true);

            SendLogToServer(level, message, stackTrace, attribution);
        }
        
        public static void SendDebugToServer(string error, string stackTrace = "")
        {
            Send("debug", error, stackTrace);
        }


        private static void SendLogToServer(string level, string message, string stackTrace, string attribution, UnityAction<bool> callback = null) {
            var requestData = new RespDebugData {
                Channel = attribution,
                Uid = LoginKit.Instance.LoginModel?.Uid ?? -1,
                Device = SystemInfo.deviceModel,
                OSVer = SystemInfo.operatingSystem,
                Network = GetNetworkType(),
                DeviceID = DeviceHelper.GetDeviceID(),
                PackName = Application.identifier,
                Version = Application.version,
                Level = level,
                Message = message,
                Stacktrace = stackTrace
            };

            NetKit.Instance.Post<RespDebugData>("event/cliDebugLog", requestData, response => {
                callback?.Invoke(response.IsSuccess);
            }, false);
        }

        private static string GetNetworkType() {
            return Application.internetReachability switch {
                NetworkReachability.ReachableViaCarrierDataNetwork => "Mobile Data",
                NetworkReachability.ReachableViaLocalAreaNetwork => "Wi-Fi",
                _ => "Not Connected"
            };
        }
    }
}
