using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Mall.ThirdCore.Commom;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;


namespace Mall.ThirdCore.Message
{
    /// <summary>
    /// 消息发送中心
    /// </summary>
    public  class MessageCore
    {
        private static bool IsFinish = true;
        public static void Init()
        {
            while (QueueHelper.Queue.Count == 0 || !IsFinish)
            {
                Thread.Sleep(1000);
            };
            IsFinish = false;
            string content = QueueHelper.Queue.Dequeue() as string;
            //Run(content);
            Init();
        }

        public static void Run(string content)
        {
            try
            {
                JObject obj = JObject.Parse(content);
                switch (obj["cmd"].ToString().ToLower())
                {
                    case "sms":
                        //SendSMS(obj);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            IsFinish = true;
        }

        private static void SendSMS(JObject obj)
        {
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                JObject aliSms = Config.AliSms;
                String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
                String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
                String accessKeyId = aliSms["accessKeyId"].ToString();
                String accessKeySecret = aliSms["accessKeySecret"].ToString();
                IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
                DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
                IAcsClient acsClient = new DefaultAcsClient(profile);
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = obj["phoneNumber"].ToString();
                request.SignName = "印象之旅"; //aliSms["signName"].ToString();
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = obj["templateCode"].ToString();
                //可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,此处的值为
                request.TemplateParam = obj["templateParam"].ToString();
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                if (!sendSmsResponse.Code.Equals("OK"))
                {
                    var data = new { phoneNumber = obj["phoneNumber"].ToString(), templateParam = obj["templateParam"].ToString(), code = sendSmsResponse.Code, message = sendSmsResponse.Message };
                    LogHelper.Write(JsonConvert.SerializeObject(data));
                }

                var datatst = new { phoneNumber = obj["phoneNumber"].ToString(), templateParam = obj["templateParam"].ToString(), code = sendSmsResponse.Code, message = sendSmsResponse.Message };
                Mall.Common.Plugin.LogHelper.WriteInfo(JsonConvert.SerializeObject(datatst));
            }
            catch (Aliyun.Acs.Core.Exceptions.ServerException ex)
            {
                LogHelper.Write(ex, "SendSMS1");
            }
            catch (ClientException ex)
            {
                LogHelper.Write(ex, "SendSMS2");
            }
        }

        /// <summary>
        /// java调用
        /// </summary>
        /// <param name="obj"></param>
        public static string SendSMSToJava(string phoneNumber, string templateCode, string templateParam)
        {
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                JObject aliSms = Config.AliSms;
                String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
                String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
                String accessKeyId = aliSms["accessKeyId"].ToString();
                String accessKeySecret = aliSms["accessKeySecret"].ToString();
                IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
                DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
                IAcsClient acsClient = new DefaultAcsClient(profile);
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = phoneNumber;
                request.SignName = aliSms["signName"].ToString();
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = templateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,此处的值为
                request.TemplateParam = templateParam;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                if (!sendSmsResponse.Code.Equals("OK"))
                {
                    var data = new { phoneNumber, templateParam, code = sendSmsResponse.Code, message = sendSmsResponse.Message };
                    return "";
                }
                else
                {
                    return sendSmsResponse.BizId;
                }
            }
            catch (Aliyun.Acs.Core.Exceptions.ServerException ex)
            {
                LogHelper.Write(ex, "SendSMSToJava1");
            }
            catch (ClientException ex)
            {
                LogHelper.Write(ex, "SendSMSToJava2");
            }
            return "";
        }

        /// <summary>
        /// 获取短信发送状态
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="SendDate"></param>
        /// <param name="BizId"></param>
        /// <returns></returns>
        public static string SendSMSStatus(string phoneNumber, string SendDate, string BizId)
        {
            JObject aliSms = Config.AliSms;
            String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            String accessKeyId = aliSms["accessKeyId"].ToString();
            String accessKeySecret = aliSms["accessKeySecret"].ToString();
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //拼接参数  返回url
            string url = $@"https://{domain}/?AccessKeyId={accessKeyId}&Action=QuerySendDetails&CurrentPage=1&Format=JSON&PageSize=12&PhoneNumber={phoneNumber}&RegionId=cn-hangzhou&SecureTransport=true&SendDate={SendDate}&BizId={BizId}&SignatureMethod=HMAC-SHA1&SignatureNonce=46edc0b6cc74e437aa0ba1703c71a99b&SignatureVersion=1.0&SourceIp=171.88.98.6&Timestamp=2019-09-25T02%3A12%3A35Z&Version=2017-05-25&Signature=Uvqz3E13092wPxNYUt3ytDojV50%3D";
            return url;
        }

        /// <summary>
        /// 获取短信状态
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="SendDate"></param>
        /// <param name="BizId"></param>
        /// <returns></returns>
        public static string SendSMSStatus2(string phoneNumber, string SendDate, string BizId)
        {
            JObject aliSms = Config.AliSms;
            String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            String accessKeyId = aliSms["accessKeyId"].ToString();
            String accessKeySecret = aliSms["accessKeySecret"].ToString();
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            QuerySendDetailsRequest request = new QuerySendDetailsRequest();

            request.CurrentPage = 1;
            request.PageSize = 12;
            request.PhoneNumber = phoneNumber;
            request.SendDate = SendDate;
            request.BizId = BizId;
            //请求失败这里会抛ClientException异常        
            var robj = acsClient.DoAction(request);
            if (robj.Status == 200)
            {
                System.IO.Stream stream = new System.IO.MemoryStream(robj.Content);
                var reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8);
                string rrrr = reader.ReadToEnd();
                return rrrr;
            }
            return "";
        }

    }
}
