using IRaCIS.Core.Domain.Share;
using MimeKit;
using IRaCIS.Core.Application.Helper;
using MailKit;
using Microsoft.AspNetCore.Hosting;
using IRaCIS.Core.Application.Auth;
using AutoMapper;
using IRaCIS.Application.Contracts;

namespace IRaCIS.Application.Services
{
    public interface IMailVerificationService
    {
        Task SendMail(Guid userId, string userName, string emailAddress, int verificationCode);

        Task AnolymousSendEmail(string researchProgramNo, string emailAddress, int verificationCode);

        Task SendMailEditEmail(Guid userId, string userName, string emailAddress, int verificationCode);

        Task AnolymousSendEmailForResetAccount(string emailAddress, int verificationCode);

        Task AddUserSendEmailAsync(Guid userId,  string routeUrl);

        Task AdminResetPwdSendEmailAsync(Guid userId);
    }

    public class MailVerificationService : IMailVerificationService
    {
        private readonly IRepository<VerificationCode> _verificationCodeRepository;

        private readonly IRepository<SystemBasicData> _systemBasicDatarepository;

        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly IRepository<User> _userRepository;

        private readonly ITokenService _tokenService;

        private readonly IMapper _mapper;


        public MailVerificationService(IRepository<VerificationCode> verificationCodeRepository,
            IRepository<SystemBasicData> systemBasicDatarepository,
            IWebHostEnvironment hostEnvironment, IRepository<User> userRepository, ITokenService tokenService, IMapper mapper)
        {
            _verificationCodeRepository = verificationCodeRepository;
            _systemBasicDatarepository = systemBasicDatarepository;

            _hostEnvironment = hostEnvironment;

            _mapper = mapper;

            _tokenService = tokenService;
            _userRepository = userRepository;

        }

        //重置邮箱
        public async Task SendMailEditEmail(Guid userId, string userName, string emailAddress, int verificationCode)
        {


            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(userName, emailAddress));
            //主题
            messageToSend.Subject = "[来自展影IRC] 关于重置邮箱的提醒";

            var builder = new BodyBuilder();


            var pathToFile = _hostEnvironment.WebRootPath
                          + Path.DirectorySeparatorChar.ToString()
                          + "EmailTemplate"
                          + Path.DirectorySeparatorChar.ToString()
                          + "UserOptCommon.html";

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                var templateInfo = SourceReader.ReadToEnd();


                builder.HtmlBody = string.Format(templateInfo,
                    $" 尊敬的 {userName} , ",
                    "您正在进行邮箱重置操作",
                    verificationCode
                    );
            }

            messageToSend.Body = builder.ToMessageBody();



            EventHandler<MessageSentEventArgs> sucessHandle = (sender, args) =>
          {
              // args.Response 
              var code = verificationCode.ToString();
              _ = _verificationCodeRepository.AddAsync(new VerificationCode()
              {
                  CodeType = 0,
                  HasSend = true,
                  Code = code,
                  UserId = userId,
                  ExpirationTime = DateTime.Now.AddMinutes(3)
              }).Result;
              _ = _verificationCodeRepository.SaveChangesAsync().Result;

          };


