/// <summary> /// 清算用户数据 /// </summary> /// <param name="questionModel"></param> /// <param name="activityId"></param> private void UserAnswerClear(QuestionModel questionModel, long activityId) { var questionId = questionModel.PKID; //获取题目的选项和子项 var options = DalActivity.SearchQuestionOption(questionId)?.ToList(); if (options?.Count == 0) { return; } //正确选项 var rightOption = options.FirstOrDefault(p => p.QuestionParentID == 0 && p.IsRightValue == 1); if (rightOption == null) { return; } var i = 1; using (var db = DbHelper.CreateDbHelper()) using (var configClient = new ConfigClient()) using (var userClient = new UserClient()) using (var activityClient = new ActivityClient()) using (var templatePushClient = new TemplatePushClient()) using (var cacheClient = CacheHelper.CreateCacheClient("ActivityUserQuestionAnswerClear")) { //推送的开关设置 var pushResult = configClient.GetOrSetRuntimeSwitch("activityquestionclearpush")?.Result; //推送开关 var pushFlag = pushResult?.Value ?? false; //推送的模板ID var pushIdstr = pushResult?.Description; var pushId = 0; int.TryParse(pushIdstr, out pushId); while (true) { var ts = new Stopwatch(); ts.Start(); var clearCount = 1000; //获取用户答题尚未清算数据 var userAnswerNotClearDatas = DalActivity.SearchUserAnswerNotClear(questionId, clearCount)?.ToList(); if (userAnswerNotClearDatas?.Count == 0) { break; } //循环用户数据 userAnswerNotClearDatas.AsParallel().ForAll(userData => { try { //用户选择的选项 var userOption = options.FirstOrDefault(p => p.PKID == userData.AnswerOptionID); if (userOption != null) { Logger.Info($"开始清算用户数据:{userData.UserID} {userData.AnswerOptionID}"); //找用户选项的根选项 var rootOption = GetRootOption(userOption, options); //判断是否正确选项 //正确则赠送兑换券 否则不赠送兑换券 if (rootOption.PKID == rightOption.PKID) { //更新回答结果 var resultAnswer = activityClient.ModifyQuestionUserAnswerResult( new ModifyQuestionUserAnswerResultRequest() { AnswerResultStatus = 1, ResultId = userData.PKID, WinCouponCount = userData.WinCouponCount }); if (resultAnswer?.Result?.IsOk == true) { //更新兑换券 和 日志 var result = activityClient.ModifyActivityCoupon(userData.UserID, activityId, userOption.WinCouponCount ?? 0 , "答题清算服务" , userData.AnswerDate); if (!result.Success && result.Result <= 0) { Logger.Warn($"请求 ModifyActivityCoupon 失败 {result.ErrorMessage}"); //回滚 DalActivity.UpdateUserAnswerResult(db, userData.PKID, userData.WinCouponCount, 0); return; } } } else { //更新用户答题结果 var resultAnswer = activityClient.ModifyQuestionUserAnswerResult( new ModifyQuestionUserAnswerResultRequest() { AnswerResultStatus = 2, ResultId = userData.PKID, WinCouponCount = 0 }); } Logger.Info($"用户 {userData.UserID} "); //推送消息 判断推送开关是否开启 if (pushFlag && pushId != 0) { PushMessage(pushId, cacheClient, userClient, templatePushClient, userData.UserID, userData.CreateDatetime); } } } catch (Exception e) { Logger.Error($" {nameof(ActivityUserQuestionAnswerClearJob)} 失败 ", e); } }); ts.Stop(); Logger.Info($" {nameof(UserAnswerClear)} 清算 {clearCount} 条数据 执行时间 {ts.Elapsed.TotalSeconds} 秒 "); i++; } } }