using Nancy.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using JsonSerializer = System.Text.Json.JsonSerializer;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.Common
* 唯一标识：496f8d2b-70e3-4a05-ae18-a9b0fcd06b82
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-03-27 21:58:35
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Common
{
    public class StringChange
    {
        /// <summary>
        /// 将字符串强制转换成int，转换失败则返回0
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public int ParseToInt(string str)
        {
            int returnInt = 0;
            if (str == null || str.Trim().Length < 1)
            {
                return returnInt;
            }
            if (int.TryParse(str, out returnInt))
            {
                return returnInt;
            }
            else
            {
                return 0;
            }
        }
        public byte[] StructToBytes(object structObj)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(structObj);
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }
        public byte[] CalculateVerifytobyte(byte[] pMessage, int iLength)
        {
            UInt16 i;
            int iVerify = 0;

            iVerify = pMessage[0];
            for (i = 0; i < iLength - 1; i++)
            {
                iVerify = iVerify + pMessage[i + 1];
            }
            return BitConverter.GetBytes(Convert.ToUInt16(iVerify));
        }
        public byte CalculateVerify(byte[] pMessage, int iLength)
        {
            UInt16 i;
            byte iVerify = 0;

            iVerify = pMessage[0];
            for (i = 1; i < iLength; i++)
            {
                iVerify = (byte)(iVerify ^ pMessage[i]);
            }
            return iVerify;
        }
        /// <summary>
        /// char数组转Array
        /// </summary>
        /// <param name="cha"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public string CharArrayToString(char[] cha, int len)
        {
            string str = "";
            for (int i = 0; i < len; i++)
            {
                str += string.Format("{0}", cha[i]);
            }

            return str;
        }

        public string bytesToHexStr(byte[] bytes, int iLen)//e.g. { 0x01, 0x01} ---> " 01 01"
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < iLen; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        public byte[] HexStrTorbytes(string strHex)//e.g. " 01 01" ---> { 0x01, 0x01}
        {
            strHex = strHex.Replace(" ", "");
            if ((strHex.Length % 2) != 0)
                strHex += " ";
            byte[] returnBytes = new byte[strHex.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        public string StringToHexString(string s, Encoding encode)
        {
            byte[] b = encode.GetBytes(s);          //按照指定编码将string编程字节数组
            string result = string.Empty;
            for (int i = 0; i < b.Length; i++)      //逐字节变为16进制字符，以%隔开
            {
                result += "%" + Convert.ToString(b[i], 16);
            }
            return result;
        }

        public string HexStringToString(string hs, Encoding encode)
        {
            //以%分割字符串，并去掉空字符
            string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
            byte[] b = new byte[chars.Length];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < chars.Length; i++)
            {
                b[i] = Convert.ToByte(chars[i], 16);
            }
            //按照指定编码将字节数组变为字符串
            return encode.GetString(b);
        }

        /// <summary>
        /// 将整数转换为指定位数的byte数组（大端序）
        /// </summary>
        /// <param name="length">目标byte数组长度</param>
        /// <param name="num">要转换的整数</param>
        /// <returns>指定长度的byte数组</returns>
        public byte[] IntToBytes(int length, int num)
        {
            if (length <= 0)
                throw new ArgumentException("长度必须大于0", nameof(length));

            byte[] result = new byte[length];

            // 从最高位开始填充
            for (int i = 0; i < length; i++)
            {
                // 计算当前字节的位置（从高位到低位）
                // 例如 length=2, i=0 时，移位 8 位；i=1 时，移位 0 位
                int shift = (length - 1 - i) * 8;
                result[i] = (byte)((num >> shift) & 0xFF);
            }

            return result;
        }

        /// <summary>
        /// 将byte数组转换为整数（大端序）
        /// </summary>
        public int BytesToInt(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                Console.WriteLine("字节数组不能为空");

            if (bytes.Length > 4)
                Console.WriteLine("字节数组长度不能超过4（int最大4字节）");

            int result = 0;

            // 从高位到低位组合（大端序）
            for (int i = 0; i < bytes.Length; i++)
            {
                result = (result << 8) | bytes[i];
            }

            return result;
        }

        /// <summary>
        /// 将byte数组转换为整数（小端序）
        /// </summary>
        public int BytesToIntLittleEndian(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                throw new ArgumentException("字节数组不能为空", nameof(bytes));

            if (bytes.Length > 4)
                throw new ArgumentException("字节数组长度不能超过4（int最大4字节）", nameof(bytes));

            int result = 0;

            // 从低位到高位组合（小端序）
            for (int i = 0; i < bytes.Length; i++)
            {
                result |= (bytes[i] << (i * 8));
            }

            return result;
        }

        

        public byte[] Swap16Bytes(byte[] OldU16)
        {
            byte[] ReturnBytes = new byte[2];
            ReturnBytes[1] = OldU16[0];
            ReturnBytes[0] = OldU16[1];
            return ReturnBytes;
        }


        /// <param name="strbase64">64Base码</param>
        /// <param name="path">保存路径</param>
        /// <param name="filename">文件名称</param>
        /// <returns></returns>
        public bool Base64ToImage(string strbase64, string path, string filename)
        {
            bool Flag = false;
            try
            {
                //base64编码的文本 转为 图片
                //图片名称
                byte[] arr = Convert.FromBase64String(strbase64);//将指定的字符串（它将二进制数据编码为 Base64 数字）转换为等效的 8 位无符号整数数组。
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    Bitmap bmp = new Bitmap(ms);//加载图像
                    if (!Directory.Exists(path))//判断保存目录是否存在
                    {
                        Directory.CreateDirectory(path);
                    }
                    bmp.Save((path + "\\" + filename + ".png"), System.Drawing.Imaging.ImageFormat.Png);//将图片以JPEG格式保存在指定目录(可以选择其他图片格式)
                    ms.Close();//关闭流并释放
                    if (File.Exists(path + "\\" + filename + ".png"))//判断是否存在
                    {
                        Flag = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("图片保存失败：" + ex.Message);
            }
            return Flag;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public long GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        public byte[] ConvertFloatToINt(byte[] floatBytes)
        {
            byte[] intBytes = new byte[floatBytes.Length / 2];
            for (int i = 0; i < intBytes.Length; i++)
            {
                intBytes[i] = floatBytes[i * 2];
            }
            return intBytes;
        }


        public int HexStringToNegative(string strNumber)
        {

            int iNegate = 0;
            int iNumber = Convert.ToInt32(strNumber, 16);
            if (iNumber > 127)
            {
                int iComplement = iNumber - 1;
                string strNegate = string.Empty;
                char[] binchar = Convert.ToString(iComplement, 2).PadLeft(8, '0').ToArray();
                foreach (char ch in binchar)
                {
                    if (Convert.ToInt32(ch) == 48)
                    {
                        strNegate += "1";
                    }
                    else
                    {
                        strNegate += "0";
                    }
                }
                iNegate = -Convert.ToInt32(strNegate, 2);
            }
            return iNegate;
        }
        public static string ModeToJson(object Model)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string str = serializer.Serialize(Model);
            //HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            //return result;
            return str;
        }

        private static readonly Dictionary<string, string> _regionToNumber = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        { "China1", "1" },
        { "China2", "2" },
        { "Europe", "3" },
        { "Europe2", "4" },
        { "Europe3", "5" },
        { "US", "6" },
        { "NA", "7" },
        { "Korea", "8" },
        { "Korea2", "9" },
        { "Japan", "10" },
        { "Australia", "11" },
        { "India", "12" },
        { "Open", "0" }
    };
        // 🔍 反向映射：Region Num → Region 名称
        private static readonly Dictionary<string, string> _numberToRegion = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        { "1", "China1" },
        { "2", "China2" },
        { "3", "Europe" },
        { "4", "Europe2" },
        { "5", "Europe3" },
        { "6", "US" },
        { "7", "NA" },
        { "8", "Korea" },
        { "9", "Korea 2" },
        { "A", "Japan" },
        { "B", "Australia" },
        { "C", "India" },
        { "0", "Open" }
    };
        /// <summary>
        /// 根据 Region 名称获取对应的 Region Num
        /// </summary>
        /// <param name="region">Region 名称（如 "China1"）</param>
        /// <returns>Region Num（如 "01"），不存在则返回 null</returns>
        public static string GetRegionNumber(string region)
        {
            if (string.IsNullOrWhiteSpace(region))
                return null;

            _regionToNumber.TryGetValue(region, out var number);
            return number;
        }

        /// <summary>
        /// 根据 Region Num 获取对应的 Region 名称
        /// </summary>
        /// <param name="regionNum">Region Num（如 "0A"）</param>
        /// <returns>Region 名称（如 "Japan"），不存在则返回 null</returns>
        public static string GetRegionByNumber(string regionNum)
        {
            if (string.IsNullOrWhiteSpace(regionNum))
                return null;

            _numberToRegion.TryGetValue(regionNum, out var region);
            return region;
        }

        public T JTokenToEntity<T>(JToken value) where T : class
        {
            if (value == null)
            {
                return null;
            }
            string json = value.ToString();
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            T ResponseEntity;
            ResponseEntity = JsonSerializer.Deserialize<T>(json);
            return ResponseEntity;
        }
    }
}