using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
 


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

namespace CallCenterApi.Interface.Controllers
{
    public class TencentSmsController : BaseController
    {


        Log log = LogFactory.GetLogger("TencentSmsController");
        // private static readonly string secretId = "1400467981";
        private static readonly string secretKey = "sZ5eDakngNrodJpQtHgDapyueDcpriQC";
        //private static readonly string secretKey = "ba3aa1a33da088dac57bcac8ce5f8d41";
        private static readonly string endpoint = "sms.tencentcloudapi.com";
        private static readonly string smsSdkAppId = "1400467981";
        private static readonly string signName = "巩义市网络舆情研究中心";
        private static readonly string templateId = "1963450";
        private static readonly string action = "SendSms";
        public static string SHA256Hex(string s)
        {
            using (SHA256 algo = SHA256.Create())
            {
                byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashbytes.Length; ++i)
                {
                    builder.Append(hashbytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        public static byte[] HmacSHA256(byte[] key, byte[] msg)
        {
            using (HMACSHA256 mac = new HMACSHA256(key))
            {
                return mac.ComputeHash(msg);
            }
        }

        public static Dictionary<String, String> BuildHeaders(string secretid,
            string secretkey, string service, string endpoint, string region,
            string action, string version, DateTime date, string requestPayload)
        {
            string datestr = date.ToString("yyyy-MM-dd");
            DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000;
            // ************* 步骤 1：拼接规范请求串 *************
            string algorithm = "TC3-HMAC-SHA256";
            string httpRequestMethod = "POST";
            string canonicalUri = "/";
            string canonicalQueryString = "";
            string contentType = "application/json";
            string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8\n" + "host:" + endpoint + "\n";
            string signedHeaders = "content-type;host";
            string hashedRequestPayload = SHA256Hex(requestPayload);
            string canonicalRequest = httpRequestMethod + "\n"
                + canonicalUri + "\n"
                + canonicalQueryString + "\n"
                + canonicalHeaders + "\n"
                + signedHeaders + "\n"
                + hashedRequestPayload;
            Console.WriteLine(canonicalRequest);

            // ************* 步骤 2：拼接待签名字符串 *************
            string credentialScope = datestr + "/" + service + "/" + "tc3_request";
            string hashedCanonicalRequest = SHA256Hex(canonicalRequest);
            string stringToSign = algorithm + "\n" + requestTimestamp.ToString() + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
            Console.WriteLine(stringToSign);

            // ************* 步骤 3：计算签名 *************
            byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretkey);
            byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));
            byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));
            byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
            byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
            string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();
            Console.WriteLine(signature);

