using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using TEAMModelOS.SDK.DI;
using TEAMModelOS.SDK;
using TEAMModelOS.Models;
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using TEAMModelOS.SDK.Models.Dtos;
using TEAMModelOS.SDK.Context.Constant;
using System.Collections.Generic;
using System.Text.Json;
using TEAMModelOS.SDK.Extension;
using TEAMModelOS.Filter;
using TEAMModelOS.SDK.Models;
using Azure.Cosmos;
using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
using System;
using System.Text;
namespace TEAMModelOS.Controllers
{ ///
/// 企业定制化接口
///
[Route("business")]
[ApiController]
public class BizCustomizeController : ControllerBase
{
public AzureCosmosFactory _azureCosmos;
private readonly AzureStorageFactory _azureStorage;
private readonly AzureRedisFactory _azureRedis;
private readonly DingDing _dingDing;
private readonly Option _option;
private readonly IConfiguration _configuration;
private readonly CoreAPIHttpService _coreAPIHttpService;
private readonly AzureServiceBusFactory _serviceBus;
private readonly SnowflakeId _snowflakeId;
public BizCustomizeController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, AzureServiceBusFactory serviceBus, DingDing dingDing, CoreAPIHttpService coreAPIHttpService, IOptionsSnapshot option, IConfiguration configuration, SnowflakeId snowflakeId)
{
_azureCosmos = azureCosmos;
_azureStorage = azureStorage;
_azureRedis = azureRedis;
_dingDing = dingDing;
_option = option?.Value;
_configuration = configuration;
_coreAPIHttpService = coreAPIHttpService;
_serviceBus = serviceBus;
_snowflakeId = snowflakeId;
}
#region 杉达公司
///
/// 开课或者上传课例信息 是因支持VR/AR的公司(杉达)
///
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesDefaultResponseType]
[HttpPost("create-vrar-lesson-shanda")]
[ApiToken(Auth = "2003", Name = "VR·AR开课/上传课例信息", TName = "VR·AR開課/上傳課例信息", EName = "Start VR·AR lesson/upload VR·AR lesson ", RWN = "W", Limit = false)]
public async Task UpLessonRec(JsonElement jsonElement)
{
var (id, school) = HttpContext.GetApiTokenInfo();
try
{
jsonElement.TryGetProperty("baseJson", out JsonElement baseJson); //课例基础文件信息json
jsonElement.TryGetProperty("timLineJson", out JsonElement timLineJson); //时间json
jsonElement.TryGetProperty("lessonId", out JsonElement lessonId); //课例id
if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return Ok(new { responseDate = new ResponseData() { code = RespondCode.ParamsError, msg = "tmdId参数错误", data = null } }); //上课人ID
jsonElement.TryGetProperty("tmdName", out JsonElement tmdName); //上课人昵称
jsonElement.TryGetProperty("tmdPicture", out JsonElement tmdpicture); //上课人头像
if (!jsonElement.TryGetProperty("startTime", out JsonElement startTime)) return Ok(new { responseDate = new ResponseData() { code = RespondCode.ParamsError, msg = "startTime参数错误", data = null } }); //开始时间
if (!jsonElement.TryGetProperty("duration", out JsonElement duration)) return Ok(new { responseDate = new ResponseData() { code = RespondCode.ParamsError, msg = "startTime参数错误", data = null } }); //上课时长
jsonElement.TryGetProperty("periodId", out JsonElement periodId); //学段id
jsonElement.TryGetProperty("periodName", out JsonElement periodName); //学段名称
jsonElement.TryGetProperty("groupIds", out JsonElement _groupIds); //名单id
jsonElement.TryGetProperty("groupNames", out JsonElement _groupNames); //名单名称
jsonElement.TryGetProperty("gradeIds", out JsonElement _gradeIds); //年级id
jsonElement.TryGetProperty("gradeNames", out JsonElement _gradeNames); //年级名称
jsonElement.TryGetProperty("subjectId", out JsonElement subjectId); //科目id
jsonElement.TryGetProperty("subjecName", out JsonElement subjecName); //科目名称
jsonElement.TryGetProperty("courseId", out JsonElement courseId); //课程id
jsonElement.TryGetProperty("courseName", out JsonElement courseName); //课程名称
LessonRecord lessonRecord = new();
LessonBase lessonBase = null;
TimeLine timeLine = null;
if (!string.IsNullOrEmpty($"{baseJson}"))
{
lessonBase = baseJson.ToObject();
lessonRecord.upload = 1;
}
else
lessonRecord.upload = 0;
if (!string.IsNullOrEmpty($"{timLineJson}"))
{
timeLine = timLineJson.ToObject();
lessonRecord.upload = 1;
}
else
lessonRecord.upload = 0;
List groupIds = new();
List groupNames = new();
List gradeIds = new();
List gradeNames = new();
if (!string.IsNullOrEmpty($"{_groupIds}"))
groupIds = _groupIds.ToObject>();
if (!string.IsNullOrEmpty($"{_groupNames}"))
groupNames = _groupNames.ToObject>();
if (!string.IsNullOrEmpty($"{_gradeIds}"))
gradeIds = _gradeIds.ToObject>();
if (!string.IsNullOrEmpty($"{_gradeNames}"))
gradeNames = _gradeNames.ToObject>();
var cosmosClient = _azureCosmos.GetCosmosClient();
string code = $"LessonRecord-{school}";
var resLess = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{lessonId}", new PartitionKey($"{code}"));
if (resLess.Status == 200)
{
JsonDocument jsonD = JsonDocument.Parse(resLess.Content);
lessonRecord = jsonD.RootElement.ToObject();
}
else
{
lessonRecord.id = _snowflakeId.NextId().ToString();
lessonRecord.code = code;
}
lessonRecord.tmdid = $"{tmdId}";
lessonRecord.tmdname = $"{tmdName}";
lessonRecord.tmdpicture = $"{tmdpicture}";
lessonRecord.school = school;
lessonRecord.scope = "school";
lessonRecord.startTime = long.Parse($"{startTime}");
lessonRecord.duration = double.Parse($"{duration}");
lessonRecord.periodId = $"{periodId}";
lessonRecord.periodName = $"{periodName}";
lessonRecord.subjectId = $"{subjectId}";
lessonRecord.subjecName = $"{subjecName}";
lessonRecord.courseId = $"{courseId}";
lessonRecord.courseName = $"{courseName}";
lessonRecord.groupIds = groupIds;
lessonRecord.groupNames = groupNames;
lessonRecord.grade = gradeIds;
lessonRecord.gradeName = gradeNames;
if (!string.IsNullOrEmpty($"{baseJson}"))
{
lessonRecord.name = lessonBase.summary.activityName;
lessonRecord.attendCount = lessonBase.summary.attendCount;
lessonRecord.clientCount = lessonBase.summary.clientCount;
lessonRecord.attendRate = lessonBase.summary.attendRate;
lessonRecord.groupCount = lessonBase.summary.groupCount;
lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
lessonRecord.collateCount = lessonBase.summary.collateCount;
lessonRecord.pushCount = lessonBase.summary.pushCount;
lessonRecord.totalPoint = lessonBase.summary.totalPoint;
lessonRecord.examQuizCount = lessonBase.summary.examQuizCount;
lessonRecord.interactionCount = lessonBase.summary.interactionCount;
lessonRecord.examPointRate = lessonBase.summary.examPointRate;
lessonRecord.clientInteractionCount = lessonBase.summary.clientInteractionCount;
lessonRecord.clientInteractionAverge = lessonBase.summary.clientInteractionAverge;
lessonRecord.examCount = lessonBase.summary.examCount;
lessonRecord.totalInteractPoint = lessonBase.summary.totalInteractPoint;
lessonRecord.learningCategory = lessonBase.summary.learningCategory;
lessonRecord.source = 1;
//计算TP灯
{
int T = -1;
int P = -1;
if (lessonRecord.clientInteractionAverge <= 0)
{
T = 0;
}
else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
{
T = 1;
}
else
{
T = 2;
}
//if (lessonRecord.examCount > 0)
//{
// //有评测次数大于0则P是直接绿灯
// P = 2;
//}
//else {
//}
int a = lessonRecord.hitaClientCmpCount;
int b = lessonRecord.pushCount;
int c = lessonRecord.examCount;
switch (true)
{
case bool when T == 0:
P = 0;
break;
case bool when T == 1 || T == 2:
if (a == 0 && b == 0 && c == 0)
{
P = 0;
}
else if ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0))
{
P = 2;
}
else
{
P = 1;
}
break;
}
lessonRecord.tLevel = T;
lessonRecord.pLevel = P;
}
}
if (resLess.Status == 200)
lessonRecord = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey($"{code}"));
else
lessonRecord = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(lessonRecord, new PartitionKey($"{code}"));
var blobClient = _azureStorage.GetBlobContainerClient(containerName: $"{school}");
if (!string.IsNullOrEmpty($"{baseJson}"))
//保存Basejson文件
await AzureStorageBlobExtensions.UploadFileByContainer(blobClient, lessonBase.ToJsonString(), $"records/{lessonRecord.id}/IES", $"Base.json");
if (!string.IsNullOrEmpty($"{timLineJson}"))
//保存TimeLinejson文件
await AzureStorageBlobExtensions.UploadFileByContainer(blobClient, timeLine.ToJsonString(), $"records/{lessonRecord.id}/IES", $"TimeLine.json");
return Ok(new
{
responseData = new ResponseData()
{
code = RespondCode.Ok,
msg = "成功",
data = new
{
lessonRecord,
analysis = new
{
lessonRecord.id,
lessonRecord.name,
lessonRecord.subjectId,
lessonRecord.courseId,
intIndex = lessonRecord.tLevel,
learning = lessonRecord.pLevel,
atendCnt = lessonRecord.attendCount,
grCnt = lessonRecord.groupCount,
taskCnt = lessonRecord.collateTaskCount,
worksCnt = lessonRecord.collateCount,
pushCnt = lessonRecord.pushCount,
scoreCnt = lessonRecord.totalPoint,
emCnt = lessonRecord.examCount,
intTopicCnt = lessonRecord.interactionCount,
emPct = $"{lessonRecord.examPointRate} %",
stuIntCnt = lessonRecord.clientInteractionCount,
study = new
{
coopCnt = lessonRecord.learningCategory.cooperation,
testCnt = lessonRecord.learningCategory.exam,
intCnt = lessonRecord.learningCategory.interaction,
dCnt = lessonRecord.learningCategory.diffential,
taskCnt = lessonRecord.learningCategory.task,
}
}
}
}
});
}
catch (Exception ex)
{
await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} BizOverallEducation/UpLessonRec() 参数:bizId:{id},school:{school},json:{jsonElement.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
return Ok(new { responseData = new ResponseData() { code = RespondCode.Error, msg = "服务端异常" } });
}
}
///
/// 获取学校课例 是因支持VR/AR的公司(杉达)
///
///
///
[ProducesDefaultResponseType]
[HttpPost("get-lesson-relords")]
[ApiToken(Auth = "2004", Name = "获取学校课例", TName = "獲取學校課例", EName = "Get school lessons", RWN = "R", Limit = false)]
public async Task GetLessonRec(JsonElement jsonElement)
{
var (id, school) = HttpContext.GetApiTokenInfo();
jsonElement.TryGetProperty("lessonId", out JsonElement lessId);
var cosmosClient = _azureCosmos.GetCosmosClient();
StringBuilder sql = new("select value(c) from c where c.source=1");
if (!string.IsNullOrEmpty($"{lessId}"))
sql.Append($" and c.id='{lessId}'");
List lessonRecords = new();
await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
{
lessonRecords.Add(item);
}
return Ok(new { responseData = new ResponseData() { code = RespondCode.Ok, msg = "成功", data = lessonRecords } });
}
///
/// 获取学校课例分析结果 是因支持VR/AR的公司(杉达)
///
///
///
[ProducesDefaultResponseType]
[HttpPost("get-lesson-analysis")]
[ApiToken(Auth = "2006", Name = "获取学校课例", TName = "獲取學校課例", EName = "Get school lessons", RWN = "R", Limit = false)]
public async Task GetLessonStats(JsonElement jsonElement)
{
var (id, school) = HttpContext.GetApiTokenInfo();
if (!jsonElement.TryGetProperty("lessonId", out JsonElement lessonId)) return Ok(new { responseDate = new ResponseData() { code = RespondCode.ParamsError, msg = "lessId参数错误", data = null } }); //上课人ID ;
var cosmosClient = _azureCosmos.GetCosmosClient();
dynamic analysis = null;
await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"select c.id,c.name,c.subjectId,c.courseId,c.tLevel,c.pLevel,c.attendCount,c.groupCount,c.collateTaskCount,c.collateCount,c.pushCount,c.totalPoint,c.examCount,c.interactionCount,c.examPointRate,c.clientInteractionCount,c.learningCategory from c where c.id='{lessonId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
{
using var json = await JsonDocument.ParseAsync(item.ContentStream);
if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
{
var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
while (accounts.MoveNext())
{
JsonElement account = accounts.Current;
LearningCategory learningCategory = account.GetProperty("learningCategory").ToObject();
analysis = new
{
id = account.GetProperty("id").GetString(),
name = account.GetProperty("name").GetString(),
subjectId = account.GetProperty("subjectId").GetString(),
courseId = account.GetProperty("courseId").GetString(),
intIndex = account.GetProperty("tLevel").GetInt64(),
learning = account.GetProperty("pLevel").GetInt64(),
atendCnt = account.GetProperty("attendCount").GetInt64(),
grCnt = account.GetProperty("groupCount").GetInt64(),
taskCnt = account.GetProperty("collateTaskCount").GetInt64(),
worksCnt = account.GetProperty("collateCount").GetInt64(),
pushCnt = account.GetProperty("pushCount").GetInt64(),
scoreCnt = account.GetProperty("totalPoint").GetInt64(),
emCnt = account.GetProperty("examCount").GetInt64(),
intTopicCnt = account.GetProperty("interactionCount").GetInt64(),
emPct = $"{account.GetProperty("examPointRate").GetDouble()} %",
stuIntCnt = account.GetProperty("clientInteractionCount").GetInt64(),
study = new
{
coopCnt = learningCategory.cooperation,
testCnt = learningCategory.exam,
intCnt = learningCategory.interaction,
dCnt = learningCategory.diffential,
taskCnt = learningCategory.task,
}
};
//var ids = account.GetProperty("id").GetString();
//var name = account.GetProperty("name").GetString();
//var intIndex = account.GetProperty("tLevel").GetInt64();
//var learning = account.GetProperty("pLevel").GetInt64();
//var atendCnt = account.GetProperty("attendCount").GetInt64();
//var grCnt = account.GetProperty("groupCount").GetInt64();
//var taskCnt = account.GetProperty("collateTaskCount").GetInt64();
//var worksCnt = account.GetProperty("collateCount").GetInt64();
//var pushCnt = account.GetProperty("pushCount").GetInt64();
//var scoreCnt = account.GetProperty("totalPoint").GetInt64();
//var emCnt = account.GetProperty("examCount").GetInt64();
//var intTopicCnt = account.GetProperty("interactionCount").GetInt64();
//var emPct = $"{account.GetProperty("examPointRate").GetDouble()} %";
//var stuIntCnt = account.GetProperty("clientInteractionCount").GetInt64();
//var study = new
//{
// coopCnt = learningCategory.cooperation,
// testCnt = learningCategory.exam,
// intCnt = learningCategory.interaction,
// dCnt = learningCategory.diffential
//};
}
}
}
return Ok(new { responseData = new ResponseData() { code = RespondCode.Ok, msg = "成功", data = analysis } });
}
#endregion
#region 智音公司
///
/// 添加/修改学生艺术评测(音乐)答题结果
///
///
///
[ProducesDefaultResponseType]
[HttpPost("set-stdent-score")]
[ApiToken(Auth = "2005", Name = "添加/修改学生艺术评测(音乐)答题结果", TName = "添加/修改學生藝術評測音樂答題結果", EName = "Add/modify the music answer results of student art evaluation", RWN = "W", Limit = false)]
public async Task SetStudnetScore(JsonElement jsonElement)
{
var (id, school) = HttpContext.GetApiTokenInfo();
if (!jsonElement.TryGetProperty("oAnswer", out JsonElement _oAnswer)) return Ok(new { responseDate = new ResponseData() { code = RespondCode.ParamsError, msg = "oaswer参数错误", data = null } });
OAnswerUp oAnswer = _oAnswer.ToObject();
StudentArtResult studentArtResult = new();
var cosmosClient = _azureCosmos.GetCosmosClient();
var resArt = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync($"{school}-{oAnswer.studentId}", new PartitionKey($"ArtResult-{oAnswer.artId}"));
if (resArt.Status == 200)
{
JsonDocument jsonD = JsonDocument.Parse(resArt.Content);
studentArtResult = jsonD.RootElement.ToObject();
var temp = studentArtResult.results.Find(f => f.taskId.Equals(oAnswer.thirdAnswerId));
temp.score = oAnswer.score;
temp.source = 1;
studentArtResult.oAnswer.questionId = oAnswer.questionId;
studentArtResult.oAnswer.thirdAnswerId = oAnswer.thirdAnswerId;
studentArtResult.oAnswer.score = oAnswer.score;
studentArtResult.oAnswer.detail = oAnswer.detail;
await cosmosClient.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(studentArtResult, studentArtResult.id, new PartitionKey(studentArtResult.code));
}
else
return Ok(new { responseDate = new ResponseData() { code = RespondCode.NotFound, msg = "未找到活动相关学生答题信息", data = null } });
return Ok(new { responseData = new ResponseData() { code = RespondCode.Ok, msg = "成功", data = oAnswer } });
}
#endregion
}
}