using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Mall.Common
{
    /// <summary>
    /// 类型转换帮助类
    /// </summary>
    public static class ConvertHelper
    {

        /// <summary>
        /// json字符串将属性值中的英文双引号变成中文双引号
        /// </summary>
        /// <param name="strJson">json字符串</param>
        /// <returns></returns>
        public static string JsonReplaceSign(string strJson)
        {
            char[] temp = strJson.ToCharArray();
            int n = temp.Length;
            for (int i = 0; i < n; i++)
            {
                if (temp[i] == ':' && temp[i + 1] == '"')
                {
                    for (int j = i + 2; j < n; j++)
                    {
                        if (temp[j] == '"')
                        {
                            if (temp[j + 1] != ',' && temp[j + 1] != '}')
                            {
                                temp[j] = '”';
                            }
                            else if (temp[j + 1] == ',' || temp[j + 1] == '}')
                            {
                                break;
                            }
                        }
                    }
                }
            }
            return new String(temp).Replace(@"\","");
        }

        /// <summary>
        /// 转换字符流成字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToString(byte[] bytes)
        {
            var sb = new StringBuilder(64);
            foreach (byte iByte in bytes) sb.AppendFormat("{0:x2}", iByte);
            return sb.ToString();
        }

        /// <summary>
        /// 转换成Byte数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] ToBytes(string hexString)
        {
            if (hexString == null) return null;
            var data = new byte[hexString.Length / 2];
            int h, l;
            for (var i = 0; i < data.Length; i++)
            {
                h = (hexString[2 * i] > 57 ? hexString[2 * i] - 'A' + 10 : hexString[2 * i] - '0') << 4 & 0x000000F0;
                l = (hexString[2 * i + 1] > 57 ? hexString[2 * i + 1] - 'A' + 10 : hexString[2 * i + 1] - '0') & 0x0000000F;

                data[i] = (byte)(h | l);
            }

            return data;
        }

        /// <summary>
        /// 类型转换
        /// </summary>
        /// <typeparam name="T">要转换类型</typeparam>
        /// <param name="obj">要转换的值</param>
        /// <returns></returns>
        public static T ConvertTo<T>(object obj)
        {
            if (obj == null) return default;//返回默认值
            Type tp = typeof(T);
            //泛型Nullable判断，取其中的类型
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            //string直接返回转换
            if (tp.Name.ToLower() == "string")
            {
                return (T)obj;
            }
            //反射获取TryParse方法
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { obj, Activator.CreateInstance(tp) };
            try
            {
                bool success = (bool)TryParse.Invoke(null, parameters);
                //成功返回转换后的值，否则返回类型的默认值
                if (success)
                {
                    return (T)parameters[1];
                }
                return default;
            }
            catch
            {
                return default;
            }
        }

        /// <summary>
        /// 转Int
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ConvertInt(object obj)
        {
            return ConvertTo<int>(obj);
        }

        /// <summary>
        /// 字符串状态List<int>
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<int> ConvertToListInt(object obj)
        {
            List<int> result = new List<int>();
            if (obj != null && !string.IsNullOrWhiteSpace(obj.ToString()))
            {
                var tempArray = obj.ToString().Split(',');
                if (tempArray != null && tempArray.Length > 0)
                {
                    foreach (var item in tempArray)
                    {
                        Int32.TryParse(item, out int NewValue);
                        if (NewValue > 0)
                        {
                            result.Add(NewValue);
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 字符串状态List<int>
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static List<string> ConvertToListString(object obj)
        {
            List<string> result = new List<string>();
            if (obj != null && !string.IsNullOrWhiteSpace(obj.ToString()))
            {
                var tempArray = obj.ToString().Split(',');
                if (tempArray != null && tempArray.Length > 0)
                {
                    foreach (var item in tempArray)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            result.Add(item);
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 转Int
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static int ToInt(object obj, int defaultValue = 0)
        {
            int result = defaultValue;
            if (obj != null)
            {
                Int32.TryParse(obj.ToString(), out result);
            }
            return result;
        }

        /// <summary>
        /// 格式化时间【yyyy-MM-dd HH:mm:ss】
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatTime(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch
                {

                }
            }
            return timeStr;
        }

        /// <summary>
        /// 获取时间格式
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatTimeStr(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("HH:mm");
                }
                catch
                {

                }
            }
            return timeStr;
        }


        /// <summary>
        /// 获取时间格式(yyyy-MM)
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatYearMonth(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("yyyy-MM");
                }
                catch
                {

                }
            }
            return timeStr;
        }

        /// <summary>
        /// 获取时间格式
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatMonthDay(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("MM-dd");
                }
                catch
                {

                }
            }
            return timeStr;
        }

        /// <summary>
        /// 格式化时间【yyyy-MM-dd】
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatDate(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("yyyy-MM-dd");
                    if (timeStr == "0001-01-01")
                    {
                        timeStr = "";
                    }
                }
                catch
                {

                }
            }
            return timeStr;
        }

        /// <summary>
        /// 格式化时间【yyyy-MM-dd HH:mm】
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string FormatDate2(this object time)
        {
            string timeStr = "";
            if (time != null)
            {
                try
                {
                    timeStr = Convert.ToDateTime(time.ToString()).ToString("yyyy-MM-dd");
                    if (timeStr == "0001-01-01")
                    {
                        timeStr = "";
                    }
                    else
                    {
                        timeStr= Convert.ToDateTime(time.ToString()).ToString("yyyy-MM-dd HH:mm");
                    }
                }
                catch
                {

                }
            }
            return timeStr;
        }

        /// <summary>
        /// 字符串转List
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static List<int> StringToList(object value)
        {
            List<int> list = new List<int>();
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                var tempArray = value.ToString().Split(',');
                if (tempArray != null && tempArray.Length > 0)
                {
                    foreach (var item in tempArray)
                    {
                        Int32.TryParse(item, out int NewValue);
                        if (NewValue > 0)
                        {
                            list.Add(NewValue);
                        }
                    }
                }
            }
            return list;
        }
    }
}