using MailKit.Net.Smtp;
using MimeKit;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace JiaZhiQuan.Common
{

    public class MailInfo
    {
        public string Account { get; set; }
        public string AuthCode { get; set; }

        /// <summary>
        /// Key为Address，Value为Name
        /// </summary>
        public Dictionary<string, string> MailToDic { get; set; }

        public string MailFromName { get; set; }
        public string MailFromAddr { get; set; }

        public string Subject { get; set; }
        public string Content { get; set; }

    }

    public class CommunityTextSegment
    {
        /// <summary>
        /// 类型：0 纯文本 1 @的用户编号（content为通过逗号分隔，前段为id，后段为昵称）
        /// </summary>
        public int type { get; set; }
        public string content { get; set; }
    }


    public static class CommonUtils
    {
        /// <summary>
        /// 将dateTime格式转换为Unix时间戳
        /// </summary>
        public static long DateTimeToUnixTime(DateTime dateTime)
        {
            return (long)(dateTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
        }

        public async static Task SendEmail(MailInfo info)
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(info.MailFromName, info.MailFromAddr));
            message.To.AddRange(info.MailToDic.ToList().Select(e => new MailboxAddress(e.Key, e.Value)));
            message.Subject = info.Subject;
            message.Body = new TextPart("plain") { Text = info.Content };
            using var client = new SmtpClient();
            client.Connect("smtp.exmail.qq.com", 465, true);
            await client.AuthenticateAsync(info.Account, info.AuthCode);
            await client.SendAsync(message);
            client.Disconnect(true);
        }

        public static string GetFirstOrDefaultImage(string imgs)
        {
            if (string.IsNullOrEmpty(imgs))
            {
                return null;
            }
            return imgs.Split(',', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
        }

        /// <summary>
        /// Mock用户的数据中心Id为21
        /// </summary>
        public static bool IsMockUser(long userId)
        {
            var dataCenterId = userId >> 17 & 31;
            return dataCenterId == 21;
        }

        /// <summary>
        /// 取字符串右边多少个字符，前面的字符使用*号。rightCharCount如果<=0，则默认为1
        /// </summary>
        public static string TakeRightSubString(string original, int rightCharCount)
        {
            if (string.IsNullOrEmpty(original))
            {
                return string.Empty;
            }
            if (rightCharCount <= 0) rightCharCount = 1;
            StringBuilder sb = new StringBuilder();
            for (var i = 0; i < original.Length; i++)
            {
                sb.Append(i + rightCharCount >= original.Length ? original[i] : '*');
            }
            return sb.ToString();
        }

        /// <summary>
        /// 取字符串左边多少个字符，后面的字符使用*号。leftCharCount如果<=0，则默认为1
        /// </summary>
        public static string TakeLeftSubString(string original, int leftCharCount)
        {
            if (string.IsNullOrEmpty(original))
            {
                return string.Empty;
            }
            if (leftCharCount <= 0) leftCharCount = 1;
            StringBuilder sb = new StringBuilder();
            for (var i = 0; i < original.Length; i++)
            {
                sb.Append(leftCharCount + i >= original.Length ? '*' : original[i]);
            }
            return sb.ToString();
        }

        public static string Md5Encrypt(string strSource)
        {
            byte[] result = Encoding.Default.GetBytes(strSource);
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");
        }

        /// <summary>
        /// 比较版本号，版本号如：v3.2.2 或 3.2.2
        /// </summary>
        public static int CompareVersion(string version1, string version2)
        {
            try
            {
                var chars = new char[] { 'v', 'V' };
                var nums1 = (version1 ?? string.Empty).Trim(chars).Split('.').Select(e => int.Parse(e)).ToList();
                var nums2 = (version2 ?? string.Empty).Trim(chars).Split('.').Select(e => int.Parse(e)).ToList();
                var maxLen = Math.Max(nums1.Count, nums2.Count);
                for (var i = 0; i < maxLen; i++)
                {
                    var val1 = nums1.Count > i ? nums1[i] : 0;
                    var val2 = nums2.Count > i ? nums2[i] : 0;
                    if (val1 > val2)
                    {
                        return 1;
                    }
                    else if (val1 < val2)
                    {
                        return -1;
                    }
                }
                return 0;
            }
            catch
            {
                return string.Compare(version1, version2);
            }
        }


        #region 动态评论相关

        /// <summary>
        /// 解析社区文本，并返回纯文本表示
        /// </summary>
        public static string GetPlainTextByCommunityText(string content)
        {
            if (string.IsNullOrWhiteSpace(content)) return string.Empty;
            try
            {
                var sb = new StringBuilder();
                var segList = TransformCommunityText(content);
                if (segList != null && segList.Count > 0)
                {
                    return GetPlainTextByCommunityTextSegments(segList);
                }
                else
                {
                    return string.Empty;
                }
            }
            catch
            {
                return content;
            }
        }

        /// <summary>
        /// 通过社区文本对象，获取纯文本表示
        /// </summary>
        /// <param name="segList"></param>
        /// <returns></returns>
        public static string GetPlainTextByCommunityTextSegments(IList<CommunityTextSegment> segList)
        {
            try
            {
                var sb = new StringBuilder();
                foreach (var item in segList)
                {
                    if (item.type == 0)
                    {
                        sb.Append(item.content);
                    }
                    else if (item.type == 1)
                    {
                        sb.Append("@" + item.content.Split(',')[0]);
                    }
                }
                return sb.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }


        /// <summary>
        /// 解析社区文本，返回社区文本对象
        /// </summary>
        public static IList<CommunityTextSegment> TransformCommunityText(string content)
        {
            try
            {
                return JsonConvert.DeserializeObject<IList<CommunityTextSegment>>(content);
            }
            catch
            {
                return null;
            }
        }


        #endregion



        public static string GetIdCardDisplayName(string name)
        {
            if (string.IsNullOrEmpty(name)) return "";
            var str = "";
            var i = 0;
            name.ForEach(e =>
            {
                if (i == 0)
                {
                    str += e;
                }
                else
                {
                    str += "*";
                }
                i++;
            });
            return str;
        }

        public static string GetIdCardDisplayCode(string code)
        {
            if (string.IsNullOrEmpty(code)) return "";
            var str = "";
            var i = 0;
            code.ForEach(e =>
            {
                if (i == 0 || i == code.Length - 1)
                {
                    str += e;
                }
                else
                {
                    str += "*";
                }
                i++;
            });
            return str;
        }

        private static Regex ProvinceOrCityEndReg = new Regex("(市)|(省)|(自治区)|(特别行政区)|(盟)|(自治州)|(地区)|(蒙古自治州)|(柯尔克孜自治州)|(哈萨克自治州)$");
        private static Regex ProvinceOrCityReplaceReg =
            new Regex("(壮族)|(回族)|(维吾尔)|(朝鲜族)|(土家族)|(苗族)|(藏族)|(羌族)|(彝族)|(布依族)|(侗族)|(哈尼族)|(傣族)|(白族)|(景颇族)|(傈僳族)|(蒙古族)");
        /// <summary>
        /// 获取省或市简要名称
        /// </summary>
        public static string GetShortNameOfProvinceAndCity(string provinceOrCityName)
        {
            return ProvinceOrCityEndReg.Replace(ProvinceOrCityReplaceReg.Replace(provinceOrCityName, ""), "");
        }


        /// <summary>
        /// 计算金额
        /// </summary>
        /// <param name="numerator"></param>
        /// <param name="denominator"></param>
        /// <returns></returns>
        public static decimal DivideAndRound(int numerator, int denominator) {
            decimal result = (decimal)numerator / denominator;
            return Math.Round(result, 2, MidpointRounding.AwayFromZero);
        }
    }
}
