using Azure;
using Azure.Cosmos;
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TEAMModelOS.Models;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.SDK.Models;
using Member = TEAMModelOS.SDK.Models.Member;
namespace TEAMModelOS.SDK
{
public class StudentService
{
public class StudentActivity
{
public string id { get; set; }
public string code { get; set; }
public string userType { get; set; }
public string stuId { get; set; }
///
/// 源数据的发布层级 类型 school teacher
///
public string owner { get; set; }
public string pk { get; set; }
//评测模式
public string source { get; set; }
public string name { get; set; }
public long startTime { get; set; }
public long endTime { get; set; }
public string scope { get; set; }
public string school { get; set; }
public string creatorId { get; set; }
public string scode { get; set; }
public string type { get; set; }
public Custom examType { get; set; } = new Custom();
public List subjects { get; set; } = new List();
//返回科目内容
public List subs { get; set; } = new List();
//返回字段
public List classIds { get; set; } = new List();
public List classes { get; set; } = new List();
public List stuLists { get; set; } = new List();
public List tchLists { get; set; } = new List();
public List targets { get; set; } = new List();
public long createTime { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public Dictionary ext { get; set; } = new Dictionary();
/// 评分状态,0,未评分, 1已评分
public int sStatus { get; set; } = 0;
//评测 纸本1或者书面问答0
public int qamode { get; set; } = 0;
//标记作业活动是否比交
public bool mustSubmit { get; set; } = false;
//标记问卷是否重复提交 0 否 1 是
public int isSub { get; set; } = 0;
///
/// 任务完成状态,-1 未参与,0,未完成, 1已完成
///
public int taskStatus { get; set; } = -1;
public string recordUrl { get; set; }
}
///
///
///
///
///
///
///
///
/// Exam ,Vote,Homework,Survey
///
///
public static async Task> FindActivity(JsonElement request, string userId, string userScope, List groupListIds, List subjects, string school, List types, AzureCosmosFactory _azureCosmos)
{
string filed = "c.id ,c.code,c.owner,c.pk as type,c.examType,c.targets,c.qamode,c.name,c.school,c.startTime,c.endTime,c.classes,c.stuLists,c.tchLists,c.createTime,c.creatorId,c.isSub,c.mustSubmit,c.sStatus,c.scope,c.source,c.subjects";
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();
}
}
}
long stime = DateTimeOffset.UtcNow.AddDays(-30).ToUnixTimeMilliseconds(), etime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (request.TryGetProperty("stime", out JsonElement _stime))
{
if (!_stime.ValueKind.Equals(JsonValueKind.Undefined) && !_stime.ValueKind.Equals(JsonValueKind.Null) && _stime.TryGetInt64(out long data))
{
stime = data;
}
}
if (request.TryGetProperty("etime", out JsonElement _etime))
{
if (!_etime.ValueKind.Equals(JsonValueKind.Undefined) && !_etime.ValueKind.Equals(JsonValueKind.Null) && _etime.TryGetInt64(out long data))
{
etime = data;
}
}
string groupListSQL = string.Empty;
if (groupListIds.IsNotEmpty())
{
List arrayStr = new List();
groupListIds.ForEach(z =>
{
arrayStr.Add($"array_contains(c.classes,'{z}') ");
arrayStr.Add($"array_contains(c.stuLists,'{z}') ");
if (userScope.Equals(Constant.ScopeTeacher))
{
arrayStr.Add($"array_contains(c.tchLists,'{z}') ");
}
});
groupListSQL = $"and ({string.Join(" or ", arrayStr)})";
}
else
{
throw new Exception("名单为空");
}
List datas = new List();
if (types.IsEmpty() || types.Contains("Exam"))
{
string subjectSQL = "";
string subjectJoin = "";
if (subjects.IsNotEmpty())
{
subjectJoin = "join s in c.subjects";
subjectSQL = $" and s.id in ({string.Join(",", subjects.Select(z => $"'{z}'"))}) ";
}
StringBuilder SQL = new StringBuilder($"select distinct {filed} from c {subjectJoin} where c.pk='Exam' {subjectSQL} {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} and c.qamode != 2 ");
//获取学校发布的活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL} and c.owner='school' ", $"Exam-{school}");
if (resultSchool.list.Count > 0) {
List activity = await getStuActivity(_azureCosmos, resultSchool.list, school, userId, userScope);
datas.AddRange(activity);
}
}
//获取教师发布的活动(个人名单,学校名单)
{
var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL} and c.owner='teacher' ");
if(resultTeacher.list.Count > 0) {
List activity = await getStuActivity(_azureCosmos, resultTeacher.list, school, userId, userScope);
datas.AddRange(activity);
}
}
}
if (types.IsEmpty() || types.Contains("Vote"))
{
StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Vote' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
//获取学校发布的活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='school' ", $"Vote-{school}");
if (resultSchool.list.Count > 0)
{
foreach (var vote in resultSchool.list)
{
vote.scode = vote.code;
vote.classIds = vote.classes.Count > 0 ? vote.classes : vote.stuLists;
List sub = new();
if (vote.tchLists.Count == 0)
{
if (vote.targets.Count > 0)
{
foreach (var course in vote.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
vote.subs = sub;
}
}
datas.AddRange(resultSchool.list);
}
//获取教师发布的活动(个人名单,学校名单)
{
var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='teacher' ");
if (resultTeacher.list.Count > 0)
{
foreach (var vote in resultTeacher.list)
{
vote.scode = vote.code;
vote.classIds = vote.classes.Count > 0 ? vote.classes : vote.stuLists;
List sub = new();
if (vote.tchLists.Count == 0)
{
if (vote.targets.Count > 0)
{
foreach (var course in vote.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
vote.subs = sub;
}
}
datas.AddRange(resultTeacher.list);
}
}
if (types.IsEmpty() || types.Contains("Survey"))
{
StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Survey' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
//获取学校发布的活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='school' ", $"Survey-{school}");
if (resultSchool.list.Count > 0)
{
foreach (var survey in resultSchool.list)
{
survey.scode = survey.code;
survey.classIds = survey.classes.Count > 0 ? survey.classes : survey.stuLists;
List sub = new();
if (survey.tchLists.Count == 0)
{
if (survey.targets.Count > 0)
{
foreach (var course in survey.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
survey.subs = sub;
}
}
datas.AddRange(resultSchool.list);
}
//获取教师发布的活动(个人名单,学校名单)
{
var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='teacher' ");
if (resultTeacher.list.Count > 0) {
foreach (var survey in resultTeacher.list) {
survey.scode = survey.code;
survey.stuLists = survey.classes.Count > 0 ? survey.classes : survey.stuLists;
List sub = new();
if (survey.tchLists.Count == 0)
{
if (survey.targets.Count > 0)
{
foreach (var course in survey.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
survey.subs = sub;
}
}
datas.AddRange(resultTeacher.list);
}
}
if (types.IsEmpty() || types.Contains("Homework"))
{
StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Homework' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
//获取学校发布的活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='school' ", $"Homework-{school}");
if (resultSchool.list.Count > 0)
{
foreach (var work in resultSchool.list)
{
work.classIds = work.classes.Count > 0 ? work.classes : work.stuLists;
work.scode = work.code;
List sub = new();
if (work.tchLists.Count == 0)
{
if (work.targets.Count > 0)
{
foreach (var course in work.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
work.subs = sub;
}
}
datas.AddRange(resultSchool.list);
}
//获取教师发布的活动(个人名单,学校名单)
{
var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='teacher' ");
if (resultTeacher.list.Count > 0)
{
foreach (var work in resultTeacher.list)
{
work.scode = work.code;
work.classIds = work.classes.Count > 0 ? work.classes : work.stuLists;
List sub = new();
if (work.tchLists.Count == 0)
{
if (work.targets.Count > 0)
{
foreach (var course in work.targets)
{
var info = course.ToObject>();
if (info.Count > 1)
{
sub.Add(info[0]);
}
}
}
}
work.subs = sub;
}
}
datas.AddRange(resultTeacher.list);
}
}
if (types.IsEmpty() || types.Contains("Art"))
{
string subjectSQL = "";
string subjectJoin = "";
if (subjects.IsNotEmpty())
{
subjectJoin = "join s in c.subjects";
subjectSQL = $" and s.id in ({string.Join(",", subjects.Select(z => $"'{z}'"))}) ";
}
StringBuilder SQL = new($"select distinct {filed} from c {subjectJoin} where c.pk='Art' {subjectSQL} {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
//获取学校发布的活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL} and c.school='{school}' ", $"Art-{school}");
if (resultSchool.list.Count > 0)
{
foreach (var stu in resultSchool.list)
{
stu.classIds = stu.classes;
}
}
datas.AddRange(resultSchool.list);
}
}
if (types.IsEmpty() || types.Contains("Study"))
{
StringBuilder SQL = new StringBuilder($"select {filed} from c where c.pk='Study' {groupListSQL} and c.startTime>={stime} and c.startTime <= {etime} ");
//获取学校发布的研修活动
if (userScope.Equals(Constant.ScopeStudent) && !string.IsNullOrWhiteSpace(school))
{
var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL} and c.owner='school' ", $"Study-{school}");
datas.AddRange(resultSchool.list);
}
/* //获取教师发布的活动(个人名单,学校名单)
{
var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList($"{SQL.ToString()} and c.owner='teacher' ");
datas.AddRange(resultTeacher.list);
}*/
}
//作答 记录recordUrl taskStatus
return datas.OrderByDescending(c => c.createTime).Distinct().ToList();
}
///
///
///
///
///
///
public static async Task> GeStudentData(AzureCosmosFactory _azureCosmos, string schoolId, IEnumerable students)
{
List studentDatas = new List();
if (students.Any())
{
string queryText = $"SELECT c.id, c.code ,c.classId ,c.year FROM c WHERE c.id IN ({string.Join(",", students.Select(o => $"'{o}'"))})";
await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
{
studentDatas.Add(item);
}
}
return studentDatas;
}
public static async Task> getStuActivity(AzureCosmosFactory _azureCosmos, List activities, string school, string userId, string userScope)
{
//获取所有活动Id
List examIds = activities.Select(c => c.id).ToList();
List examClassResults = new();
await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator(
queryText: $"select value(c) from c where c.examId in ({string.Join(",", examIds.Select(z => $"'{z}'"))}) and c.pk = 'ExamClassResult'" ))
{
examClassResults.Add(item);
}
bool iss = false;
//标记学生作答状态
int ts = 0;
List<(string eId, int status)> et = new();
List<(string eId, bool flag)> es = new();
if (examClassResults.Count > 0)
{
foreach (ExamClassResult exam in examClassResults)
{
//List<(string eId, int status)> examTasks = new();
//List<(string eId, bool flag)> examStatus = new();
int index = exam.studentIds.IndexOf(userId);
if (index != -1)
{
if (exam.studentAnswers[index].Count > 0)
{
bool flag = exam.studentScores[index].Exists(x => x == -1);
if (!flag)
{
ts = 1;
iss = true;
//break;
}
else
{
iss = false;
ts = 0;
}
et.Add((exam.examId, ts));
es.Add((exam.examId,iss));
}
else
{
ts = -1;
iss = false;
et.Add((exam.examId, ts));
es.Add((exam.examId, iss));
}
}
}
}
var stuActivity = activities.Select(x => new StudentActivity
{
id = x.id,
stuId = userId,
userType = userScope,
type = "Exam",
name = x.name,
source = x.source,
startTime = x.startTime,
endTime = x.endTime,
scope = x.scope,
school = x.school,
scode = x.code,
creatorId = x.creatorId,
subjects = x.subjects,
owner = x.owner,
classIds = x.classes.Count > 0 ? x.classes : x.stuLists,
code = x.code,
createTime = x.createTime,
qamode = x.qamode,
examType = x.examType,
//taskStatus = et.Select(c => c[x.id]).FirstOrDefault(),
//ext = new Dictionary() { { "type", !string.IsNullOrEmpty(x.examType) ? x.examType.ToJsonString().ToObject():new JsonElement() },
//{ "subjects", x.subjects.ToJsonString().ToObject() } },
taskStatus = et.Where(c => c.eId.Equals(x.id)).FirstOrDefault().status,
sStatus = es.Where(z => z.eId.Equals(x.id)).FirstOrDefault().flag ? 1 : 0
//sStatus = es.Select(c => c[x.id]).FirstOrDefault() ? 1 : 0
}).ToList();
return stuActivity;
}
///
///
///
/// 学校编码
/// 前端要修改的学生
/// 操作
/// 变更前的学生
///
public static async Task> CheckStudent(AzureServiceBusFactory _serviceBus, IConfiguration _configuration, AzureCosmosFactory _azureCosmos, string schoolId, List students, List prestudents)
{
List aftstudents = await StudentService.GeStudentData(_azureCosmos, schoolId, students?.Select(x => x.id));
Dictionary dictChange = new Dictionary();
if (prestudents.Count >= aftstudents.Count)
{
foreach (var pstu in prestudents)
{
var afstu = aftstudents.Find(x => x.id.Equals(pstu.id));
if (afstu != null)
{
if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
{
//则是加入的学生
if (dictChange.ContainsKey(afstu.classId))
{
dictChange[afstu.classId].stujoin.Add(
new Member
{
id = afstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = afstu.classId,
stujoin = new List
{
new Member
{
id= afstu.id,
code= $"{schoolId}",
type =2
}
}
};
dictChange.Add(afstu.classId, change);
}
}
else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
{
//则该学生是解除了班级状态
if (dictChange.ContainsKey(pstu.classId))
{
dictChange[pstu.classId].stuleave.Add(
new Member
{
id = pstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = pstu.classId,
stuleave = new List
{
new Member
{
id= pstu.id,
code= $"{schoolId}",
type=2
}
}
};
dictChange.Add(pstu.classId, change);
}
}
else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
{
//id不同则有异动
if (!pstu.classId.Equals(afstu.classId))
{
//则是加入的学生
if (dictChange.ContainsKey(afstu.classId))
{
dictChange[afstu.classId].stujoin.Add(
new Member
{
id = afstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = afstu.classId,
stujoin = new List
{
new Member
{
id= afstu.id,
code= $"{schoolId}",
type = 2
}
}
};
dictChange.Add(afstu.classId, change);
}//则该学生是解除了班级状态
if (dictChange.ContainsKey(pstu.classId))
{
dictChange[pstu.classId].stuleave.Add(
new Member
{
id = pstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = pstu.classId,
stuleave = new List
{
new Member
{
id= pstu.id,
code= $"{schoolId}",
type= 2
}
}
};
dictChange.Add(pstu.classId, change);
}
}
else
{
//相同则不管
}
}
else
{
//变更前后都没绑定班级则不管。
}
}
else
{
if (!string.IsNullOrEmpty(pstu.classId))
{
//则该学生是被删除的学生
if (dictChange.ContainsKey(pstu.classId))
{
dictChange[pstu.classId].stuleave.Add(
new Member
{
id = pstu.id,
code = $"Base-{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = pstu.classId,
stuleave = new List
{
new Member
{
id= pstu.id,
code= $"{schoolId}",
type = 2
}
}
};
dictChange.Add(pstu.classId, change);
}
}
}
}
}
else
{
foreach (var afstu in aftstudents)
{
var pstu = prestudents.Find(x => x.id.Equals(afstu.id));
if (pstu != null)
{
if (string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
{
//则是加入的学生
if (dictChange.ContainsKey(afstu.classId))
{
dictChange[afstu.classId].stujoin.Add(
new Member
{
id = afstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client = "web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = afstu.classId,
stujoin = new List
{
new Member
{
id= afstu.id,
code= $"Base-{schoolId}",
type = 2
}
}
};
dictChange.Add(afstu.classId, change);
}
}
else if (!string.IsNullOrEmpty(pstu.classId) && string.IsNullOrEmpty(afstu.classId))
{
//则该学生是解除了班级状态
if (dictChange.ContainsKey(pstu.classId))
{
dictChange[pstu.classId].stuleave.Add(
new Member
{
id = pstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = pstu.classId,
stuleave = new List
{
new Member
{
id= pstu.id,
code= $"{schoolId}",
type= 2
}
}
};
dictChange.Add(pstu.classId, change);
}
}
else if (!string.IsNullOrEmpty(pstu.classId) && !string.IsNullOrEmpty(afstu.classId))
{
//id不同则有异动
if (!pstu.classId.Equals(afstu.classId))
{
//则是加入的学生
if (dictChange.ContainsKey(afstu.classId))
{
dictChange[afstu.classId].stujoin.Add(
new Member
{
id = afstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = afstu.classId,
stujoin = new List
{
new Member
{
id= afstu.id,
code= $"{schoolId}",
type = 2
}
}
};
dictChange.Add(afstu.classId, change);
}//则该学生是解除了班级状态
if (dictChange.ContainsKey(pstu.classId))
{
dictChange[pstu.classId].stuleave.Add(
new Member
{
id = pstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = pstu.classId,
stuleave = new List
{
new Member
{
id= pstu.id,
code= $"{schoolId}",
type=2
}
}
};
dictChange.Add(pstu.classId, change);
}
}
else
{
//相同则不管
}
}
else
{
//变更前后都没绑定班级则不管。
}
}
else
{
if (!string.IsNullOrEmpty(afstu.classId))
{
//代表学生是新增的
if (dictChange.ContainsKey(afstu.classId))
{
dictChange[afstu.classId].stujoin.Add(
new Member
{
id = afstu.id,
code = $"{schoolId}",
type = 2
});
}
else
{
GroupChange change = new GroupChange
{
client="web",
scope = "school",
school = schoolId,
type = "student",
originCode = schoolId,
listid = afstu.classId,
stujoin = new List
{
new Member
{
id= afstu.id,
code= $"{schoolId}",
type = 2
}
}
};
dictChange.Add(afstu.classId, change);
}
}
}
}
}
List classes = new List();
if (dictChange.Keys.Count>0)
{
string insql = string.Join(",", dictChange.Keys.Select(x => $"'{x}'"));
var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetList($"select c.id,c.name from c where c.id in ({insql})", $"Class-{schoolId}");
if (result.list.IsNotEmpty())
{
classes.AddRange(result.list);
}
}
foreach (var changed in dictChange.Keys)
{
var change = dictChange[changed];
if (change.stujoin.Count != 0 || change.stuleave.Count != 0)
{
var clazz= classes.Find(x => x.id.Equals(changed));
if (clazz!=null) {
change.name=clazz.name;
var messageChange = new ServiceBusMessage(change.ToJsonString());
messageChange.ApplicationProperties.Add("name", "GroupChange");
var ActiveTask = _configuration.GetValue("Azure:ServiceBus:ActiveTask");
await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
}
}
}
return dictChange;
}
public record StudentInfo
{
public string studentId { get; set; }
public string picture { get; set; }
public string name { get; set; }
public string mobile { get; set; }
public string mail { get; set; }
///
/// f女性 m男性 n 保密
///
public string gender { get; set; }
}
///
/// 整理前端匯入的學生資訊
///
///
///
///
private static (Dictionary guardians, string gender)> studs,
Dictionary classInfo,
Dictionary> classStudNo,
List errorYear,
List duplId) doSortImpStuds(string schoolId, JsonElement.ArrayEnumerator students)
{
//批量匯入 檢查輸入數據 確認座號 確認教室(創建教室) 確認學生存不存在或是要不要更新
//存放輸入的學生資訊 key:stud id value:學生詳細資料
Dictionary guardians, string gender)> dicStuds =
new Dictionary guardians, string gender)>();
//存放教室資訊用 key:classNo value:className
Dictionary dicClassInfo = new Dictionary();
//存放欲加入該間教室的學生座號清單 key:classNo value:no list
Dictionary> dicClassStudNo = new Dictionary>();
//存放輸入id重複
List duplId = new List();
List errorYear = new List();
while (students.MoveNext())
{
//string id = null, no = null, name = null, year = null, pw = null, classNo = null, className = null;
JsonElement student = students.Current;
//ClassNo內的座號
//欲加入的教室
//查學生
//該間教室的座號與目前欲更新的是否有重複 有些可能是同教室換座號 反正都要將學生讀出來
//舊學生完整資料+新學生資料
//進行輸入資料的整理
if (student.TryGetProperty("id", out var tmpId))
{
string id = tmpId.GetString();
//如果id欄位是空的,則跳過該筆資料
if (string.IsNullOrWhiteSpace(id)) continue;
//輸入的id不應有重複
if (dicStuds.ContainsKey(id))
{
//如果id重複,則將之從整理清單內清除
duplId.Add(id);
dicStuds.Remove(id);
}
(string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int classYear,
string guardian, string gName, string gPhone, string imei, List guardians, string gender) studentInfo =
(null, null, 0, null, null, null, null, null, 0, null, null, null, null, null, null);
if (student.TryGetProperty("name", out var tmpName) && !string.IsNullOrWhiteSpace(tmpName.GetString())) studentInfo.name = tmpName.GetString();
//入學學年為必須,故若是無給值則將之紀錄並跳過該筆資料
if (student.TryGetProperty("year", out var tmpYear) && !string.IsNullOrWhiteSpace(Convert.ToString(tmpYear))) studentInfo.year = tmpYear.GetInt32();
else
{
errorYear.Add(id);
continue;
}
//Password,若沒給則使用學號當密碼
studentInfo.salt = Utils.CreatSaltString(8);
studentInfo.pw = student.TryGetProperty("pw", out var tmpPw) && !string.IsNullOrWhiteSpace(tmpPw.GetString())
? Utils.HashedPassword(tmpPw.GetString(), studentInfo.salt)
: Utils.HashedPassword(id, studentInfo.salt);
if (student.TryGetProperty("periodId", out var tmpPeriodId) && !string.IsNullOrWhiteSpace(tmpPeriodId.GetString())) studentInfo.periodId = tmpPeriodId.GetString();
// if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
if (student.TryGetProperty("classNo", out var tmpClassNo) && !string.IsNullOrWhiteSpace(tmpClassNo.GetString()))
{
studentInfo.classNo = tmpClassNo.GetString();
//在新建帳號上,應要給classNo才能設定no,但是若只是已存在的帳號要進行座號更新呢? 為避免使用者出錯,故已存在的帳號也應當給classNo。
if (student.TryGetProperty("no", out var tmpNo) && !string.IsNullOrWhiteSpace(tmpNo.GetString()))
{
studentInfo.no = tmpNo.GetString();
//這邊先將該間教室欲使用到的no整理出來
if (dicClassStudNo.ContainsKey(tmpClassNo.GetString())) dicClassStudNo[tmpClassNo.GetString()].Add((id, tmpNo.GetString()));
else dicClassStudNo.Add(tmpClassNo.GetString(), new List<(string id, string no)>() { (id, tmpNo.GetString()) });
}
//有給classNo才會紀錄className,classNo屬於實體教室門牌號,全校理當只會有一個。
int year = 0;
if (student.TryGetProperty("classYear", out var tmpClassYear) && tmpClassYear.TryGetInt32(out int syear))
{
year = syear;
studentInfo.classYear = syear;
}
if (student.TryGetProperty("className", out var tmpClassName) && !string.IsNullOrWhiteSpace(tmpClassName.GetString()))
{
studentInfo.className = tmpClassName.GetString();
if (!dicClassInfo.ContainsKey($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"))
{ dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, year, tmpClassNo.GetString())); }
}
}
///导入的时候
if (student.TryGetProperty("guardian", out var guardian) && !string.IsNullOrWhiteSpace($"{guardian}"))
{
studentInfo.guardian = $"{guardian}";
student.TryGetProperty("gName", out var gName);
student.TryGetProperty("gPhone", out var gPhone);
studentInfo.gName = $"{gName}";
studentInfo.gPhone = $"{gPhone}";
}
//更新的时候
if (student.TryGetProperty("guardians", out var _guardians) && _guardians.ValueKind.Equals(JsonValueKind.Array))
{
List guardians = _guardians.Deserialize>();
studentInfo.guardians = guardians;
}
if (student.TryGetProperty("imei", out var tmpImei) && !string.IsNullOrWhiteSpace($"{tmpImei}")) studentInfo.imei = tmpImei.GetString();
if (student.TryGetProperty("gender", out var tmpgender) && !string.IsNullOrWhiteSpace($"{tmpgender}")) studentInfo.gender = tmpgender.GetString();
//將最後結果加到字典內
dicStuds.Add(id, studentInfo);
}
}
return (dicStuds, dicClassInfo, dicClassStudNo, errorYear, duplId);
}
///
/// 更新或是新增學生
///
///
///
///
public static async Task<(List