using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qcloudsms_csharp;
using qcloudsms_csharp.httpclient;
using qcloudsms_csharp.json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Mvc;
using TencentCloud.Common;
using TencentCloud.Common.Profile;




using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;

namespace CallCenterApi.Interface.Controllers
{
    //经分助手
    public class SMSNewController : BaseController
    {
        public static string apiKey = "d40cf1f4e0748a1e1c199e6712e4ac1d";
        public static string accessKey = "9c0ff687133407cad821f20419ee9a08ad4904082dfa3700e039e763988fe533";
        public static string authHost = "https://opassapi.infocloud.cc/message/send";


        public static string AddSmS(int userId, string Content, string mobiles, string templateCode
         , string templateParam = "", string workorderid = "")
        {
            int t = 0;
            try
            {
                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", mobiles);

                jsArr.Add("templateCode", templateCode);

                //"[\"变量值1\",\"变量值2\"]"
                if (!string.IsNullOrEmpty(templateParam))
                    jsArr.Add("templateParam", templateParam);

                //将headers参与与接口报文参数合并、排序，并生成本次请求的签名信息
                var signDic = jsArr.Union(requestHeaders).ToDictionary(k => k.Key, v => v.Value);

                //     var signDic = 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(JsonConvert.SerializeObject(jsArr));
                str.Headers.Remove("Content-Type");
                str.Headers.Add("Content-Type", "application/json");

                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                HttpResponseMessage response = client.PostAsync(authHost, str).Result;



                string result = response.Content.ReadAsStringAsync().Result;

                JObject jo = (JObject)JsonConvert.DeserializeObject(result);

                string code = jo["code"].ToString();
                Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                dModel.CallerNum = mobiles.Trim();
                dModel.Content = Content.Trim();
                dModel.RecvModemIMEI = templateCode;
                dModel.F_Name = workorderid;
                dModel.State = 0;
                dModel.F_UserID = userId;
                dModel.RecvTime = DateTime.Now;
                int b = new BLL.T_SMS_RecvSMS().Add(dModel);

                if (code != "200")
                {
                    string desc = jo["message"].ToString();
                    LogFactory.GetLogger("SmsNew/Receive").Debug(code + "(" + desc + ")" + mobiles + Content);

                    return code + "(" + desc + ")";
                }
                else
                {
                    if (b > 0)
                    {
                        return "";
                    }
                    else
                    {
                        return "发送失败";
                    }

                }


            }
            catch (Exception e)
            {
                LogFactory.GetLogger("SmsNew/Receive").Debug(e.ToString());
                return e.ToString();
            }


        }



        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        /// <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;
        }



    }
}