using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CallCenter.Utility
{
    /// <summary>
    /// 短信
    /// </summary>
    public static class SmsHelper
    {
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phones">手机号、多个手机号英文逗号隔开</param>
        /// <param name="templateCode">模板编号</param>
        /// <param name="templateParam">[\"工单号\"]、[\"工单号\",\"工单号\",\"工单号\",...]</param>
        /// <returns></returns>
        public static string Send(string phones,string templateCode,string templateParam="")
        {
            string result = string.Empty;

            try
            {
                string apiKey = Configs.GetValue("SmsNewApiKey");
                string accessKey = Configs.GetValue("SmsNewSecretKey");
                string authHost = Configs.GetValue("SmsNewUrl");

                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var currentTime = Convert.ToInt64(ts.TotalMilliseconds).ToString();
                HttpClient client = new HttpClient();

                var requestHeaders = new Dictionary<string, string>();
                //签名算法。支持HmacSHA256、HmacMD5、HmacSHA224、HmacSHA384、HmacSHA512
                requestHeaders.Add("x-sign-method", "HmacSHA256");
                requestHeaders.Add("x-api-key", $"{apiKey}");
                //随机数。每次请求随机数建议不相同
                requestHeaders.Add("x-nonce", $"{GetRandom()}");
                //时间戳
                requestHeaders.Add("x-timestamp", $"{currentTime}");


                // client.DefaultRequestHeaders.Host = "recognition.image.myqcloud.com";
                //设置headers请求参数 
                foreach (var item in requestHeaders)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }

                //短信接口请求参数。参见接口规范
                var jsArr = new Dictionary<string, string>();
                jsArr.Add("phones", phones);
                jsArr.Add("templateCode", templateCode);
                if (!string.IsNullOrEmpty(templateParam))
                {
                    jsArr.Add("templateParam", templateParam);
                }

                //将headers参与与接口报文参数合并、排序，并生成本次请求的签名信息
                var signDic = jsArr.Union(requestHeaders).ToDictionary(k => k.Key, v => v.Value);
                var dicStr = GetSignContent(signDic);
                var sign = Hmacsha256Encrypt(dicStr, accessKey);
                //在header中设置本次请求签名信息
                client.DefaultRequestHeaders.Add("x-sign", sign);


                HttpContent str = new StringContent(jsArr.ToJson());
                str.Headers.Remove("Content-Type");
                str.Headers.Add("Content-Type", "application/json");
                HttpResponseMessage response = client.PostAsync(authHost, str).Result;
                var result1 = response.Content.ReadAsStringAsync().Result;
                var objresult = result1.ToJObject();
                if (objresult["code"].ToString() != "200")
                {
                    LogFactory.GetLogger("SmsHelper").Error(phones + "\r\n" + templateCode + "\r\n" + templateParam + "\r\n" + result1);
                }

            }
            catch (Exception ex)
            {
                LogFactory.GetLogger("SmsHelper").Error(phones + "\r\n" + templateCode + "\r\n" + templateParam + "\r\n" + ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// Get Sign Content
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private static string GetSignContent(IDictionary<string, string> parameters)
        {
            // 第一步：把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            // 第二步：把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }

        /// <summary>
        /// HMACSHA1算法加密
        /// </summary>
        private static string Hmacsha256Encrypt(string encryptText, string encryptKey)
        {
            var encoding = new System.Text.UTF8Encoding();
            StringBuilder builder = new StringBuilder();

            using (var hmacsha256 = new HMACSHA256(encoding.GetBytes(encryptKey)))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(encoding.GetBytes(encryptText));
                for (int i = 0; i < hashmessage.Length; i++)
                {
                    builder.Append(hashmessage[i].ToString("x2"));
                }
            }
            return builder.ToString();
        }
        /// <summary>
        /// 获取随机数
        /// </summary>
        private static int GetRandom()
        {
            var random = new Random();
            var rand = random.Next(10000, 999999999);
            return rand;
        }
    }
}
