using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace Tiobon.Core.Common.Helper;

public class StringHelper
{
    /// <summary>
    /// 根据分隔符返回前n条数据
    /// </summary>
    /// <param name="content">数据内容</param>
    /// <param name="separator">分隔符</param>
    /// <param name="top">前n条</param>
    /// <param name="isDesc">是否倒序（默认false）</param>
    /// <returns></returns>
    public static List<string> GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false)
    {
        if (string.IsNullOrEmpty(content))
        {
            return new List<string>() { };
        }

        if (string.IsNullOrEmpty(separator))
        {
            throw new ArgumentException("message", nameof(separator));
        }

        var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray();
        if (isDesc)
        {
            Array.Reverse(dataArray);
        }

        if (top > 0)
        {
            dataArray = dataArray.Take(top).ToArray();
        }

        return dataArray.ToList();
    }
    /// <summary>
    /// 根据字段拼接get参数
    /// </summary>
    /// <param name="dic"></param>
    /// <returns></returns>
    public static string GetPars(Dictionary<string, object> dic)
    {

        StringBuilder sb = new StringBuilder();
        string urlPars = null;
        bool isEnter = false;
        foreach (var item in dic)
        {
            sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}");
            isEnter = true;
        }
        urlPars = sb.ToString();
        return urlPars;
    }
    /// <summary>
    /// 根据字段拼接get参数
    /// </summary>
    /// <param name="dic"></param>
    /// <returns></returns>
    public static string GetPars(Dictionary<string, string> dic)
    {

        StringBuilder sb = new StringBuilder();
        string urlPars = null;
        bool isEnter = false;
        foreach (var item in dic)
        {
            sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}");
            isEnter = true;
        }
        urlPars = sb.ToString();
        return urlPars;
    }
    /// <summary>
    /// 获取一个GUID
    /// </summary>
    /// <param name="format">格式-默认为N</param>
    /// <returns></returns>
    public static string GetGUID(string format = "N")
    {
        return Guid.NewGuid().ToString(format);
    }
    /// <summary>  
    /// 根据GUID获取19位的唯一数字序列  
    /// </summary>  
    /// <returns></returns>  
    public static long GetGuidToLongID()
    {
        byte[] buffer = Guid.NewGuid().ToByteArray();
        return BitConverter.ToInt64(buffer, 0);
    }
    /// <summary>
    /// 获取字符串最后X行
    /// </summary>
    /// <param name="resourceStr"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    public static string GetCusLine(string resourceStr, int length)
    {
        string[] arrStr = resourceStr.Split("\r\n");
        return string.Join("", (from q in arrStr select q).Skip(arrStr.Length - length + 1).Take(length).ToArray());
    }
    #region 求系统唯一字符串
    /// <summary>
    /// 求系统唯一字符串，常用于ROW_ID值。
    /// </summary>
    /// <returns>字符串</returns>
    public static string GetSysID()
    {
        string sid = string.Empty;

        byte[] buffer = Guid.NewGuid().ToByteArray();
        sid = DateTime.Now.ToString("yyMMddHHmmss") + BitConverter.ToInt64(buffer, 0).ToString();
        return sid;
    }
    #endregion

    #region 格式化数字字符
    /// <summary>
    /// 格式化数字字符，如传入1.24500，返回1.245
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string TrimDecimalString(string value)
    {
        try
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(value))
            {
                Decimal tmp = Decimal.Parse(value);
                result = string.Format("{0:#0.##########}", tmp);
            }
            return result;
        }
        catch (Exception)
        {
            throw;
        }
    }

    public static string TrimDecimalString(decimal value)
    {
        return TrimDecimalString(value.ToString());
    }
    public static string TrimDecimalString(decimal? value)
    {
        if (value is null) return "";
        return TrimDecimalString(value.ToString());
    }
    /// <summary>
    /// 格式化数字字符，并保留指定的小数位
    /// </summary>
    /// <param name="value">需要处理的值</param>
    /// <param name="reservedDigit">保留小数点后位数</param>
    /// <returns></returns>
    public static string TrimDecimalString(string value, int reservedDigit)
    {
        try
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(value))
            {
                Decimal tmp = Decimal.Parse(value);
                if (reservedDigit == -1)
                    result = string.Format("{0:#0.##########}", tmp);
                else
                {
                    result = String.Format("{0:N" + reservedDigit.ToString() + "}", tmp);
                    result = result.Replace(",", "");
                }
            }
            return result;
        }
        catch (Exception) { throw; }
    }

    /// <summary>
    /// 格式化数字字符，并保留指定的小数位
    /// </summary>
    /// <param name="value">需要处理的值</param>
    /// <param name="reservedDigit">保留小数点后位数，-1时只会去除小数点后最后几位的0</param>
    /// <returns></returns>
    public static string TrimDecimalString(object value, int reservedDigit)
    {
        try
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(Convert.ToString(value)))
            {
                Decimal tmp = Decimal.Parse(Convert.ToString(value));
                if (reservedDigit == -1)
                    result = string.Format("{0:#0.##########}", tmp);
                else
                {
                    result = String.Format("{0:N" + reservedDigit.ToString() + "}", tmp);
                    result = result.Replace(",", "");
                }
            }
            return result;
        }
        catch (Exception) { throw; }
    }

    /// <summary>
    /// 格式化数字字符，并保留指定的小数位
    /// </summary>
    /// <param name="value">需要处理的值</param>
    /// <param name="reservedDigit">保留小数点后位数，-1时只会去除小数点后最后几位的0</param>
    /// <returns></returns>
    public static decimal TrimDecimal(object value, int reservedDigit)
    {
        try
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(Convert.ToString(value)))
            {
                Decimal tmp = Decimal.Parse(Convert.ToString(value));
                if (reservedDigit == -1)
                    result = string.Format("{0:#0.##########}", tmp);
                else
                {
                    result = String.Format("{0:N" + reservedDigit.ToString() + "}", tmp);
                    result = result.Replace(",", "");
                }
            }
            return Convert.ToDecimal(result);
        }
        catch (Exception) { throw; }
    }
    #endregion

    #region 获取字段描述
    /// <summary>
    /// 对象字段描述
    /// </summary>
    private static Dictionary<string, Dictionary<string, string>> m_FieldDesc = new Dictionary<string, Dictionary<string, string>>();

    /// <summary>
    /// 获取字段的描述(描述 - 列名)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static Dictionary<string, string> GetFieldDesc<T>()
    {
        var type = typeof(T).ToString();
        lock (m_FieldDesc)
        {
            if (m_FieldDesc.ContainsKey(type))
                return m_FieldDesc[type];
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        try
        {
            PropertyInfo[] peroperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            if (peroperties != null)
            {
                foreach (PropertyInfo property in peroperties)
                {
                    object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (objs.Length > 0)
                    {
                        var desc = ((DescriptionAttribute)objs[0]).Description.Trim();
                        if (!dic.ContainsKey(desc))
                        {
                            dic.Add(desc, property.Name);
                        }
                        else
                        {
                            dic[desc] = property.Name;
                        }
                    }
                }
            }
        }
        catch //(Exception ex)
        {
        }
        lock (m_FieldDesc)
        {
            if (!m_FieldDesc.ContainsKey(type))
                m_FieldDesc.Add(type, dic);
        }
        return dic;
    }
    #endregion
}
