using Aliyun.OSS.Model;
using CSRedis;
using JiaZhiQuan.Common.AliMessage;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Cache;

namespace JiaZhiQuan.Common.JuheAPI.SendSms
{
    /// <summary>
    /// 发送短信服务
    /// 1分钟两次，每天最多10次
    /// </summary>
    public static class JuheSendSmsUtils
    {
        const string JUHE_SMS_KEY = "d753412f9bf62957f872b4e0a12d3122";
        const int JUHE_SMS_TPL_ID = 266760;

        /// <summary>
        /// 发送验证码短信
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="client"></param>
        /// <returns></returns>
        public static async Task SendCodeSms(string mobile, string code, RedisCacheProvider redis, HttpClient client)
        {
            string dayLimitKey = CacheKeys.MobileDayLimit(mobile),
                   continuousLimitKey = CacheKeys.ContinuousLimit(mobile);
            int dayLimitCount = await redis.Get<int>(dayLimitKey);
            dynamic continuousLimit = await redis.Get<dynamic>(continuousLimitKey);
            if (dayLimitCount >= 10)
            {
                throw new LogicalException("您当日发送短信太频繁，请明天再试", ErrorCodes.SMSendDayLimitError);
            }
            if (continuousLimit != null && continuousLimit.count >= 2)
            {
                throw new LogicalException("您发送短信太频繁，请稍后再试", ErrorCodes.SMSendBusinessLimitError);
            }
            // 发送短信
            string sendParams = HttpUtility.UrlEncode($"#code#={code}");
            //使用阿里云短信服务
            var res = AliMessageHelper.SendMessage(mobile, AliMessageTemplateEnum.SMS_480085126, JsonConvert.SerializeObject(new { code }));
                            // await client.GetStringAsync($"http://v.juhe.cn/sms/send?mobile={mobile}&tpl_id={JUHE_SMS_TPL_ID}&tpl_value={sendParams}&key={JUHE_SMS_KEY}");
            if (!res.Equals("OK"))
            {
                LoggerManager.Logger.Error($"调用阿里云发送验证码短信API失败：" + JsonConvert.SerializeObject(res));
                throw new LogicalException("发送短信失败，请稍后再试[" + res + "]", ErrorCodes.Exception);
            }
            // 设置今天的发送次数
            int newDayLimitCount = dayLimitCount + 1;
            await redis.Set(dayLimitKey, newDayLimitCount, DateTime.Now.Date.AddDays(1));
            // 设置连续发送的次数
            DateTime expiration = continuousLimit is null ? DateTime.Now.AddMinutes(1) : continuousLimit.endTime;
            int newcontinuousLimitCount = continuousLimit is null ? 1 : continuousLimit.count + 1;
            dynamic newContinuousLimit = new
            {
                count = newcontinuousLimitCount,
                endTime = expiration
            };
            await redis.Set(continuousLimitKey, newContinuousLimit, expiration);
            // 查看发送结果
            //var obj = JsonConvert.DeserializeObject<JuheResponseModel1<JuheMobileAddressResultDetails>>(res);
            //if (obj.error_code != 0)
            //{
            //    LoggerManager.Logger.Error($"调用聚合发送验证码短信API失败：" + JsonConvert.SerializeObject(obj));
            //    throw new LogicalException("发送短信失败，请稍后再试[" + res + "]", ErrorCodes.Exception);
            //}
        }
    }

    public class JuheMobileAddressResultDetails
    {
        public string sid { get; set; }
        public int count { get; set; }
        public int fee { get; set; }
    }
}