            // ************* 步骤 4：拼接 Authorization *************
            string authorization = algorithm + " "
                + "Credential=" + secretid + "/" + credentialScope + ", "
                + "SignedHeaders=" + signedHeaders + ", "
                + "Signature=" + signature;
            Console.WriteLine(authorization);

            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Authorization", authorization);
            headers.Add("Host", endpoint);
            headers.Add("Content-Type", contentType + "; charset=utf-8");
            headers.Add("X-TC-Timestamp", requestTimestamp.ToString());
            headers.Add("X-TC-Version", version);
            headers.Add("X-TC-Action", action);
            headers.Add("X-TC-Region", region);
            return headers;
        }


        //        public static async Task SendSmsAsync(string phoneNumber, string[]  templateParams)
        //        {
        //            var request = new
        //            {
        //                SmsSdkAppId = smsSdkAppId,
        //                Sign = signName,
        //                TemplateId = templateId,
        //                PhoneNumberSet = new[] { phoneNumber },
        //                TemplateParamSet = templateParams
        //            };

        //            var requestBody = JsonConvert.SerializeObject(request);
        //            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        //            var nonce = new Random().Next(100000, 999999).ToString();
        //            var signature = GenerateSignature(requestBody, timestamp, nonce);

        //            using (var client = new HttpClient())
        //            {
        //                client.DefaultRequestHeaders.Add("Authorization", signature);
        //                client.DefaultRequestHeaders.Add("X-TC-Action", "SendSms");
        //                client.DefaultRequestHeaders.Add("X-TC-Timestamp", timestamp);
        //                client.DefaultRequestHeaders.Add("X-TC-Nonce", nonce);
        //                client.DefaultRequestHeaders.Add("X-TC-Version", "2021-01-11");

        //                //foreach (KeyValuePair<string, string> kv in headers)
        //                //{
        //                //    // Console.WriteLine(kv.Key + ": " + kv.Value);
        //                //    client.DefaultRequestHeaders.Add(kv.Key, kv.Value);
        //                //}

        //                var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
        //                var response = await client.PostAsync($"https://{endpoint}", content);

        //                if (response.IsSuccessStatusCode)
        //                {
        //                    var responseBody = await response.Content.ReadAsStringAsync();
        //                    Console.WriteLine("SMS sent successfully: " + responseBody);
        //                }
        //                else
        //                {
        //                    Console.WriteLine("Failed to send SMS: " + response.ReasonPhrase);
        //                }
        //            }
        //        }

        //        private static string GenerateSignature(string requestBody, string timestamp, string nonce)
        //        {
        //            var source = $"POST{smsSdkAppId}{timestamp}{nonce}{requestBody}";
        //            using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)))
        //            {
        //                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(source));
        //                return Convert.ToBase64String(hash);
        //            }
        //        }
        //        public static byte[] HmacSHA256(byte[] key, byte[] msg)
        //        {
        //            using (HMACSHA256 mac = new HMACSHA256(key))
        //            {
        //                return mac.ComputeHash(msg);
        //            }
        //        }
        //        public static string SHA256Hex(string s)
        //        {
        //            using (SHA256 algo = SHA256.Create())
        //            {
        //                byte[] hashbytes = algo.ComputeHash(Encoding.UTF8.GetBytes(s));
        //                StringBuilder builder = new StringBuilder();
        //                for (int i = 0; i < hashbytes.Length; ++i)
        //                {
        //                    builder.Append(hashbytes[i].ToString("x2"));
        //                }
        //                return builder.ToString();
        //            }
        //        }

        //        public static Dictionary<String, String> BuildHeaders(string secretid,
        //        string secretkey, string service, string endpoint, string region,
        //        string action, string version, DateTime date, string requestPayload) {


        //            string datestr = date.ToString("yyyy-MM-dd");
        //            DateTime startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        //            long requestTimestamp = (long)Math.Round((date - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero) / 1000;
        //            // ************* 步骤 1：拼接规范请求串 *************
        //            string algorithm = "TC3-HMAC-SHA256";
        //            string httpRequestMethod = "POST";
        //            string canonicalUri = "/";
        //            string canonicalQueryString = "";
        //            string contentType = "application/json";
        //            string canonicalHeaders = "content-type:" + contentType + "; charset=utf-8\n"
        //                + "host:" + endpoint + "\n"
        //                + "x-tc-action:" + action.ToLower() + "\n";
        //            string signedHeaders = "content-type;host;x-tc-action";
        //            string hashedRequestPayload = SHA256Hex(requestPayload);
        //            string canonicalRequest = httpRequestMethod + "\n"
        //                + canonicalUri + "\n"
        //                + canonicalQueryString + "\n"
        //                + canonicalHeaders + "\n"
        //                + signedHeaders + "\n"
        //                + hashedRequestPayload;
        //            Console.WriteLine(canonicalRequest);

        //            // ************* 步骤 2：拼接待签名字符串 *************
        //            string credentialScope = datestr + "/" + service + "/" + "tc3_request";
        //            string hashedCanonicalRequest = SHA256Hex(canonicalRequest);
        //            string stringToSign = algorithm + "\n"
        //                + requestTimestamp.ToString() + "\n"
        //                + credentialScope + "\n"
        //                + hashedCanonicalRequest;
        //            Console.WriteLine(stringToSign);

        //            // ************* 步骤 3：计算签名 *************
        //            byte[] tc3SecretKey = Encoding.UTF8.GetBytes("TC3" + secretkey);
        //            byte[] secretDate = HmacSHA256(tc3SecretKey, Encoding.UTF8.GetBytes(datestr));
        //            byte[] secretService = HmacSHA256(secretDate, Encoding.UTF8.GetBytes(service));
        //            byte[] secretSigning = HmacSHA256(secretService, Encoding.UTF8.GetBytes("tc3_request"));
        //            byte[] signatureBytes = HmacSHA256(secretSigning, Encoding.UTF8.GetBytes(stringToSign));
        //            string signature = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower();
        //            Console.WriteLine(signature);

        //            // ************* 步骤 4：拼接 Authorization *************
        //            string authorization = algorithm + " "
        //                + "Credential=" + secretid + "/" + credentialScope + ", "
        //                + "SignedHeaders=" + signedHeaders + ", "
        //                + "Signature=" + signature;
        //            Console.WriteLine(authorization);
        //            Dictionary<string, string> headers = new Dictionary<string, string>();
        //            headers.Add("Authorization", authorization);
        //            headers.Add("Host", endpoint);
        //            headers.Add("Content-Type", contentType + "; charset=utf-8");
        //            headers.Add("X-TC-Timestamp", requestTimestamp.ToString());
        //            headers.Add("X-TC-Version", version);
        //            headers.Add("X-TC-Action", action);
        //            headers.Add("X-TC-Region", region);
        //            return headers;
        //        }

        [HttpGet]
        public void SmsNew()
        {
            //string phoneNumber = "15639002755"; // 替换为实际的手机号码
            //var templateParams = new[] { "202402110000" }; // 替换为实际的模板参数
            //string service = "cvm";
            //string endpoint = "cvm.tencentcloudapi.com";
            //string region = "ap-guangzhou";
            //string action = "DescribeInstances";
            //string version = "2017-03-12";
            //DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1551113065);


            //  string requestPayload = "{\"Limit\": 1, \"Filters\": [{\"Values\": [\"\\u672a\\u547d\\u540d\"], \"Name\": \"instance-name\"}]}";


            //  Dictionary<string, string> headers = BuildHeaders(smsSdkAppId, secretKey, service
            //, endpoint, region, action, version, date);
            //string SECRET_ID = "AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******";
            //string SECRET_KEY = "Gu5t9xGARNpq86cd98joQYCN3*******";

            string service = "sms";
            string endpoint = "sms.tencentcloudapi.com";
            string region = "ap-guangzhou";
            string action = "SendSms";
            string version = "2021-01-11";

            // 此处由于示例规范的原因，采用时间戳2019-02-26 00:44:25，此参数作为示例，如果在项目中，您应当使用：
            DateTime date = DateTime.UtcNow;
            // 注意时区，建议此时间统一采用UTC时间戳，否则容易出错
            // DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1551113065);
            // 实际调用需要更新参数，这里仅作为演示签名验证通过的例子
            string requestPayload = "{\"SmsSdkAppId\":\"1400467981\",\"TemplateParamSet\":[\"11111230\"],\"PhoneNumberSet\":[\"+8615639002755\"],\"SessionContext\":\"test\",\"SignName\":\"巩义市网络舆情研究中心\",\"TemplateId\":\"1963450\"}";

            Dictionary<string, string> headers = BuildHeaders(smsSdkAppId, secretKey, service
                , endpoint, region, action, version, date, requestPayload);

            Console.WriteLine("POST https://sms.tencentcloudapi.com");
            foreach (KeyValuePair<string, string> kv in headers)
            {
                Console.WriteLine(kv.Key + ": " + kv.Value);
            }
            Console.WriteLine();
            Console.WriteLine(requestPayload);

            string curlcmd = "curl -X POST https://" + endpoint;
            foreach (KeyValuePair<string, string> kv in headers)
            {
                curlcmd = curlcmd + " -H \"" + kv.Key + ": " + kv.Value + "\"";
            }
            curlcmd = curlcmd + " -d '" + requestPayload + "'";
            Console.WriteLine(curlcmd);
        }

        public void SmsAsync () {

            try
            {
                // 必要步骤：
                // 实例化一个认证对象，入参需要传入腾讯云账户密钥对 SecretId，SecretKey。
                // 为了保护密钥安全，建议将密钥设置在环境变量中或者配置文件中。
                // 硬编码密钥到代码中有可能随代码泄露而暴露，有安全隐患，并不推荐。
                // 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
                // SecretId、SecretKey 查询：https://console.cloud.tencent.com/cam/capi
                Credential cred = new Credential
                {
                    SecretId = "AKIDugJkz1qSq21oPrAHH0Zw63rSq33tb9VQ",// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = secretKey// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                /* 非必要步骤:
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();
                /* SDK 默认用TC3-HMAC-SHA256进行签名
                 * 非必要请不要修改这个字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
                /* 非必要步骤
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();
                /* SDK默认使用POST方法。
                 * 如果您一定要使用GET方法，可以在这里设置。GET方法无法处理一些较大的请求 */
                httpProfile.ReqMethod = "POST";
                httpProfile.Timeout = 10; // 请求连接超时时间，单位为秒(默认60秒)
                /* 指定接入地域域名，默认就近地域接入域名为 sms.tencentcloudapi.com ，也支持指定地域域名访问，例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
                httpProfile.Endpoint = "sms.tencentcloudapi.com";
                // 代理服务器，当您的环境下有代理服务器时设定（无需要直接忽略）
                // httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;
                /* 实例化要请求产品(以sms为例)的client对象
                 * 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
                SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);

                /* 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
                 * 您可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
                 * 属性可能是基本类型，也可能引用了另一个数据结构
                 * 推荐使用IDE进行开发，可以方便的跳转查阅各个接口和数据结构的文档说明 */
                SendSmsRequest req = new SendSmsRequest();

                /* 基本类型的设置:
                 * SDK采用的是指针风格指定参数，即使对于基本类型您也需要用指针来对参数赋值。
                 * SDK提供对基本类型的指针引用封装函数
                 * 帮助链接：
                 * 短信控制台: https://console.cloud.tencent.com/smsv2
                 * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
                /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
                // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
                req.SmsSdkAppId = "1400467981";// "1304639164";

                /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
                // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
                req.SignName = signName;

                /* 模板 ID: 必须填写已审核通过的模板 ID */
                // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
                req.TemplateId = templateId;// "449739";

                /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
                req.TemplateParamSet = new String[] { "DH20250808996" };

                /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
                 * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
                req.PhoneNumberSet = new String[] { "15639002755","17839539537" };

                /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
                //req.SessionContext = "";

                /* 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手] */
                //req.ExtendCode = "";

                /* 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。注：月度使用量达到指定量级可申请独立 SenderId 使用，详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 */
                //req.SenderId = "";

                SendSmsResponse resp = client.SendSmsSync(req);

                // 输出json格式的字符串回包
             //   Console.WriteLine(AbstractModel.ToJsonString(resp));

                /* 当出现以下错误码时，快速解决方案参考
                 * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * 更多错误，可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
                 */
            }
            catch (Exception e)
            {
                log.Error(e.Message);
               // Console.WriteLine(e.ToString());
            }
            Console.Read();
        } 
    }
    }


 