123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676 |
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Azure.Amqp.Framing;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using NUnit.Framework;
- using OfficeOpenXml;
- using OpenXmlPowerTools;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.School;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("school/exam")]
- [ApiController]
- public class ImportExamController: ControllerBase
- {
- public IWebHostEnvironment _environment { get; set; }
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- public IConfiguration _configuration { get; set; }
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly HttpTrigger _httpTrigger;
- public ImportExamController(HttpTrigger httpTrigger, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration, IWebHostEnvironment env)
- {
- _environment = env;
- _coreAPIHttpService = coreAPIHttpService;
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _httpTrigger = httpTrigger;
- }
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("read-excel-virtue")]
- //[Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,business")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<IActionResult> ReadExcelVirtue([FromForm] IFormFile file, [FromForm] string periodId) {
- List<KeyValuePair<string, List<string>>> error = new List<KeyValuePair<string, List<string>>>();
- List<KeyValuePair<string, List<string>>> warn = new List<KeyValuePair<string, List<string>>>();
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
- List<VirtueImport> virtueImports = new List<VirtueImport> { };
- using (ExcelPackage package = new ExcelPackage(file.OpenReadStream())) {
- ExcelWorksheets sheet = package.Workbook.Worksheets;
- //德育数据导入
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new Azure.Cosmos.PartitionKey("Base"));
- Period period = schoolBase.period.Find(x => x.id.Equals(periodId));
- var daily_sheets = sheet.Where(z => !z.Name.Equals("栏位说明"));
- HashSet<IdNameCode> rightStudents = new HashSet<IdNameCode>();
- List<Class> classes = new List<Class>();
- foreach (var daily_sheet in daily_sheets)
- {
- if (DateTimeOffset.TryParse(daily_sheet.Name, out DateTimeOffset sheetNameTime))
- {
- var data = GetSubSheetData(daily_sheet, error);
- Dictionary<string, object> dailyData = new Dictionary<string, object> { { "subject", "德育" }, { "students", data.students } };
- ImportExamSubject importExamDaily = dailyData.ToJsonString().ToObject<ImportExamSubject>();
- var subject = period.subjects.Find(z => z.name.Equals(importExamDaily.subject));
- if (subject != null)
- {
- List<ResultImportStudent> examImportStudents = new List<ResultImportStudent>();
- //学生
- await ExamImportStudent(importExamDaily.students, rightStudents, school, period, examImportStudents, error, warn, classes, daily_sheet.Name);
- VirtueImport virtueImport = new VirtueImport {
- time = sheetNameTime.ToUnixTimeMilliseconds(),
- id = $"{}",
- students = examImportStudents
- };
- virtueImport.students.AddRange(examImportStudents);
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("subject_invalid", new List<string> { importExamDaily.subject }));// 科目不存在
- }
- }
- else {
-
- }
- }
- }
- return Ok(new { virtueImports, error,warn});
- }
- // [AuthToken(Roles = "teacher,admin")]
- [HttpPost("read-excel-exam")]
- //[Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,business")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<IActionResult> ReadExcel([FromForm] IFormFile file,[FromForm] string periodId) {
- List<KeyValuePair<string, List<string>>> error = new List<KeyValuePair<string, List<string>>>();
- List<KeyValuePair<string, List<string>>> warn = new List<KeyValuePair<string, List<string>>>();
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
- using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
- {
- ExcelWorksheets sheet = package.Workbook.Worksheets;
- List<string> baseTitle = new List<string>();
- List<string> baseData = new List<string>();
- List<string> itemTitle = new List<string>();
- List<List<string>> itemDatas = new List<List<string>>();
- Dictionary<string, object> baseInfo = new Dictionary<string, object>();
- List<Dictionary<string, object>> itemInfo = new List<Dictionary<string, object>>();
- HashSet<string> subjects = new HashSet<string>();
- //科目标题的栏位序列
- int subjectTitelIndex = -1;
- //读取Exam_
- var exam_sheet = sheet.Where(z => z.Name.StartsWith("Exam_")).FirstOrDefault();
- if (exam_sheet!=null )
- {
-
- var rows = exam_sheet.Dimension.Rows;
- var columns = exam_sheet.Dimension.Columns;
- for (int r = 1; r <= rows; r++) {
- List<string> itemData = null;
- if (r >= 4) {
- itemData= new List<string>();
- }
- for (int c = 1; c <= columns; c++) {
- var value = exam_sheet.GetValue(r, c);
- if (r == 1)
- {
- if (!string.IsNullOrWhiteSpace($"{value}"))
- {
- baseTitle.Add($"{value}");
- }
- else
- {
- break;
- }
- }
- else if (r == 2)
- {
- if (c > baseTitle.Count)
- {
- break;
- }
- else
- {
- baseData.Add($"{value}");
- }
- }
- else if (r == 3)
- {
- if (!string.IsNullOrWhiteSpace($"{value}"))
- {
- if ($"{value}".Equals("subject")) {
- subjectTitelIndex= c;
- }
- itemTitle.Add($"{value}");
- }
- else
- {
- break;
- }
- }
- else {
- if (c > itemTitle.Count)
- {
- break;
- }
- else
- {
- itemData.Add($"{value}");
- }
- }
- }
- if (itemData != null) {
- itemDatas.Add(itemData);
- }
- }
-
- for (int i = 0; i < baseTitle.Count; i++)
- {
- baseInfo.Add(baseTitle[i], baseData[i]);
- }
- for (int i = 0; i < itemDatas.Count; i++)
- {
- Dictionary<string, object> item = new Dictionary<string, object>();
- for (int j = 0; j < itemTitle.Count; j++)
- {
- if (itemTitle[j].Equals("index"))
- {
- if (int.TryParse(itemDatas[i][j], out int index))
- {
- item.Add(itemTitle[j], index);
- }
- else {
- error.Add(new KeyValuePair<string, List<string>>("index_invalid",new List<string> { itemDatas[i][j] } ));// 题目序列只能是正整数
- }
-
- }
- else if (itemTitle[j].Equals("score") )
- {
- if (double.TryParse(itemDatas[i][j], out double score))
- {
- item.Add(itemTitle[j], score);
- }
- else if (string.IsNullOrWhiteSpace(itemDatas[i][j])) {
- item.Add(itemTitle[j], 0);
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("score_invalid", new List<string> { itemDatas[i][j] }));// 配分只能是数字
- }
- }
- else {
- item.Add(itemTitle[j], itemDatas[i][j]);
- }
-
- }
- itemInfo.Add(item);
- subjects.Add(itemDatas[i][subjectTitelIndex-1]);
- }
- }
- List<Dictionary<string, object>> subjectDatas = new List<Dictionary<string, object>>();
- if (subjects.Count > 0) {
- foreach (var subject in subjects) {
-
- var subject_sheet = sheet.Where(z => z.Name.StartsWith($"Sub_{subject}")).FirstOrDefault();
- var data = GetSubSheetData(subject_sheet,error);
- var items = itemInfo.FindAll(x => x["subject"].Equals(subject));
-
- Dictionary<string, object> subjectData = new Dictionary<string, object> { { "subject", subject } ,{ "items",items },{ "students", data.students } };
- subjectDatas.Add(subjectData);
- }
- }
-
- baseInfo.Add("periodId", periodId);
- baseInfo.Add("school", school);
- baseInfo.Add("subjects", subjectDatas);
- var importExam =baseInfo.ToJsonString().ToObject<ImportExam>();
- var validData = importExam.Valid();
- ExamImport examImport = null;
- if (validData.isVaild)
- {
- string sql = $"select value c from c where c.name ='{importExam.name}'";
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<ExamImport>(sql, $"ExamImport-{importExam.school}", pageSize: 1);
-
- if (string.IsNullOrEmpty(result.continuationToken))
- {
- warn.Add(new KeyValuePair<string, List<string>>("name_duplicate", new List<string> { importExam.name }));//评测名称重复
- }
- if (result.list.IsNotEmpty())
- {
- examImport = result.list[0];
- warn.Add(new KeyValuePair<string, List<string>>("name_update", new List<string> { importExam.name }));//同名评测数据更新
- }
- if (examImport == null)
- {
- examImport = new ExamImport { name = importExam.name, type = importExam.type, school = importExam.school };
- if (DateTimeOffset.TryParse(importExam.time, out DateTimeOffset dateTime))
- {
- examImport.time = dateTime.ToUnixTimeMilliseconds();
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("time_format", new List<string> { importExam.time }));// 时间格式错误
- }
- }
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(importExam.school, new Azure.Cosmos.PartitionKey("Base"));
- Period period = schoolBase.period.Find(x => x.id.Equals(importExam.periodId));
- if (period != null)
- {
- //用于处理多学科,不需要重复查询学习基础信息
- //id 学生id code 行政班id name 学生姓名
- HashSet<IdNameCode> rightStudents = new HashSet<IdNameCode>();
- List<Class> classes = new List<Class>();
- foreach (var item in importExam.subjects)
- {
- var subject = period.subjects.Find(z => z.name.Equals(item.subject));
- if (subject != null)
- {
- List<ResultImportStudent> examImportStudents = new List<ResultImportStudent>();
- //学生
- await ExamImportStudent(item.students, rightStudents, school, period, examImportStudents, error, warn, classes, item.subject);
- examImport.subjects.Add(new ExamImportSubject { id = subject.id, name = subject.name, students = examImportStudents, }) ;
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("subject_invalid", new List<string> { item.subject }));// 科目不存在
- }
- }
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("period_invalid",new List<string> { importExam.periodId }));// 学段不存在
- }
- }
- else {
- validData.errors.SelectMany(z => z.Value).ToList().ForEach(x => {
- error.Add(new KeyValuePair<string, List<string>>(x, new List<string> { }));
- });
- }
- List<KeyValuePair<string, HashSet<string>>> errorData = new List<KeyValuePair<string, HashSet<string>>>();
- error.ForEach(x => {
- var value = errorData.Find(z => z.Key.Equals(x.Key));
- if (!string.IsNullOrWhiteSpace(value.Key))
- {
- x.Value.ForEach(z => { value.Value.Add(z); });
- }
- else {
- errorData.Add(new KeyValuePair<string, HashSet<string>>(x.Key,x.Value.ToHashSet()));
- }
- });
- return Ok(new { code = 400, error = errorData, examImport });
- }
- }
- private async Task ExamImportStudent(List<ImportResultStudent> importExamStudents, HashSet<IdNameCode> rightStudents,string school,
- Period period, List<ResultImportStudent> examImportStudents, List<KeyValuePair<string, List<string>>> error,
- List<KeyValuePair<string, List<string>>> warn, List<Class> classes, string sheetName)
- {
- // 学号确定的学生
- var hasIdStudents = importExamStudents.Where(z => !string.IsNullOrWhiteSpace(z.id));
- var needSearch = hasIdStudents.ExceptBy(rightStudents.Select(x => x.id), hasId => hasId.id).ToList();
- List<ImportResultStudent> notExistIds = new List<ImportResultStudent>();
- //通过id在数据库和rightStudents 都找不到的学生
- List<ImportResultStudent> evenNotExistIds = new List<ImportResultStudent>();
- if (needSearch.Any())
- {
- ///在rightStudents找不到的学生需要查询数据库。
- string stuidsql = $"select c.id,c.classId as code , c.name from c where c.id in ({string.Join(",", needSearch.Select(x => $"'{x.id}'"))}) and c.periodId='{period.id}' ";
- var sturesult = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<IdNameCode>(stuidsql, $"Base-{school}");
- if (sturesult.list.IsNotEmpty())
- {
- sturesult.list.ForEach(x => {
- var exist = rightStudents.Where(y => y.id.Equals(x.id));
- if (!exist.Any())
- {
- rightStudents.Add(x);
- }
- });
- //needSearch与 sturesult.list(数据库)查找的对比,仍然没有找到的学生。
- var notInDb = needSearch.ExceptBy(sturesult.list.Select(x => x.id), y => y.id);
- if (notInDb.Any())
- {
- evenNotExistIds.AddRange(notInDb);
- }
- }
- else
- {
- evenNotExistIds.AddRange(needSearch);
- }
- }
- foreach (var item in hasIdStudents)
- {
- var existStudent = rightStudents.Where(n => n.id.Equals(item.id));
- if (existStudent .Any())
- {
- long time = 0;
- if (DateTimeOffset.TryParse(item.time, out DateTimeOffset dateTime))
- {
- time = dateTime.ToUnixTimeMilliseconds();
- }
- examImportStudents.Add(new ResultImportStudent
- {
- id = item.id,
- name = existStudent.First().name,
- classId = existStudent.First().code,
- score = item.score,
- scores = item.scores,
- time = time,
- items = item.items,
- });
- }
- }
- //id信息在数据库找不到的 且班级和姓名不全,
- var hasNameClassid = evenNotExistIds.Where(x => !string.IsNullOrWhiteSpace(x.name) && !string.IsNullOrWhiteSpace(x.classId));
- var notexistStudent = evenNotExistIds.Except(hasNameClassid);
- if (notexistStudent.Any())
- {
- error.Add(new KeyValuePair<string, List<string>>("student_notexist", notexistStudent.Select(x => $"id:{x.id}_name:{x.name}_classId:{x.classId}").ToList()));//没有班级和姓名不全,且id信息在数据库找不到的
- }
- //没有学号 ,且姓名和班级信息不全的
- var studentInvalid = importExamStudents.Where(z => string.IsNullOrWhiteSpace(z.id) && (string.IsNullOrWhiteSpace(z.name) || string.IsNullOrWhiteSpace(z.classId)));
- if (studentInvalid.Any())
- {
- error.Add(new KeyValuePair<string, List<string>>("student_invalid", studentInvalid.Select(x => $"id:{x.id}_name:{x.name}_classId:{x.classId}").ToList()));// 学生信息不全
- }
- //没有id ,但是存在姓名和班级信息
- var classesStu = importExamStudents.Where(z => !string.IsNullOrWhiteSpace(z.classId) && !string.IsNullOrWhiteSpace(z.name) && string.IsNullOrWhiteSpace(z.id)).ToHashSet();
- if (hasNameClassid.Any())
- {
- hasNameClassid.ToList().ForEach(x => classesStu.Add(x));
- }
- var group = classesStu.GroupBy(x => x.classId);
- //不能被拆分的以班级名称查找。
- foreach (var classGroupStudents in group)
- {
- Class clzz = null;
- bool isClassName = false;
- string className = string.Empty;
- var cls = classGroupStudents.Key.Split("-");
- var classStudents = classGroupStudents.ToList();
- var duplicateStudents = new List<ImportResultStudent>();
- classStudents.GroupBy(z => z.name).Select(z => new { key = z.Key, list = z.ToList() }).ToList().ForEach(y => {
- if (y.list.Count > 1)
- {
- duplicateStudents.AddRange(y.list);
- error.Add(new KeyValuePair<string, List<string>>("stuname_duplicate", y.list.Select(z => $"{sheetName}-{z.name}").ToList()));
- }
- });
- if (duplicateStudents.IsNotEmpty())
- {
- duplicateStudents.ForEach(z => { classStudents.Remove(z); });
- }
- if (cls.Length == 2 && int.TryParse(cls[0], out int year) && year > 2000 && int.TryParse(cls[1], out int no) && no > 0)
- {
- var existInTemp = classes.FindAll(z => z.year == year && z.no.Equals(cls[1]));
- if (existInTemp.Any())
- {
- clzz = existInTemp.First();
- }
- else
- {
- string sqlClazz = $"select value c from c where c.year={year} and c.no ='{cls[1]}' and c.periodId='{period.id}' ";
- var classresult = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Class>(sqlClazz, $"Class-{school}", pageSize: 1);
- if (classresult.list.IsNotEmpty())
- {
- clzz = classresult.list[0];
- classes.Add(clzz);
- }
- else
- {
- className = classGroupStudents.Key;
- isClassName = true;
- }
- }
- }
- else
- {
- className = classGroupStudents.Key;
- isClassName = true;
- }
- if (isClassName)
- {
- var existInTemp = classes.FindAll(z => z.name.Equals(className));
- if (existInTemp.Any())
- {
- clzz = existInTemp.First();
- }
- else
- {
- string sqlClazz = $"select value c from c where c.name ='{className}' and c.periodId='{period.id}' ";
- var classresult = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Class>(sqlClazz, $"Class-{school}", pageSize: 1);
- if (classresult.list.IsNotEmpty())
- {
- clzz = classresult.list[0];
- classes.Add(clzz);
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("class_invalid", new List<string> { $"{sheetName}-{className}" }));// 班级错误
- }
- }
- }
- if (clzz != null)
- {
- string stuClassIdsql = $"select c.id,c.classId as code , c.name from c where c.name in ({string.Join(",", classStudents.Select(x => $"'{x.name}'"))}) and c.classId ='{clzz.id}' and c.periodId='{period.id}' ";
- var sturesult = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<IdNameCode>(stuClassIdsql, $"Base-{school}");
- //检查重名
- if (sturesult.list.IsNotEmpty())
- {
- var groupNames = sturesult.list.GroupBy(x => x.name).Select(x => new { key = x.Key, list = x.ToList() }).Where(y => y.list.Count > 1);
- if (groupNames.Any())
- {
- warn.Add(new KeyValuePair<string, List<string>>("stuname_duplicate", groupNames.Select(x => $"{sheetName}-{x.key}").ToList()));//学生姓名重复
- }
- foreach (var stu in classesStu)
- {
- var student = sturesult.list.FindAll(x => x.name.Equals(stu.name));
- if (student.Any())
- {
- long time = 0;
- if (DateTimeOffset.TryParse(stu.time, out DateTimeOffset dateTime))
- {
- time = dateTime.ToUnixTimeMilliseconds();
- }
- examImportStudents.Add(new ResultImportStudent
- {
- id = student[0].id,
- name = student[0].name,
- classId = student[0].code,
- score = stu.score,
- scores = stu.scores,
- time = time,
- items = stu.items
- });
- }
- }
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("student_invalid", classGroupStudents.ToList().Select(x => $"{sheetName}-{x.name}").ToList()));
- }
- }
- }
- }
- private (List<Dictionary<string, object>> students, List<KeyValuePair<string, List<string>>> error) GetSubSheetData(ExcelWorksheet subject_sheet, List<KeyValuePair<string, List<string>>> error) {
- List<Dictionary<string, object>> students = new List<Dictionary<string, object>>();
- List<string> titles = new List<string>();
- List<List<string>> datas = new List<List<string>>();
- if (subject_sheet != null)
- {
- var rows = subject_sheet.Dimension.Rows;
- var columns = subject_sheet.Dimension.Columns;
- for (int r = 1; r <= rows; r++)
- {
- List<string> data = new List<string>();
- for (int c = 1; c <= columns; c++)
- {
- var value = subject_sheet.GetValue(r, c);
- if (r == 1)
- {
- if (!string.IsNullOrWhiteSpace($"{value}"))
- {
- titles.Add($"{value}");
- }
- else
- {
- break;
- }
- }
- else
- {
- if (c > titles.Count)
- {
- break;
- }
- else
- {
- data.Add($"{value}");
- }
- }
- }
- if (data.Any())
- {
- datas.Add(data);
- }
- }
- }
- for (int i = 0; i < datas.Count; i++)
- {
- Dictionary<string, object> item = new Dictionary<string, object>();
- List<KeyValuePair<int, int>> _index_order = new List<KeyValuePair<int, int>>();
- List<ItemVlaue> items = new List<ItemVlaue>();
- for (int j = 0; j < titles.Count; j++)
- {
- if (int.TryParse(titles[j], out int index))
- {
- _index_order.Add(new KeyValuePair<int, int>(index, j));
- }
- else if (titles[j].StartsWith("item_"))
- {
- double score = 0;
- if (double.TryParse(datas[i][j], out score))
- {
- items.Add(new ItemVlaue() { code = titles[j].Replace("item_", ""), value = score });
- }
- else if (string.IsNullOrWhiteSpace(datas[i][j]))
- {
- items.Add(new ItemVlaue() { code = titles[j].Replace("item_", ""), value = score });
- }
- else {
- error.Add(new KeyValuePair<string, List<string>>("score_invalid",new List<string> { datas[i][j] }));// 得分只能是数字
- }
-
- }
- else
- {
- if (titles[j].Equals("score") )
- {
- if (double.TryParse(datas[i][j], out double score))
- {
- item.Add(titles[j], score);
- }
- else if (string.IsNullOrWhiteSpace(datas[i][j]))
- {
- item.Add(titles[j], 0);
- }
- else {
- error.Add(new KeyValuePair<string, List<string>>("score_invalid", new List<string> { datas[i][j] }));// 得分只能是数字
- }
- }
- else {
- item.Add(titles[j], datas[i][j]);
- }
-
- }
- }
- var orders = _index_order.OrderBy(x => x.Key).ToList();
- List<double> scores = new List<double>();
- for (int j = 0; j < orders.Count; j++)
- {
- double score = 0;
- if (double.TryParse($"{datas[i][orders[j].Value]}", out score))
- {
- scores.Add(score);
- }
- else if (string.IsNullOrWhiteSpace($"{datas[i][orders[j].Value]}"))
- {
- scores.Add(score);
- }
- else
- {
- error.Add(new KeyValuePair<string, List<string>>("score_invalid", new List<string> { datas[i][orders[j].Value] }));// 得分只能是数字
- }
-
- }
- if (scores.IsNotEmpty())
- {
- item.Add("scores", scores);
- }
- if (items.IsNotEmpty())
- {
- item.Add("items", items);
- }
- students.Add(item);
- }
-
- return (students, error);
- }
-
- }
- }
|