//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-03-04 13:33:56 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Domain.Share;
using MimeKit;
using MailKit.Security;
using Microsoft.AspNetCore.Authorization;
using Panda.DynamicWebApi.Attributes;
using IRaCIS.Core.Application.Auth;
using IRaCIS.Application.Services;
using IRaCIS.Core.Application.Filter;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 项目外部人员  录入流程相关
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Trial")]
    public class TrialExternalUserService : BaseService, ITrialExternalUserService
    {
        private readonly IRepository<TrialExternalUser> _trialExternalUseRepository;
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<TrialUser> _trialUserRepository;
        private readonly IRepository<TrialSiteUserSurvey> _trialSiteSurveyUserRepository;
        private readonly IRepository<TrialSiteUser> _trialSiteUserRepository;
        private readonly IMailVerificationService _mailVerificationService;

        public TrialExternalUserService(IRepository<TrialExternalUser> trialExternalUseRepository, IRepository<User> userRepository, IRepository<TrialUser> trialUserRepository,
            IRepository<TrialSiteUserSurvey> trialSiteSurveyUserRepository, IRepository<TrialSiteUser> trialSiteUserRepository,
          IMailVerificationService mailVerificationService)
        {
            _trialExternalUseRepository = trialExternalUseRepository;
            _userRepository = userRepository;
            _trialUserRepository = trialUserRepository;
            _trialSiteSurveyUserRepository = trialSiteSurveyUserRepository;
            _trialSiteUserRepository = trialSiteUserRepository;

            _mailVerificationService = mailVerificationService;
        }



        [HttpPost]
        public async Task<List<TrialExternalUserView>> GetTrialExternalUserList(TrialExternalUserQuery queryTrialExternalUser)
        {

            var trialExternalUserQueryable = _trialExternalUseRepository.Where(t => t.TrialId == queryTrialExternalUser.TrialId)
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Phone), t => t.Phone.Contains(queryTrialExternalUser.Phone))
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Email), t => t.Email.Contains(queryTrialExternalUser.Email))
                .WhereIf(!string.IsNullOrEmpty(queryTrialExternalUser.Name), t => (t.LastName + " / " + t.FirstName).Contains(queryTrialExternalUser.Name))
            .ProjectTo<TrialExternalUserView>(_mapper.ConfigurationProvider);

            return await trialExternalUserQueryable.ToListAsync();
        }



        /// <summary>
        /// 添加和更新接口   已验证邮箱和账户类型不允许添加重复项
        /// </summary>
        /// <param name="addOrEditTrialExternalUser"></param>
        /// <returns></returns>
               //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        [UnitOfWork]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        public async Task<IResponseOutput> AddOrUpdateTrialExternalUser(TrialExternalUserAddAndSendEmail addOrEditTrialExternalUser)
        {

            if (addOrEditTrialExternalUser.Id == null)
            {
                var existSysUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId);

                if (existSysUser != null)
                {
                    if (existSysUser.LastName != addOrEditTrialExternalUser.LastName || existSysUser.FirstName != addOrEditTrialExternalUser.FirstName)
                    {
                        return ResponseOutput.NotOk($"该用户在系统中的用户名为：{existSysUser.LastName + " / " + existSysUser.FirstName} 电话：{existSysUser.Phone}，与填写信息存在不一致项, 请将界面信息修改为与系统一致，再进行保存", new { existSysUser.LastName, existSysUser.FirstName, existSysUser.Phone, existSysUser.IsZhiZhun, existSysUser.IsTestUser }, ApiResponseCodeEnum.NeedTips);
                    }

                }

                //处理  生成账户

                if (await _trialExternalUseRepository.AnyAsync(t =>
                        t.Email == addOrEditTrialExternalUser.Email &&
                        t.UserTypeId == addOrEditTrialExternalUser.UserTypeId && t.TrialId == addOrEditTrialExternalUser.TrialId))
                {
                    return ResponseOutput.NotOk("系统已经存在与列表中填写的邮箱和用户类型相同的账户，请确认。");
                }



                var addEntity = _mapper.Map<TrialExternalUser>(addOrEditTrialExternalUser);

                await _trialExternalUseRepository.AddAsync(addEntity);


                var existUser = await _userRepository.FirstOrDefaultAsync(t => t.EMail == addOrEditTrialExternalUser.Email && t.UserTypeId == addOrEditTrialExternalUser.UserTypeId);
                var trialType = await _repository.Where<Trial>(t => t.Id == addOrEditTrialExternalUser.TrialId).Select(t => t.TrialType).FirstOrDefaultAsync();

                if (existUser != null)
                {
                    addEntity.IsSystemUser = true;
                    addEntity.SystemUserId = existUser.Id;

                }
                else
                {

                    //生成账户  并插入

                    var generateUser = _mapper.Map<User>(addOrEditTrialExternalUser);

                    if (trialType == TrialType.NoneOfficial)
                    {
                        generateUser.IsTestUser = true;                   
                    }

                    // 外部人员生成账号 都是外部的
                    generateUser.IsZhiZhun = false;

                    generateUser.Code = _userRepository.Select(t => t.Code).DefaultIfEmpty().Max() + 1;


                    generateUser.UserCode = AppSettings.GetCodeStr(generateUser.Code, nameof(User));

                    generateUser.UserName = generateUser.UserCode;

                    generateUser.UserTypeEnum = _repository.Where<UserType>(t => t.Id == generateUser.UserTypeId).Select(t => t.UserTypeEnum).First();

                    generateUser.Password = MD5Helper.Md5("123456");

                    generateUser.Status = UserStateEnum.Disable;

                    var newAddUser = await _repository.AddAsync(generateUser);


                    addEntity.IsSystemUser = false;
                    addEntity.SystemUserId = newAddUser.Id;


                    existUser = newAddUser;

                }

                #region 验证用户 能否加入

                if (trialType == TrialType.OfficialTrial || trialType == TrialType.Training)
                {

                    if (existUser.IsTestUser)
                    {
                        throw new BusinessValidationFailedException("正式类型 、培训类型的项目 不允许加入测试用户 ");

                    }
                }

                if (trialType == TrialType.NoneOfficial)
                {

                    if (existUser.IsTestUser == false )
                    {
                        throw new BusinessValidationFailedException("测试项目  不允许加入正式用户 ");
                    }
                }

                #endregion


                await _trialExternalUseRepository.SaveChangesAsync();


                //添加的时候就发邮件  现在省略
                if (addOrEditTrialExternalUser.IsSendEmail)
                {
                    await SendExternalUserJoinEmail(new TrialExternalUserSendEmail()
                    {
                        BaseUrl = addOrEditTrialExternalUser.BaseUrl,
                        RouteUrl = addOrEditTrialExternalUser.RouteUrl,
                        TrialId = addOrEditTrialExternalUser.TrialId,
                        SendUsers = new List<UserEmail>()
                        {
                            new UserEmail()
                            {
                                Id = addEntity.Id,
                                Email=addEntity.Email,
                                IsSystemUser=addEntity.IsSystemUser,
                                SystemUserId=addEntity.SystemUserId
                            }
                        }
                    });
                }


                return ResponseOutput.Ok(addEntity.Id.ToString());

            }
            else
            {
                return ResponseOutput.NotOk("人员信息不支持编辑，请删除后重新添加。");

            }
        }




        [HttpDelete("{trialExternalUserId:guid}/{isSystemUser:bool}/{systemUserId}")]
               //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        public async Task<IResponseOutput> DeleteTrialExternalUser(Guid trialExternalUserId, bool isSystemUser, Guid systemUserId)
        {
            var trialExternalUser = await _trialExternalUseRepository.FirstOrDefaultAsync(t => t.Id == trialExternalUserId);

            if (await _trialUserRepository.AnyAsync(t => t.TrialId == trialExternalUser.TrialId && t.UserId == trialExternalUser.SystemUserId))
            {
                return ResponseOutput.NotOk("当前用户已参与到项目，不允许删除");
            }


            var success = await _trialExternalUseRepository.BatchDeleteNoTrackingAsync(t => t.Id == trialExternalUserId);

            if (isSystemUser == false)
            {
                await _userRepository.BatchDeleteNoTrackingAsync(t => t.Id == systemUserId);
            }

            return ResponseOutput.Result(success);
        }


        //New  省掉邀请流程
        [HttpPost]
               //[Authorize(Policy = IRaCISPolicy.PM_APM)]
        [TypeFilter(typeof(TrialResourceFilter), Arguments = new object[] { "AfterStopCannNotOpt" })]
        [UnitOfWork]
        public async Task<IResponseOutput> SendExternalUserJoinEmail(TrialExternalUserSendEmail sendEmail)
        {
            var trialId = sendEmail.TrialId;

            foreach (var userInfo in sendEmail.SendUsers)
            {
                var userId = userInfo.SystemUserId;




                //判断TrialUser中是否存在  不存在就插入  注意退出了，也不能再加进来
                if (!await _trialUserRepository.AnyAsync(t => t.TrialId == trialId && t.UserId == userId, true))
                {

                    await _repository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId, JoinTime = DateTime.Now });

                    await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == userId, u => new User() { Status = UserStateEnum.Enable });

                    await _trialExternalUseRepository.BatchUpdateNoTrackingAsync(t => t.Id == userInfo.Id, u => new TrialExternalUser() { IsJoin = true });


                    await _userRepository.SaveChangesAsync();
                }

                await _mailVerificationService.ExternalUserJoinEmail(trialId, userId, sendEmail.BaseUrl, sendEmail.RouteUrl);

            }

            return ResponseOutput.Ok();

        }






        #region 老版本流程  现在废弃

        /// <summary>
        /// 勾选用户 批量发送邮件 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SendInviteEmail(TrialExternalUserSendEmail sendEmail)
        {

            var trialInfo = await _repository.FirstOrDefaultAsync<Trial>(t => t.Id == sendEmail.TrialId);

            foreach (var userInfo in sendEmail.SendUsers)
            {
                var messageToSend = new MimeMessage();
                //发件地址
                messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
                //收件地址
                messageToSend.To.Add(new MailboxAddress(String.Empty, userInfo.Email));
                //主题
                messageToSend.Subject = $"[{trialInfo.ResearchProgramNo}] 邀请";

                //var baseApiUrl = sendEmail.BaseUrl.Remove(sendEmail.BaseUrl.IndexOf("#")) + "api";

                var builder = new BodyBuilder();

                var sysUserInfo = (await _userRepository.Where(t => t.Id == userInfo.SystemUserId).FirstOrDefaultAsync()).IfNullThrowException();


                builder.HtmlBody = @$"<body style='font-family: 微软雅黑;padding: 0;margin: 0;'>
                                      <div style='padding-left: 40px;background: #f6f6f6'>
                                        <div style='padding-top: 20px;'>
                                          <div style='line-height: 40px;font-size: 18px'>
                                            {sysUserInfo.LastName + "/" + sysUserInfo.FirstName}:
                                          </div>
                                          <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>
                                           您好，展影医疗作为 实验方案号：{trialInfo.ResearchProgramNo} 项目的IRC供应商，诚邀您参加该项目IRC相关工作，欢迎您提供指导和建议，非常感谢！
                                          </div>
                                         
                                 

                                          <a href='  {sendEmail.RouteUrl + "?Id=" + userInfo.Id + "&IsExternalUser=1"}' style='margin-left:60px;font-size:14px;text-decoration: none;display: inline-block;height: 40px;width: 140px;background: #00D1B2;color:#fff;border-radius: 5px;line-height: 40px;text-align: center;margin-bottom: 100px;'>
                                            查看并确认
                                          </a>   
                                        </div>櫭
                                      </div>
                                    </body>";


                //< form action = '#' method = 'post' >

                //                    < button type = 'submit' style = 'margin-left:60px;font-size:14px;text-decoration: none;display: inline-block;height: 40px;width: 140px;background: #00D1B2;color:#fff;border-radius: 5px;line-height: 40px;text-align: center;border:none;margin-bottom: 100px;cursor: pointer' > 查看并确认 </ button >

                //                    </ form >
                messageToSend.Body = builder.ToMessageBody();

                using (var smtp = new MailKit.Net.Smtp.SmtpClient())
                {
                    smtp.MessageSent += (sender, args) =>
                    {

                        _ = _trialExternalUseRepository.BatchUpdateNoTrackingAsync(t => t.Id == userInfo.Id, u => new TrialExternalUser() { InviteState = TrialExternalUserStateEnum.HasSend, ConfirmTime = null, RejectReason = String.Empty, ExpireTime = DateTime.Now.AddDays(7) }).Result;

                    };

                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await smtp.ConnectAsync("smtp.163.com", 465, SecureSocketOptions.StartTls);

                    await smtp.AuthenticateAsync("iracis_grr@163.com", "XLWVQKZAEKLDWOAH");

                    await smtp.SendAsync(messageToSend);

                    await smtp.DisconnectAsync(true);
                }


            }

            return ResponseOutput.Ok();

        }




        /// <summary>
        ///  不带Token 访问  用户选择   参与  不参与    Id:  TrialExternalUserId   加入发送邮件
        /// </summary>
        /// <param name="editTrialUserPreparation"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IResponseOutput> TrialExternalUserJoinTrial(TrialExternalUserConfirm editTrialUserPreparation)
        {

            var needUpdate = await _trialExternalUseRepository.FirstOrDefaultAsync(t => t.Id == editTrialUserPreparation.Id);

            if (DateTime.Now > needUpdate.ExpireTime)
            {
                return ResponseOutput.NotOk("邀请加入时间已过期，重新被邀请后才可以进行确认操作");
            }

            _mapper.Map(editTrialUserPreparation, needUpdate);

            needUpdate.InviteState = editTrialUserPreparation.IsJoin == true ? TrialExternalUserStateEnum.UserConfirmed : TrialExternalUserStateEnum.UserReject;


            var trialId = needUpdate.TrialId;
            var userId = needUpdate.SystemUserId;

            //判断TrialUser中是否存在  不存在就插入
            if (!await _trialUserRepository.AnyAsync(t => t.TrialId == trialId && t.UserId == userId))
            {

                await _trialUserRepository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId, JoinTime = DateTime.Now });

            }

            var success = await _trialExternalUseRepository.SaveChangesAsync();


            if (editTrialUserPreparation.IsJoin == true)
            {
                var trialInfo = await _repository.FirstOrDefaultAsync<Trial>(t => t.Id == needUpdate.TrialId);

                var messageToSend = new MimeMessage();
                //发件地址
                messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
                //收件地址
                messageToSend.To.Add(new MailboxAddress(String.Empty, needUpdate.Email));
                //主题
                messageToSend.Subject = $"[来自展影IRC] [{trialInfo.ResearchProgramNo}] 账户信息";

                var builder = new BodyBuilder();


                var sysUserInfo = (await _userRepository.Where(t => t.Id == needUpdate.SystemUserId).Include(t => t.UserTypeRole).FirstOrDefaultAsync()).IfNullThrowException();

                int verificationCode = new Random().Next(100000, 1000000);

                if (sysUserInfo.IsFirstAdd)
                {
                    await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == sysUserInfo.Id,
                        u => new User() { Password = MD5Helper.Md5(verificationCode.ToString()) });
                }

                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'>
                                            {sysUserInfo.LastName + "/" + sysUserInfo.FirstName}:
                                          </div>
                                          <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>                                          
                                            您好，欢迎您参加项目  实验方案号：{trialInfo.ResearchProgramNo}IRC相关工作。该项目采用电子化工作流，系统及您的账号信息如下：                                                                                                                                 
                                          </div>
                                          <div style='border: 1px solid #eee;box-sizing:border-box;width: 80%;background: #fff;padding: 20px;line-height: 40px;font-size: 14px;border-radius: 5px;margin-left: 60px;margin-bottom: 30px;'>
                                            <div>
                                              项目编号: {trialInfo.TrialCode}
                                            </div>
                                            <div>
                                              试验方案号: {trialInfo.ResearchProgramNo}
                                            </div>
                                            <div>
                                              试验名称: {trialInfo.ExperimentName}
                                            </div>
                                            <div>
                                              用户名: {sysUserInfo.UserName}
                                            </div>
                                            <div>
                                              密码: {(sysUserInfo.IsFirstAdd ? verificationCode.ToString() + "(请在登录后进行修改)" : "***(您已有账号, 若忘记密码, 请通过邮箱找回)")}
                                            </div>
                                            <div>
                                              角色: {sysUserInfo.UserTypeRole.UserTypeShortName}
                                            </div>
                                            <div>
                                              系统登录地址: {editTrialUserPreparation.BaseUrl} 
                                            </div>
                                          </div>
                                        
                                        </div>
                                      </div>
                                    </body>";

                messageToSend.Body = builder.ToMessageBody();

                using (var smtp = new MailKit.Net.Smtp.SmtpClient())
                {

                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await smtp.ConnectAsync("smtp.163.com", 465, SecureSocketOptions.StartTls);

                    await smtp.AuthenticateAsync("iracis_grr@163.com", "XLWVQKZAEKLDWOAH");

                    await smtp.SendAsync(messageToSend);

                    await smtp.DisconnectAsync(true);
                }

                await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == userId, u => new User() { Status = UserStateEnum.Enable });


            }
            return ResponseOutput.Ok();

            //else
            //{
            //    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'>
            //                                    {sysUserInfo.LastName + "/" + sysUserInfo.FirstName}:
            //                                  </div>
            //                                  <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>
            //                                   您好，您拒绝了参加 {trialInfo.ResearchProgramNo} 项目IRC相关工作的邀请。详细信息如下：                                                                                                                                 
            //                                  </div>
            //                                  <div style='border: 1px solid #eee;box-sizing:border-box;width: 80%;background: #fff;padding: 20px;line-height: 40px;font-size: 14px;border-radius: 5px;margin-left: 60px;margin-bottom: 30px;'>
            //                                    <div>
            //                                      项目编号: {trialInfo.TrialCode}
            //                                    </div>
            //                                    <div>
            //                                      试验方案号: {trialInfo.ResearchProgramNo}
            //                                    </div>
            //                                    <div>
            //                                      试验名称: {trialInfo.ExperimentName}
            //                                    </div>
            //                                    <div>
            //                                      用户名: {sysUserInfo.UserName}
            //                                    </div>                                             
            //                                    <div>
            //                                      角色: {sysUserInfo.UserTypeRole.UserTypeShortName}
            //                                    </div>                                              
            //                                  </div>
            //                                </div>
            //                              </div>
            //                            </body>";
            //}






        }

        /// <summary>
        ///  不带Token 访问  Site调研用户 加入项目   Id:  TrialSiteSurveyUserId
        /// </summary>
        /// <param name="editInfo"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IResponseOutput> TrialSiteSurveyUserJoinTrial(TrialExternalUserConfirm editInfo)
        {

            var needUpdate = (await _trialSiteSurveyUserRepository.Where(t => t.Id == editInfo.Id, true).Include(t => t.TrialSiteSurvey).FirstOrDefaultAsync()).IfNullThrowException();

            var revieweUser = await _userRepository.FirstOrDefaultAsync(t => t.Id == needUpdate.TrialSiteSurvey.ReviewerUserId);


            if (DateTime.Now > needUpdate.ExpireTime)
            {
                return ResponseOutput.NotOk("邀请加入时间已过期，重新被邀请后才可以进行确认操作");
            }

            _mapper.Map(editInfo, needUpdate);

            needUpdate.InviteState = editInfo.IsJoin == true ? TrialSiteUserStateEnum.UserConfirmed : TrialSiteUserStateEnum.UserReject;


            if (needUpdate.SystemUserId == null)
            {
                return ResponseOutput.NotOk("调研表系统用户Id 存储有问题");
            }

            var trialId = needUpdate.TrialSiteSurvey.TrialId;
            var siteId = needUpdate.TrialSiteSurvey.SiteId;
            var userId = (Guid)needUpdate.SystemUserId;


            if (!await _trialUserRepository.AnyAsync(t => t.TrialId == trialId && t.UserId == userId))
            {
                await _trialUserRepository.AddAsync(new TrialUser() { TrialId = trialId, UserId = userId, JoinTime = DateTime.Now });

                await _trialSiteUserRepository.AddAsync(new TrialSiteUser() { TrialId = trialId, SiteId = siteId, UserId = userId });

                await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == needUpdate.SystemUserId, u => new User() { Status = UserStateEnum.Enable });


            }

            var success = await _trialExternalUseRepository.SaveChangesAsync();

            var trialInfo = await _repository.FirstOrDefaultAsync<Trial>(t => t.Id == needUpdate.TrialSiteSurvey.TrialId);


            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
            //收件地址
            messageToSend.To.Add(new MailboxAddress(String.Empty, editInfo.IsJoin == true ? needUpdate.Email : revieweUser.EMail));
            //主题
            messageToSend.Subject = $"[来自展影IRC] [{trialInfo.ResearchProgramNo}] 账户信息";


            var builder = new BodyBuilder();


            var sysUserInfo = await _userRepository.Where(t => t.Id == needUpdate.SystemUserId).Include(t => t.UserTypeRole).FirstOrDefaultAsync();

            int verificationCode = new Random().Next(100000, 1000000);

            if (sysUserInfo.IsFirstAdd)
            {
                await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == sysUserInfo.Id,
                    u => new User() { Password = MD5Helper.Md5(verificationCode.ToString()) });
            }

            if (editInfo.IsJoin == true)
            {
                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'>
                                            {sysUserInfo.LastName + "/" + sysUserInfo.FirstName}:
                                          </div>
                                          <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>
                                           您好，欢迎您参加项目  实验方案号： {trialInfo.ResearchProgramNo} IRC相关工作。该项目采用电子化工作流，系统及您的账号信息如下：
                                          </div>
                                          <div style='border: 1px solid #eee;box-sizing:border-box;width: 80%;background: #fff;padding: 20px;line-height: 40px;font-size: 14px;border-radius: 5px;margin-left: 60px;margin-bottom: 30px;'>
                                            <div>
                                              项目编号: {trialInfo.TrialCode}
                                            </div>
                                            <div>
                                              试验方案号: {trialInfo.ResearchProgramNo}
                                            </div>
                                            <div>
                                              试验名称: {trialInfo.ExperimentName}
                                            </div>
                                            <div>
                                              用户名: {sysUserInfo.UserName}
                                            </div>
                                            <div>
                                              密码: {(sysUserInfo.IsFirstAdd ? verificationCode.ToString() + "(请在登录后进行修改)" : "***(您已有账号, 若忘记密码, 请通过邮箱找回)")}
                                            </div>
                                            <div>
                                              角色: {sysUserInfo.UserTypeRole.UserTypeShortName}
                                            </div>
                                            <div>
                                              系统登录地址: {editInfo.BaseUrl} 
                                            </div>
                                          </div>
                                        
                                        </div>
                                      </div>
                                    </body>";

                messageToSend.Body = builder.ToMessageBody();

                using (var smtp = new MailKit.Net.Smtp.SmtpClient())
                {

                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await smtp.ConnectAsync("smtp.163.com", 465, SecureSocketOptions.StartTls);

                    await smtp.AuthenticateAsync("iracis_grr@163.com", "XLWVQKZAEKLDWOAH");

                    await smtp.SendAsync(messageToSend);

                    await smtp.DisconnectAsync(true);
                }
            }
            //else
            //{

            //    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'>
            //                                    {revieweUser.LastName + "/" + revieweUser.FirstName}:                                              
            //                                  </div>
            //                                  <div style='line-height: 40px;padding-left: 40px;margin-bottom: 10px;'>
            //                                   您好，{sysUserInfo.LastName + "/" + sysUserInfo.FirstName} 拒绝了参加 {trialInfo.ResearchProgramNo} 项目IRC相关工作的邀请。详细信息如下：                                                                                                                                 
            //                                  </div>
            //                                  <div style='border: 1px solid #eee;box-sizing:border-box;width: 80%;background: #fff;padding: 20px;line-height: 40px;font-size: 14px;border-radius: 5px;margin-left: 60px;margin-bottom: 30px;'>
            //                                    <div>
            //                                      项目编号: {trialInfo.TrialCode}
            //                                    </div>
            //                                    <div>
            //                                      试验方案号: {trialInfo.ResearchProgramNo}
            //                                    </div>
            //                                    <div>
            //                                      试验名称: {trialInfo.ExperimentName}
            //                                    </div>
            //                                    <div>
            //                                      用户名: {sysUserInfo.UserName}
            //                                    </div>                                             
            //                                    <div>
            //                                      角色: {sysUserInfo.UserTypeRole.UserTypeShortName}
            //                                    </div> 
            //                                    <div>
            //                                      拒绝原因: {editInfo.RejectReason}
            //                                    </div>   
            //                                  </div>
            //                                </div>
            //                              </div>
            //                            </body>";

            //}





            return ResponseOutput.Ok();

        }


        /// <summary>
        /// 不带Token 访问   页面获取项目基本信息  和参与情况 (已经确认了 就不允许再次确认)  Id:  TrialExternalUserId/TrialSiteSurveyUserId  
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isExternalUser"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<TrialInfoWithPreparationInfo> JoinBasicInfo(Guid id, bool isExternalUser)
        {
            if (isExternalUser)
            {
                return (await _trialExternalUseRepository.Where(t => t.Id == id)
                    .ProjectTo<TrialInfoWithPreparationInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            }
            else
            {
                return (await _trialSiteSurveyUserRepository.Where(t => t.Id == id)
                    .ProjectTo<TrialInfoWithPreparationInfo>(_mapper.ConfigurationProvider).FirstOrDefaultAsync()).IfNullThrowException();
            }

        }





        /// <summary>
        /// 加入项目    
        /// </summary>
        /// <param name="trialId"></param>
        /// <param name="trialExternalUserId"></param>
        /// <returns></returns>
        [HttpGet("{trialId:guid}/{trialExternalUserId:guid}")]
        [NonDynamicMethod]
        public async Task<IResponseOutput> UserConfirmJoinTrial(Guid trialId, Guid trialExternalUserId)
        {

            var externalUser = await _trialExternalUseRepository.FirstOrDefaultAsync(t => t.Id == trialExternalUserId);


            //判断TrialUser中是否存在  不存在就插入
            if (!await _repository.AnyAsync<TrialUser>(t => t.TrialId == trialId && t.UserId == externalUser.SystemUserId))
            {
                await _repository.AddAsync(new TrialUser() { TrialId = trialId, UserId = (Guid)externalUser.SystemUserId, JoinTime = DateTime.Now });

                await _trialExternalUseRepository.BatchUpdateNoTrackingAsync(t => t.Id == trialExternalUserId,
                    u => new TrialExternalUser() { InviteState = TrialExternalUserStateEnum.UserConfirmed });

                await _userRepository.BatchUpdateNoTrackingAsync(t => t.Id == externalUser.SystemUserId, u => new User() { Status = UserStateEnum.Enable });

                await _userRepository.SaveChangesAsync();
            }



            return ResponseOutput.Ok();


        }

        #endregion





    }
}
