using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Text;

namespace Performance.Services
{
    public class SmsService : IAutoInjection
    {
        private PerforSmsRepository _smsRepository;
        private PerforUserRepository _userRepository;
        private Application _options;
        private HuyiSmsNotify _sms;

        public SmsService(PerforSmsRepository smsRepository,
            PerforUserRepository userRepository,
            IOptions<Application> options,
            HuyiSmsNotify sms)
        {
            this._smsRepository = smsRepository;
            this._userRepository = userRepository;
            this._options = options.Value;
            this._sms = sms;
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public bool SendCode(int type, string mobile)
        {
            int? uid = null;
            if (type == (int)SmsCodeType.Login)
            {
                var user = _userRepository.GetEntity(t => t.Mobile == mobile || t.Login == mobile);
                if (user == null)
                    throw new PerformanceException("当前手机号不是系统账号");
                uid = user.ID;
            }

            var code = RandomHelper.GetSmsCode();
            if (code.Length == 0)
                throw new PerformanceException("随机验证码失败");

            sys_sms sms = new sys_sms
            {
                CreateDate = DateTime.Now,
                CreateUser = uid,
                Mobile = mobile.Trim(),
                SmsCode = code,
                Expiration = DateTime.Now.AddMinutes(_options.SmsCodeMinutes),
                CodeType = (int)SmsCodeType.Login
            };
            var message = _options.SmsTemplate.Replace("[code]", code);
            var response = _sms.SendSms(mobile, message);
            //2 是互亿返回成功状态
            if (response.code != "2")
                throw new PerformanceException(response.msg);
            return _smsRepository.Add(sms);
        }

        /// <summary>
        /// 检查验证码
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool Check(string mobile, string code)
        {
            if (string.IsNullOrEmpty(mobile) || string.IsNullOrEmpty(code))
                throw new PerformanceException("参数无效");
            var sms = _smsRepository.GetEntity(t => t.Mobile == mobile.Trim() && t.SmsCode == code.Trim());
            return (sms != null && sms.Expiration > DateTime.Now);
        }
    }
}
