/// <summary>
        /// 尝试创建用户,并发送注册邮件到用户邮箱
        /// </summary>
        /// <param name="registerUser"></param>
        /// <param name="roleType"></param>
        /// <returns></returns>
        private async Task <ValueTuple <bool, MoUserInfo> > TryCreateUser(MoUserInfoSimple registerUser, RoleType roleType)
        {
            if (registerUser == null)
            {
                throw new ArgumentNullException(nameof(registerUser));
            }

            // 因为我们要考虑到已经入库了但邮箱还未激活的用户(也就是还未完成全部注册流程的用户)可能会重复注册,所以我这里改成这样子
            User user = _uf.UserRepository.GetFirstOrDefault(x => x.Email.Equals(registerUser.UserName, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                using (var trans = _uf.BeginTransaction())
                {
                    try
                    {
                        user = await _uf.UserRepository.CreateUserAsync(registerUser);

                        //_uf.SaveChanges();
                        var role = await _uf.RoleRepository.GetOrAddAsync(roleType);

                        //_uf.SaveChanges();
                        var userToRole = new UserToRole
                        {
                            UserId = user.Id,
                            RoleId = role.Id
                        };

                        await _uf.UserToRoleRepository.InsertAsync(userToRole);

                        await _uf.SaveChangesAsync();

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        this.MsgBox("注册用户失败");
                        return(false, null);
                    }
                }
            }

            var userInfo = new MoUserInfo
            {
                Id         = user.Id,
                UserStatus = (int)user.UserStatus,
                Email      = user.Email,
                HeadPhoto  = user.HeadPhoto,
                UserName   = user.UserName,
                Roles      = roleType.ToString()
            };

            HttpContext.AddUserInfo(userInfo);
            this.MsgBox("注册用户成功,请查看您的邮箱,确认激活!");
            return(true, userInfo);
        }
        public async Task <IActionResult> DeleteAdmin(int id)
        {
            var data = new MoData();

            HttpContext.TryGetUserInfo(out var userInfo);
            using (var trans = _uf.BeginTransaction())
            {
                try
                {
                    var bbs = await _uf.BBSRepository.GetAsync(x => x.UserId == id);

                    if (bbs == null)
                    {
                        data.IsOk = false;
                        return(Json(data));
                    }

                    bbs.UserId = userInfo.Id;
                    _uf.BBSRepository.Update(bbs);

                    var role = await _uf.RoleRepository.GetAsync(x => x.RoleName.Equals("User", StringComparison.OrdinalIgnoreCase));

                    var userRole = await _uf.UserToRoleRepository.GetAsync(x => x.UserId == id);

                    userRole.RoleId = role.Id;
                    _uf.UserToRoleRepository.Update(userRole);

                    if (await _uf.SaveChangesAsync() > 0)
                    {
                        data.IsOk = true;
                    }
                    else
                    {
                        data.IsOk = false;
                    }

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    _logger.LogError(id, $"撤销版主失败-{ex.Message}:{DateTime.Now.ToStandardFormatString()}");
                    _uf.SaveChanges();
                    data.IsOk = false;
                }
            }


            return(Json(data));
        }
        public async Task <IActionResult> UpHeadPhoto(int id)
        {
            HttpContext.TryGetUserInfo(out var userInfo);
            ViewData["Role"] = userInfo.Roles.ToLower();
            var file = HttpRequest.Form.Files.Where(x =>
                                                    x.Name == "myHeadPhoto" &&
                                                    x.ContentType.Contains("image"))
                       .SingleOrDefault();

            if (file == null)
            {
                this.MsgBox("请选择上传的头像图片!");
                return(View(userInfo));
            }


            var maxSize = 1024 * 1024 * 4; // 图片大小不超过4M

            if (file.Length > maxSize)
            {
                this.MsgBox("头像图片不能大于4M");
                return(View(userInfo));
            }

            var directory     = RootConfiguration.Root + Path.DirectorySeparatorChar + _mapSetting.UpHeadPhotoPath;
            var directoryInfo = new DirectoryInfo(directory);

            directoryInfo.DeleteAll(userInfo.Email);

            var fileExtend  = file.FileName.Substring(file.FileName.LastIndexOf('.'));
            var fileNewName = $"{userInfo.Email}-{DateTime.Now.ToString("yyyyMMddHHssfff")}{fileExtend}";
            var path        = Path.Combine(directory, fileNewName);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                await file.CopyToAsync(stream); // 读取上传的图片并保存
            }

            // 更新数据
            var viewPath = $"{_mapSetting.ViewHeadPhotoPath}/{fileNewName}";

            using (var trans = _uf.BeginTransaction())
            {
                try
                {
                    var user = await _uf.UserRepository.GetByIdAsync(userInfo.Id);

                    if (user == null)
                    {
                        this.MsgBox("上传失败,请稍后重试!");
                        return(View(userInfo));
                    }
                    user.HeadPhoto = $"../../wwwroot{viewPath}";
                    _uf.UserRepository.Update(user);
                    var result = await _uf.SaveChangesAsync();

                    if (result > 0)
                    {
                        userInfo.HeadPhoto = user.HeadPhoto;

                        HttpContext.DeleteUserInfo();
                        HttpContext.AddUserInfo(userInfo);

                        this.MsgBox("上传成功!");
                        trans.Commit();
                    }
                    else
                    {
                        this.MsgBox("上传失败,请稍后再试!");
                        trans.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    this.MsgBox("上传失败,请稍后再试!");
                    trans.Rollback();
                    _logger.LogError(userInfo.Id, "上传头像操作失败");
                    _uf.SaveChanges();
                    trans.Commit();
                }
            }

            return(View(userInfo));
        }
        public async Task <IActionResult> SubmitReply(MoSubComment subComment)
        {
            if (subComment == null &&
                (subComment.ReplyType == ReplyType.Text &&
                 String.IsNullOrWhiteSpace(subComment.Message)))
            {
                return(ReturnJsonMsg(false, "评论内容不能为空"));
            }

            HttpContext.TryGetUserInfo(out var userInfo);
            Topic topic = await _uf.TopicRepository.GetAsync(x => x.Id == subComment.TopicId &&
                                                             x.TopicStatus != TopicStatus.Disabled);

            if (topic == null)
            {
                return(ReturnJsonMsg(false, "找不到帖子,该帖子已删除或被禁用"));
            }

            string message = String.Empty;

            if (subComment.ReplyType == ReplyType.Image)
            {
                var file = HttpRequest.Form.Files.Where(x => x.ContentType.Contains("image")).SingleOrDefault();
                var(success, resultMsg) = SaveImg(topic.Id, file);
                if (!success)
                {
                    ReturnJsonMsg(false, resultMsg);
                }

                message = resultMsg;
            }
            else
            {
                message = subComment.Message;
            }

            var user = await _uf.UserRepository.GetByIdAsync(userInfo.Id);

            if (user == null)
            {
                return(ReturnJsonMsg(false, "找不到您的用户信息"));
            }

            using (var trans = _uf.BeginTransaction())
            {
                try
                {
                    if (subComment.ReplyObject == ReplyObject.User)
                    {
                        // 楼中楼
                        if (!(await AddChildReply()))
                        {
                            return(ReturnJsonMsg(false, "提交评论失败,请稍后再试"));
                        }
                    }
                    else
                    {
                        // 评论
                        if (!(await AddReply()))
                        {
                            return(ReturnJsonMsg(false, "提交评论失败,请稍后再试"));
                        }
                    }

                    trans.Commit();
                    return(Json(new MoData {
                        IsOk = true
                    }));
                }
                catch (Exception ex)
                {
                    _logger.LogError(userInfo.Id, $"提交评论:{ex.Message}-{DateTime.Now.ToStandardFormatString()}");
                    trans.Rollback();
                    return(ReturnJsonMsg(false, "系统出错啦~~~,请稍后重试"));
                }
            }

            /// 提交评论
            async Task <bool> AddReply()
            {
                var reply = new Reply
                {
                    Message   = message,
                    TopicId   = subComment.TopicId,
                    UserId    = userInfo.Id,
                    ReplyType = subComment.ReplyType,
                    TopicName = topic.TopicName,
                    UserName  = user.UserName
                };

                UpdateIntegrate(user, (int)IntegrateType.Reply);
                var replyCount = topic.ReplyCount + 1;

                topic.ReplyCount = replyCount;
                reply.ReplyIndex = replyCount + 1; // 除去楼主
                _uf.TopicRepository.Update(topic);
                await _uf.ReplyRepository.InsertAsync(reply);

                await _uf.SaveChangesAsync();

                AddIndex(topic, reply);
                return(true);
            }

            /// 提交子评论
            async Task <bool> AddChildReply()
            {
                if (subComment.ReplyIndex == null ||
                    subComment.ReplyUserId == null)
                {
                    return(false);
                }

                var replyUser = new ReplyUser
                {
                    Message     = message,
                    ReplyIndex  = subComment.ReplyIndex.Value,
                    ReplyUserId = subComment.ReplyUserId.Value,
                    TopicId     = subComment.TopicId,
                    UserId      = userInfo.Id,
                    ReplyType   = subComment.ReplyType
                };


                var reply = await _uf.ReplyRepository.GetAsync(x => x.ReplyIndex == subComment.ReplyIndex &&
                                                               x.UserId == subComment.ReplyUserId &&
                                                               x.TopicId == subComment.TopicId);

                if (reply == null)
                {
                    return(false);
                }

                await _uf.ReplyUserRepository.InsertAsync(replyUser);

                var replyCount = reply.ReplyCount + 1;

                reply.ReplyCount = replyCount;
                _uf.ReplyRepository.Update(reply);
                UpdateIntegrate(user, (int)IntegrateType.Reply);
                await _uf.SaveChangesAsync();

                return(true);
            }
        }