using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using TEAMModelOS.SDK.Extension; using Microsoft.Azure.Cosmos; using TEAMModelOS.SDK.DI; using TEAMModelOS.SDK.Models; using TEAMModelOS.SDK.Models.Cosmos.Inner; using StackExchange.Redis; using TEAMModelOS.Models; namespace TEAMModelOS.SDK.Services { public static class ActivityStudentService { public static async Task<(int msgid, int taskStatus)> Decide(DingDing _dingDing, Option _option, JsonElement request, AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis, AzureStorageFactory _azureStorage, string userid, string school, string standard, AzureServiceBusFactory _serviceBus, Microsoft.Extensions.Configuration.IConfiguration _configuration) { Vote vote = null; DateTimeOffset now = DateTimeOffset.UtcNow; long curr = now.ToUnixTimeMilliseconds(); byte msgid = 0;//0投票失败,1投票成功,2不在时间范围内,3不在发布范围内,4投票周期内重复投票,5周期内的可投票数不足,6未设置投票项 int taskStatus = 0; //活动id if (!request.TryGetProperty("id", out JsonElement id)) { return (msgid, -1); } //活动分区 if (!request.TryGetProperty("code", out JsonElement code)) { return (msgid, taskStatus); } Dictionary option = new Dictionary(); if (request.TryGetProperty("option", out JsonElement joption)) { option = joption.ToObject>(); if (option.IsEmpty()) { msgid = 6; return (msgid, -1); } } else { return (msgid, -1); } try { //1.再次检查投票 var client = _azureCosmos.GetCosmosClient(); ///TODO 检查是否在投票范围内,包括在tmdids 及班级 但是需要处理认证金钥中的班级问题 await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql(queryText: $"select c.id,c.code ,c.school,c.creatorId,c.scope , c.progress,c.times,c.voteNum,c.startTime,c.endTime from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") })) { vote = item; break; } if (vote != null) { //判断投票时间是否在起止时间内 string optfrom = ""; ///操作来源,如果是研修的,不限制,否则现在活动结束后不能再投票或者提交问卷作答。 if (request.TryGetProperty("optfrom", out JsonElement _optFrom)) { optfrom = $"{_optFrom}"; } // if (curr >= vote.startTime && curr <= vote.endTime) bool intime=true;//默认有效期内 var endDtae = DateTimeOffset.FromUnixTimeMilliseconds(vote.endTime); if (!string.IsNullOrWhiteSpace(optfrom) && optfrom.Equals("train")) { //"optfrom":"train" 代表是研修的 if (curr >= vote.startTime) { intime = true; } else { intime = false; } endDtae = DateTimeOffset.UtcNow; } else { if (curr >= vote.startTime && curr <= vote.endTime) { intime = true; endDtae = DateTimeOffset.FromUnixTimeMilliseconds(vote.endTime); } else { intime = false; } } if (intime) { string endField = null; string Field = ""; RedisValue value; switch (vote.times) { case "once": // //如果是只能投票一次的活动则直接获取Redis的第一条 只能投一次 Field = $"{userid}-once"; HashEntry[] values = _azureRedis.GetRedisClient(8).HashGetAll($"Vote:Record:{vote.id}"); if (values != null && values.Length > 0) { value = new RedisValue(); foreach (var val in values) { if (val.Name.ToString() == Field) { value = val.Value; break; } } msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, "once"); } else { msgid = await VoteIng(vote, new RedisValue(), msgid, option, Field, curr, _azureRedis, userid, vote.times, "once"); } if (msgid == 1) { taskStatus = 1; } break; case "day": //周期内每天 Field = $"{userid}-day-{now.ToString("yyyyMMdd")}"; endField = $"{userid}-day-{endDtae.ToString("yyyyMMdd")}"; if (Field.Equals(endField)) { taskStatus = 1; } value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field); msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyyMMdd")); break; case "week": //自然周 int week = GetWeek(now); int endweek = GetWeek(endDtae); Field = $"{userid}-week-{now.ToString("yyyy")}{week}"; endField = $"{userid}-week-{endDtae.ToString("yyyy")}{endweek}"; if (Field.Equals(endField)) { taskStatus = 1; } value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field); msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, $"{now.ToString("yyyy")}{week}"); break; case "month": //月份 Field = $"{userid}-month-{now.ToString("yyyyMM")}"; endField = $"{userid}-month-{endDtae.ToString("yyyyMM")}"; if (Field.Equals(endField)) { taskStatus = 1; } value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field); msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyyMM")); break; case "year"://年份 Field = $"{userid}-year-{now.ToString("yyyy")}"; endField = $"{userid}-year-{endDtae.ToString("yyyy")}"; if (Field.Equals(endField)) { taskStatus = 1; } value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field); msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyy")); break; } } else { msgid = 2; } try { //if (!string.IsNullOrEmpty(school)) //{ // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(vote.id, new PartitionKey($"Activity-{school}-{userid}")); // activity.taskStatus = taskStatus; // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, vote.id, new PartitionKey($"Activity-{school}-{userid}")); //} //else //{ // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(vote.id, new PartitionKey($"Activity-{userid}")); // activity.taskStatus = taskStatus; // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, vote.id, new PartitionKey($"Activity-{userid}")); //} } catch (CosmosException ex) { if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { try { //StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(vote.id, new PartitionKey($"Activity-{userid}")); //activity.taskStatus = taskStatus; //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, vote.id, new PartitionKey($"Activity-{userid}")); } catch (CosmosException cex) { try { //StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync(vote.id, new PartitionKey($"Activity-{userid}")); //activity.taskStatus = taskStatus; //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(activity, vote.id, new PartitionKey($"Activity-{userid}")); if (!string.IsNullOrEmpty(standard) && !string.IsNullOrEmpty(school)) { await StatisticsService.SendServiceBus(($"{standard}", new List { $"{userid}" }, $"{school}", new List { StatisticsService.TeacherVote }, 0), _configuration, _serviceBus, client); } } catch (CosmosException cosex) { taskStatus = -1; } } } } } else { return (msgid, -1); } } catch (Exception ex) { await _dingDing.SendBotMsg($"OS,{_option.Location},common/delete-activity\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); throw new Exception(ex.StackTrace); } if (msgid == 1 && vote != null) { string blobcntr = null; if (vote.scope.Equals("school")) { blobcntr = vote.school; } else { blobcntr = vote.creatorId; } //获取投票活动的所有投票记录 var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}"); //获取投票活动的选项及投票数 var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}"); List countcds = new List(); if (counts != null && counts.Length > 0) { foreach (var count in counts) { countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score }); } } List> tasks = new List>(); List recordsBlob = new List(); foreach (var rcd in records) { var value = rcd.Value.ToString().ToObject(); recordsBlob.Add(value); } //分组每个人的 var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() }); var userdata = gp.Where(x => x.key.Equals(userid)).FirstOrDefault(); if (userdata != null) { tasks.Add(_azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(userdata.list.ToJsonString(), "vote", $"{vote.id}/urecord/{userdata.key}.json")); } //处理活动方的记录, string url = $"/vote/{vote.id}/record.json"; tasks.Add(_azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json")); } return (msgid, taskStatus); } public static async Task VoteIng(Vote vote, RedisValue value, byte msgid, Dictionary option, string Field, long curr, AzureRedisFactory _azureRedis, string userid, string times, string endpoint) { if (!value.IsNullOrEmpty) { VoteRecord record = value.ToString().ToObject(); int addCount = 0; foreach (var op in option) { addCount += op.Value; } int crdCount = 0; foreach (var op in record.opt) { crdCount += op.Value; } //处理记录投票+当前设置的投票是否小于等于周期内最大投票数 if (addCount + crdCount <= vote.voteNum) { foreach (var op in option) { if (record.opt.ContainsKey(op.Key)) { record.opt[op.Key] = record.opt[op.Key] + op.Value; } else { record.opt.Add(op.Key, op.Value); } } record.time = curr; record.userid = userid; record.times = times; record.endpoint = endpoint; //保存投票记录 bool status = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}", Field, record.ToJsonString()); //单独保存每个人方便查询的记录 bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}:{userid}", Field, record.ToJsonString()); //当前投票分组计数存入活动的Redis foreach (var opt in option) { await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Vote:Count:{vote.id}", opt.Key, opt.Value); } msgid = 1; } else { msgid = 5; } } else { if (option.Count <= vote.voteNum) { //保存投票记录 VoteRecord record = new VoteRecord { opt = option, time = curr, userid = userid, times = times, endpoint = endpoint }; bool status = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}", Field, record.ToJsonString()); //单独保存每个人方便查询的记录 bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}:{userid}", Field, record.ToJsonString()); //当前投票分组计数存入活动的Redis foreach (var opt in option) { await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Vote:Count:{vote.id}", opt.Key, opt.Value); } if (status) { msgid = 1; } } else { msgid = 5; } } return msgid; } /// /// 获取时间的在当年的第几周 /// /// /// public static int GetWeek(DateTimeOffset dt) { DateTimeOffset time = Convert.ToDateTime(dt.ToString("yyyy") + "-01-01"); TimeSpan ts = dt - time; int iii = (int)time.DayOfWeek; int day = int.Parse(ts.TotalDays.ToString("F0")); if (iii == 0) { day--; } else { day = day - (7 - iii) - 1; } int week = ((day + 7) / 7) + 1; return week; } public static async Task<(List datas, string continuationToken)> FindActivity(JsonElement request, string id, string school, AzureCosmosFactory _azureCosmos, AzureRedisFactory azureRedis) { if (string.IsNullOrWhiteSpace(id)) { if (request.TryGetProperty("userid", out JsonElement userid)) { if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String)) { id = userid.GetString(); } } } if (string.IsNullOrWhiteSpace(school)) { if (request.TryGetProperty("school", out JsonElement schooljson)) { if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String)) { school = schooljson.GetString(); } } } /// tmdid, schoolid var userType = "tmdid"; if (request.TryGetProperty("userType", out JsonElement usertype)) { if (!usertype.ValueKind.Equals(JsonValueKind.Undefined) && !usertype.ValueKind.Equals(JsonValueKind.Null) && usertype.ValueKind.Equals(JsonValueKind.String)) { userType = usertype.GetString(); } } string stimesql = ""; //开始时间,默认最近三十天 if (request.TryGetProperty("stime", out JsonElement stime)) { if (!stime.ValueKind.Equals(JsonValueKind.Undefined) && !stime.ValueKind.Equals(JsonValueKind.Null) && stime.TryGetInt64(out long data)) { stimesql = $" and c.startTime >= {data} "; } } string source = ""; //评测类型 if (request.TryGetProperty("source", out JsonElement sc)) { source = $" and c.source = '{sc}' "; } string owner = ""; //评测来源 if (request.TryGetProperty("owner", out JsonElement element)) { owner = $" and c.owner = '{element}' "; } string name = ""; //评测来源 if (request.TryGetProperty("name", out JsonElement jsonElement)) { name = $" and Contains( c.name , '{jsonElement}') = true "; } //默认当前时间, 未开始的不能查询 var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); string etimesql = $" and c.startTime <= {etimestamp} "; var typesql = ""; if (request.TryGetProperty("type", out JsonElement type)) { if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String)) { typesql = $" and c.type='{type}' "; } } string token = default; //默认不指定返回大小 int? topcout = null; if (request.TryGetProperty("count", out JsonElement jcount)) { if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data)) { topcout = data; } } //是否需要进行分页查询,默认不分页 bool iscontinuation = false; if (topcout != null && topcout.Value > 0) { iscontinuation = true; } //如果指定了返回大小 if (request.TryGetProperty("continuationToken", out JsonElement token_1)) { //指定了cancellationToken continuationSchool if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String)) { token = token_1.GetString(); } } //科目 string joinSqlSubjects = ""; string andSqlSubjects = ""; if (request.TryGetProperty("subjects", out JsonElement jsubjects)) { if (jsubjects.ValueKind is JsonValueKind.Array) { List subjects = jsubjects.ToObject>(); if (subjects.IsNotEmpty()) { joinSqlSubjects = " join A2 in c.subjects "; List sqlList = new List(); subjects.ForEach(x => { sqlList.Add($" '{x}' "); }); string sql = string.Join(" , ", sqlList); andSqlSubjects = $" and A2 in ({sql}) "; } } } List datas = new List(); var client = _azureCosmos.GetCosmosClient(); string containerId = "Student"; string PartitionKey = ""; if (!string.IsNullOrWhiteSpace(school) && userType.Equals("schoolid")) { containerId = "Student"; PartitionKey = $"Activity-{school}-{id}"; } else { containerId = "Student"; PartitionKey = $"Activity-{id}"; } string querySchool = $" SELECT value c FROM c {joinSqlSubjects} where c.pk='Activity' and c.qamode <> 2 {stimesql} {etimesql} {typesql} {andSqlSubjects} {source} {owner} {name} order by c.createTime desc"; //查询数据归属学校的 await foreach (var item in client.GetContainer(Constant.TEAMModelOS, containerId).GetItemQueryStreamIteratorSql(querySchool, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey(PartitionKey) })) { using var json = await JsonDocument.ParseAsync(item.Content); if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0) { foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray()) { datas.Add(obj.ToObject()); } } //如果需要分页则跳出 if (iscontinuation) { token = item.ContinuationToken; break; } } List results = datas.Where((x, i) => datas.FindIndex(z => z.id == x.id && z.code == x.code) == i).ToList(); return (results, token); } public static async Task<(int msgid, int taskStatus)> Answer(DingDing _dingDing, Option _option, JsonElement request, AzureCosmosFactory _azureCosmos, AzureRedisFactory azureRedis, string userid, string school, AzureStorageFactory _azureStorage, string standard, AzureServiceBusFactory _serviceBus, Microsoft.Extensions.Configuration.IConfiguration _configuration) { DateTimeOffset now = DateTimeOffset.UtcNow; long curr = now.ToUnixTimeMilliseconds(); int msgid = 0;// int taskStatus = 0; //活动id if (!request.TryGetProperty("id", out JsonElement id)) { return (msgid, -1); } //活动分区 if (!request.TryGetProperty("code", out JsonElement code)) { return (msgid, -1); } try { //1.再次检查问卷 var client = _azureCosmos.GetCosmosClient(); Survey survey = null; ///TODO 检查是否在问卷范围内,包括在tmdids 及班级 但是需要处理认证金钥中的班级问题 await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql(queryText: $"select c.id,c.owner,c.scope, c.code ,c.creatorId,c.answers ,c.school , c.progress,c.times,c.startTime,c.endTime from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") })) { survey = item; break; } if (survey != null) { string optfrom = ""; ///操作来源,如果是研修的,不限制,否则现在活动结束后不能再投票或者提交问卷作答。 if (request.TryGetProperty("optfrom", out JsonElement _optFrom)) { optfrom = $"{_optFrom}"; } // if (curr >= vote.startTime && curr <= vote.endTime) bool intime = true;//默认有效期内 var endDtae = DateTimeOffset.FromUnixTimeMilliseconds(survey.endTime); if (!string.IsNullOrWhiteSpace(optfrom) && optfrom.Equals("train")) { //"optfrom":"train" 代表是研修的 if (curr >= survey.startTime) { intime = true; } else { intime = false; } endDtae = DateTimeOffset.UtcNow; } else { if (curr >= survey.startTime && curr <= survey.endTime) { intime = true; endDtae = DateTimeOffset.FromUnixTimeMilliseconds(survey.endTime); } else { intime = false; } } //判断投票时间是否在起止时间内 // if (curr >= survey.startTime && curr <= survey.endTime) if (intime) { if (request.TryGetProperty("record", out JsonElement _record)) { var recs = _record.ToObject>>(); if (recs.IsNotEmpty() && recs.Count == survey.answers.Count) { //处理问卷调查表的每一题选项数 // List> tasks = new List>(); for (int index = 0; index < recs.Count; index++) { Dictionary dict = new Dictionary(); if (recs[index].IsNotEmpty()) { recs[index].ForEach(x => { if (!string.IsNullOrWhiteSpace(x)) { if (survey.answers[index].Contains(x)) { if (dict.ContainsKey(x)) { dict[x] = dict[x] + 1; } else { dict[x] = 1; } } else { if (dict.ContainsKey("other")) { dict["other"] = dict["other"] + 1; } else { dict["other"] = 1; } //这里暂不处理, 结算再处理other // tasks.Add(_azureStorage.UploadFileByContainer(survey.owner,new { other=x, userid, time =curr }.ToJsonString(), "survey", $"{survey.id}/other/{index}/{userid}.json", false)); } } }); } var value = azureRedis.GetRedisClient(8).HashGet($"Survey:Record:{survey.id}", index); if (value != default && !value.IsNullOrEmpty) { Dictionary dt = value.ToString().ToObject>(); foreach (var kp in dict) { //不建议放在reids if (dt.ContainsKey(kp.Key)) { dt[kp.Key] = dt[kp.Key] + kp.Value; } else { dt.Add(kp.Key, kp.Value); } } await azureRedis.GetRedisClient(8).HashSetAsync($"Survey:Record:{survey.id}", index, dt.ToJsonString()); } else { await azureRedis.GetRedisClient(8).HashSetAsync($"Survey:Record:{survey.id}", index, dict.ToJsonString()); } } //处理other ,这里暂不处理, 结算再处理other //await Task.WhenAll(tasks); //保存当前提交人的记录 string blobcntr = null; if (survey.scope.Equals("school")) { blobcntr = survey.school; } else { blobcntr = survey.creatorId; } await _azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(new SurveyRecord { ans = recs, userid = userid, time = curr }.ToJsonString(), "survey", $"{survey.id}/urecord/{userid}.json"); ///bgn 20210805 huanghb 实时结算 await azureRedis.GetRedisClient(8).SetAddAsync($"Survey:Submit:{survey.id}", userid); var submits = await azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}"); List userids = new List(); foreach (var submit in submits) { var value = submit.ToString(); userids.Add(value); } List questionRecords = new List(); //结算每道题的答题情况 var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr); List> tasks = new List>(); List items = await ContainerClient.List($"survey/{survey.id}/urecord"); List surveyRecords = new List(); foreach (string item in items) { var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync(); var json = await JsonDocument.ParseAsync(Download.Value.Content); var Record = json.RootElement.ToObject(); surveyRecords.Add(Record); } for (int index = 0; index < survey.answers.Count; index++) { string url = $"{survey.id}/qrecord/{index}.json"; QuestionRecord question = new QuestionRecord() { index = index }; foreach (SurveyRecord record in surveyRecords) { if (record.ans.Count == survey.answers.Count) { foreach (var an in record.ans[index]) { // if (question.opt.ContainsKey(an)) { if (question.opt[an] != null) { question.opt[an].Add(record.userid); } else { question.opt[an] = new HashSet() { record.userid }; } } else { if (survey.answers[index].Contains(an)) { //如果是客观题code question.opt.Add(an, new HashSet { record.userid }); } else { //如果不是客观code question.other[record.userid] = an; } } } } } questionRecords.Add(question); tasks.Add(_azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(question.ToJsonString(), "survey", url)); } var records = await azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}"); List recds = new List(); List srecords = new List(); int len = survey.answers.Count; for (int i = 0; i < len; i++) { var anses= surveyRecords.Select(z => z.ans).ToList(); srecord srecord= new srecord() { index=$"{i}"}; Dictionary dict = new Dictionary(); srecord.ans = dict; foreach (var asd in anses) { asd[i].ForEach(z => { if (!string.IsNullOrWhiteSpace(z)) { if (survey.answers[i].Contains(z)) { if (dict.ContainsKey(z)) { dict[z] = dict[z] + 1; } else { dict.Add(z, 1); } } else { if (dict.ContainsKey("other")) { dict["other"] = dict["other"] + 1; } else { dict.Add("other", 1); } } } }); } srecords.Add(srecord); } //foreach (var rcd in records) //{ // var value = rcd.Value.ToString().ToObject(); // recds.Add(new { index = rcd.Name.ToString(), ans = value }); //} await Task.WhenAll(tasks); var cods = new { records = srecords, userids, question = questionRecords, urecord = surveyRecords }; //问卷整体情况 await _azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(cods.ToJsonString(), "survey", $"{survey.id}/record.json"); ///end 20210805 huanghb 实时结算 taskStatus = 1; msgid = 1; } else { //提交的作答不符合问卷的答案长度。 msgid = 3; } } } else { msgid = 2; } try { //if (!string.IsNullOrEmpty(school)) //{ // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(survey.id, new PartitionKey($"Activity-{school}-{userid}")); // activity.taskStatus = taskStatus; // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, survey.id, new PartitionKey($"Activity-{school}-{userid}")); //} //else //{ // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(survey.id, new PartitionKey($"Activity-{userid}")); // activity.taskStatus = taskStatus; // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, survey.id, new PartitionKey($"Activity-{userid}")); //} } catch (CosmosException ex) { if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { try { // StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(survey.id, new PartitionKey($"Activity-{userid}")); // activity.taskStatus = taskStatus; // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(activity, survey.id, new PartitionKey($"Activity-{userid}")); } catch (CosmosException cex) { if (cex.StatusCode == System.Net.HttpStatusCode.NotFound) { try { //StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync(survey.id, new PartitionKey($"Activity-{userid}")); //activity.taskStatus = taskStatus; //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync(activity, survey.id, new PartitionKey($"Activity-{userid}")); if (!string.IsNullOrEmpty(standard) && !string.IsNullOrEmpty(school)) { await StatisticsService.SendServiceBus(($"{standard}", new List { $"{userid}" }, $"{school}", new List { StatisticsService.TeacherSurvey }, 0), _configuration, _serviceBus, client); } } catch (CosmosException cosex) { if (cosex.StatusCode == System.Net.HttpStatusCode.NotFound) { taskStatus = -1; } } } } } } } else { return (msgid, -1); } } catch (Exception e) { throw new Exception(e.StackTrace); } return (msgid, taskStatus); } public class RdsRecord { public Dictionary srecord { get; set; } = new Dictionary(); public Dictionary urecord { get; set; } = new Dictionary(); } public class srecord { public string index { get; set;} public Dictionary ans { get; set; } = new Dictionary(); } } }