            await SendEmailHelper.SendEmailAsync(messageToSend, sucessHandle);


        }




        //不登录  通过邮箱重置密码
        public async Task AnolymousSendEmailForResetAccount(string emailAddress, int verificationCode)
        {
            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(String.Empty, emailAddress));
            //主题
            messageToSend.Subject = "[来自展影IRC] 关于重置密码的提醒";



            var builder = new BodyBuilder();

            var pathToFile = _hostEnvironment.WebRootPath
                        + Path.DirectorySeparatorChar.ToString()
                        + "EmailTemplate"
                        + Path.DirectorySeparatorChar.ToString()
                        + "UserOptCommon.html";

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                var templateInfo = SourceReader.ReadToEnd();


                builder.HtmlBody = string.Format(templateInfo,
                    "",
                   "您正在进行邮箱重置密码操作",
                    verificationCode
                    );
            }



            messageToSend.Body = builder.ToMessageBody();


            EventHandler<MessageSentEventArgs> sucessHandle = (sender, args) =>
             {
                 var code = verificationCode.ToString();
                 _ = _verificationCodeRepository.AddAsync(new VerificationCode()
                 {
                     CodeType = Core.Domain.Share.VerifyType.Email,
                     HasSend = true,
                     Code = code,
                     UserId = Guid.Empty,//此时不知道用户
                     EmailOrPhone = emailAddress,
                     ExpirationTime = DateTime.Now.AddMinutes(3)
                 }).Result;
                 _ = _verificationCodeRepository.SaveChangesAsync().Result;
             };



            await SendEmailHelper.SendEmailAsync(messageToSend, sucessHandle);
        }

        //中心调研 登陆
        public async Task AnolymousSendEmail(string researchProgramNo, string emailAddress, int verificationCode)
        {


            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(String.Empty, emailAddress));
            //主题
            messageToSend.Subject = $"[来自展影IRC] [{researchProgramNo}] 关于中心调研的提醒";




            var builder = new BodyBuilder();

            var pathToFile = _hostEnvironment.WebRootPath
                      + Path.DirectorySeparatorChar.ToString()
                      + "EmailTemplate"
                      + Path.DirectorySeparatorChar.ToString()
                      + "UserOptCommon.html";

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                var templateInfo = SourceReader.ReadToEnd();


                builder.HtmlBody = string.Format(templateInfo,
                    "",
                   "您正在参与展影医疗IRC项目中心调研工作",
                    verificationCode
                    );
            }

            messageToSend.Body = builder.ToMessageBody();



            EventHandler<MessageSentEventArgs> sucessHandle = (sender, args) =>
            {
                // args.Response 
                var code = verificationCode.ToString();
                _ = _verificationCodeRepository.AddAsync(new VerificationCode()
                {
                    CodeType = VerifyType.Email,
                    HasSend = true,
                    Code = code,
                    UserId = Guid.Empty,//此时不知道用户
                    EmailOrPhone = emailAddress,
                    ExpirationTime = DateTime.Now.AddMinutes(3)
                }).Result;
                _ = _verificationCodeRepository.SaveChangesAsync().Result;
            };



            await SendEmailHelper.SendEmailAsync(messageToSend, sucessHandle);


        }



        //添加用户发送邮件
        public async Task AddUserSendEmailAsync(Guid userId,  string routeUrl)
        {
            var sysUserInfo = (await _userRepository.Where(t => t.Id == userId).Include(t => t.UserTypeRole).FirstOrDefaultAsync()).IfNullThrowException();


            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(sysUserInfo.FullName, sysUserInfo.EMail));
            //主题
            messageToSend.Subject = "[来自展影IRC] 关于创建账户的提醒";



            var builder = new BodyBuilder();

            var pathToFile = _hostEnvironment.WebRootPath
                        + Path.DirectorySeparatorChar.ToString()
                        + "EmailTemplate"
                        + Path.DirectorySeparatorChar.ToString()
                        + "AdminAddUser.html";

            var token = _tokenService.GetToken(IRaCISClaims.Create(_mapper.Map<UserBasicInfo>(sysUserInfo)));

            routeUrl = routeUrl + "?UserId=" + sysUserInfo.Id + "&Email=" + sysUserInfo.EMail + "&UserName=" + sysUserInfo.UserName + "&UserType=" + sysUserInfo.UserTypeRole.UserTypeShortName + "&access_token=" + token;

            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                var templateInfo = SourceReader.ReadToEnd();


                builder.HtmlBody = string.Format(templateInfo,
                   sysUserInfo.FullName,
                   sysUserInfo.UserName,
                   sysUserInfo.UserTypeRole.UserTypeShortName,
                    routeUrl
                    );
            }



            messageToSend.Body = builder.ToMessageBody();
             

            await SendEmailHelper.SendEmailAsync(messageToSend);
        }

        //管理员重置密码发送邮件
        public async Task AdminResetPwdSendEmailAsync(Guid userId)
        {
            var sysUserInfo = (await _userRepository.Where(t => t.Id == userId).Include(t => t.UserTypeRole).FirstOrDefaultAsync()).IfNullThrowException();

            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(sysUserInfo.FullName, sysUserInfo.EMail));
            //主题
            messageToSend.Subject = "[来自展影IRC] 关于重置账户密码的提醒";



            var builder = new BodyBuilder();

            var pathToFile = _hostEnvironment.WebRootPath
                        + Path.DirectorySeparatorChar.ToString()
                        + "EmailTemplate"
                        + Path.DirectorySeparatorChar.ToString()
                        + "AdminResetUser.html";


            using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
            {
                var templateInfo = SourceReader.ReadToEnd();


                builder.HtmlBody = string.Format(templateInfo,
                   sysUserInfo.FullName,
                   sysUserInfo.UserName,
                   sysUserInfo.UserTypeRole.UserTypeShortName,
                    StaticData.DefaultPassword
                    );
            }



            messageToSend.Body = builder.ToMessageBody();


            await SendEmailHelper.SendEmailAsync(messageToSend);
        }


        //废弃  添加用户发送邮件
        public async Task SendMail(Guid userId, string userName, string emailAddress, int verificationCode)
        {


            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(userName, emailAddress));
            //主题
            messageToSend.Subject = "[来自展影IRC] 关于重置邮箱的提醒";



            var builder = new BodyBuilder();

            builder.HtmlBody = @$"<body style='font-family: 微软雅黑;padding: 0;margin: 0;'>
                                      <div style='padding-left: 40px;background: #f6f6f6'>
                                        <div style='padding-top: 20px;padding-bottom:40px'>
                                          <div style='line-height: 40px;font-size: 18px'>
                                          您好：
                                          </div>
                                          <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>  
                                              感谢您使用展影云平台。                                                                                                                            
                                          </div>
                                            <div>
                                              您正在进行邮箱重置操作，验证码是: {verificationCode}，请在3分钟内输入该验证码，进行后续操作。如非本人操作，请忽略该邮件。
                                            </div>
                                            <div>
                                             此邮件属系统自动发出，无需回复。
                                            </div>   
                                            <div>
                                             祝您顺利！/Best Regards。
                                            </div>
                                            <div>
                                             上海展影医疗科技有限公司
                                            </div>   
                                        </div>
                                      </div>
                                    </body>";


            messageToSend.Body = builder.ToMessageBody();


            EventHandler<MessageSentEventArgs> sucessHandle = (sender, args) =>
            {
                // args.Response 
                var code = verificationCode.ToString();
                _ = _verificationCodeRepository.AddAsync(new VerificationCode()
                {
                    CodeType = 0,
                    HasSend = true,
                    Code = code,
                    UserId = userId,
                    ExpirationTime = DateTime.Now.AddMinutes(3)
                }).Result;
                _ = _verificationCodeRepository.SaveChangesAsync().Result;
            };

            await SendEmailHelper.SendEmailAsync(messageToSend, sucessHandle);


        }


    }
}