using Azure.Cosmos; using DocumentFormat.OpenXml.Office2010.Excel; using MathNet.Numerics.Distributions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using TEAMModelOS.SDK.DI; using TEAMModelOS.SDK.Extension; namespace TEAMModelOS.SDK.Models.Service { public static class ExamService { public static List getClasses(List cla, List stus) { List classes = new List(); try { if (cla.Count > 0) { foreach (string cl in cla) { classes.Add(cl); } } if (stus.Count > 0) { foreach (string stu in stus) { classes.Add(stu); } } return classes; } catch (Exception) { return classes; } } public static async Task deleteAsync(CosmosClient client, string id, string tId) { List correctIds = new List(); await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.cid = '{id}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"CorrectTask-{tId}") })) { using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream); if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0) { var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray(); while (accounts.MoveNext()) { JsonElement account = accounts.Current; correctIds.Add(account.GetProperty("id").GetString()); } } } if (correctIds.Count > 0) { await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(correctIds, $"CorrectTask-{tId}"); } } public static async Task classMore, double total,List<(string studentId, double scores, string classId)>students )>> getGradeScore(CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, CosmosClient client, List classIds, string periodId, string schooCode, long stime, long etime) { List<(string name, List<(string classId,double average)> classMore, double total, List<(string studentId, double scores, string classId)> stus)> grades = new(); //List<(string grade, double score)> grades = new(); try { //获取该年级所有班级ID /*List classIds = new(); await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id from c where c.year = {gradeId} and c.pk = 'Class' and c.periodId = '{periodId}' ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schooCode}") })) { using var jsonTask = await JsonDocument.ParseAsync(item.ContentStream); if (jsonTask.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0) { var accounts = jsonTask.RootElement.GetProperty("Documents").EnumerateArray(); while (accounts.MoveNext()) { JsonElement account = accounts.Current; classIds.Add(account.GetProperty("id").GetString()); } } }*/ if (classIds.Count == 0) { return grades; } else { //获取该学期内学校发生的所有评测活动(不包含个人评测活动) List exams = new(); School sc = new(); var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(schooCode.ToString(), new PartitionKey($"Base")); if (response.Status == 200) { using var json = await JsonDocument.ParseAsync(response.ContentStream); sc = json.ToObject(); } //var gradeNames = sc.period.Where(x => x.id.Equals(periodId.ToString()))?.FirstOrDefault().grades; //var index = gradeNames.IndexOf(gradeName.ToString()); await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator(queryText: $"select value(c) from c where c.startTime >= {stime} and c.startTime < {etime} and c.progress = 'finish' order by c.createTime desc", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{schooCode}") })) { exams.Add(item); } List newExams = new(); exams = exams.Where(x => x.period.id.Equals(periodId)).ToList(); foreach (ExamInfo info in exams) { bool flag = true; foreach (string id in classIds) { if (!info.classes.Contains(id)) { flag = false; } } if (flag) { newExams.Add(info); } } if (newExams.Count > 3) { newExams = newExams.Take(3).ToList(); } List examIds = newExams.Select(x => x.id).ToList(); if (examIds.Count > 0) { List classResults = new(); await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator( queryText: $"select value(c) from c where c.examId in ({string.Join(",", examIds.Select(x => $"'{x}'"))})", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{schooCode}") })) { classResults.Add(item); } (List rmembers, List groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classIds, schooCode); foreach (ExamInfo info in newExams) { double totalScore = info.papers.SelectMany(x => x.point).Sum(); var classResult = classResults.Where(x => x.examId.Equals(info.id)).ToList(); var classScores = classResult.GroupBy(x => x.info.id).Select(c => new { classId = c.Key, average = Math.Round(c.ToList().Sum(z => z.average) / info.subjects.Count / totalScore,2) }).ToList(); List<(string className, double average)> classMore = new(); foreach (var cs in classScores) { classMore.Add((cs.classId, cs.average)); } var gradeScores = Math.Round(info.average / totalScore,2); List<(string sname, double scores, string classId)> stus = new(); foreach (RMember member in rmembers) { double scroe = 0; foreach (ExamClassResult result in classResult) { if (result.studentIds.Contains(member.id)) { int index = result.studentIds.IndexOf(member.id); scroe += result.sum[index]; } } var persent = Math.Round(scroe * 1.0 / totalScore, 2); stus.Add((member.id, persent, member.classId)); } grades.Add((info.name, classMore, gradeScores, stus)); } } } } catch (Exception e) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ExamService-getGradeScore()\n{e.Message}\n{e.StackTrace}", GroupNames.成都开发測試群組); } return grades; } public static async Task saveMoreAsync(CosmosClient client, DingDing _dingDing, ExamLite trExam) { try { trExam.ttl = -1; trExam.code = "ExamLite-" + trExam.school; trExam.scope = "school"; long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); trExam.createTime = now; if (trExam.publish == 1) { trExam.progress = "pending"; } else { if (trExam.startTime > now) { trExam.progress = "pending"; } else { trExam.progress = "going"; } } if (string.IsNullOrEmpty(trExam.id)) { trExam.id = Guid.NewGuid().ToString(); await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(trExam, new PartitionKey($"{trExam.code}")); } else { await client.GetContainer("TEAMModelOS", "Common").UpsertItemAsync(trExam, new PartitionKey($"{trExam.code}")); } return trExam.id; } catch (Exception e) { await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ExamService-saveMore\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組); return ""; } } /* public static async Task getKnowledges(List knowledges,List answers ,string sub,List> kones,List point) { foreach (string k in knowledges) { double score = 0; double allScore = 0; int n = 0; int count = 0; foreach (ExamClassResult result in answers) { if (result.subjectId.Equals(sub)) { foreach (List str in kones) { if (str.Contains(k)) { var itemPersent = str.Count > 0 ? 1 / Convert.ToDouble(str.Count) : 0; allScore += point.Count > 0 ? point[n] * itemPersent : 0; if (result.studentScores.Count > 0) { score += result.studentScores.Sum(r => r.Sum()) * itemPersent; } } n++; } count += result.studentIds.Count; } } double per = count > 0 ? Math.Round(score / count, 2) : 0; } }*/ } }