LessonSticsController.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using TEAMModelOS.Models;
  8. using TEAMModelOS.SDK.DI;
  9. using Microsoft.Extensions.Options;
  10. using Microsoft.Azure.Cosmos;
  11. using System.Text.Json;
  12. using TEAMModelOS.SDK.Models.Cosmos.Common;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelBI.Models;
  15. using TEAMModelOS.SDK.Extension;
  16. using System.Text;
  17. using TEAMModelBI.Tool;
  18. using MathNet.Numerics.LinearAlgebra.Double;
  19. using TEAMModelBI.Tool.CosmosBank;
  20. using TEAMModelOS.SDK.Context.BI;
  21. using TEAMModelOS.SDK.Models.Service.BI;
  22. using TEAMModelOS.SDK.Context.Constant;
  23. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  24. using TEAMModelOS.SDK.Models.Cosmos.BI.BITable;
  25. using StackExchange.Redis;
  26. using System.Threading;
  27. namespace TEAMModelBI.Controllers.Census
  28. {
  29. [Route("lesson")]
  30. [ApiController]
  31. public class LessonSticsController : ControllerBase
  32. {
  33. private readonly AzureCosmosFactory _azureCosmos;
  34. private readonly AzureStorageFactory _azureStorage;
  35. private readonly AzureRedisFactory _azureRedis;
  36. private readonly DingDing _dingDing;
  37. private readonly Option _option;
  38. public LessonSticsController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureFactory, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option)
  39. {
  40. _azureCosmos = azureCosmos;
  41. _azureStorage = azureFactory;
  42. _azureRedis = azureRedis;
  43. _dingDing = dingDing;
  44. _option = option?.Value;
  45. }
  46. /// <summary>
  47. /// 依据区级ID分析该去所有学校课例 //已对接
  48. /// </summary>
  49. /// <param name="jsonElement"></param>
  50. /// <returns></returns>
  51. [ProducesDefaultResponseType]
  52. [HttpPost("get-schoolan")]
  53. public async Task<IActionResult> GetSchoolsAn(JsonElement jsonElement)
  54. {
  55. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  56. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  57. var (lWeekS, lWeekE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
  58. var (monthS, monthE) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
  59. var cosmosClient = _azureCosmos.GetCosmosClient();
  60. ////分开部署,就不需要,一站多用时,取消注释
  61. //if ($"{site}".Equals(BIConst.Global))
  62. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  63. List<AreaSchools> areaSchools = new();
  64. StringBuilder scSql = new("select c.id,c.name,c.picture from c ");
  65. if (!string.IsNullOrEmpty($"{areaId}"))
  66. scSql.Append($" where c.areaId='{areaId}'");
  67. else
  68. scSql.Append($" where c.areaId = null or c.areaId = ''");
  69. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<AreaSchools>(queryText: scSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base")}))
  70. {
  71. areaSchools.Add(item);
  72. }
  73. if (areaSchools.Count > 0)
  74. {
  75. foreach (var item in areaSchools)
  76. {
  77. item.allCnt = await CommonFind.GetSqlValueCount(cosmosClient,"School",$"select value(count(c.id)) from c ",$"LessonRecord-{item.id}");
  78. item.weekCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c where c.startTime >= {lWeekS} and c.startTime <= {lWeekE}", $"LessonRecord-{item.id}");
  79. item.monthCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c where c.startTime >= {monthS} and c.startTime <= {monthE}", $"LessonRecord-{item.id}");
  80. }
  81. areaSchools = areaSchools.Where(w => (w.allCnt != 0 || w.weekCnt != 0 || w.monthCnt != 0)).ToList();
  82. }
  83. return Ok(new { state = RespondCode.Ok, areaSchools });
  84. }
  85. /// <summary>
  86. /// 统计区级一年每周的课例数据趋势 //已对接
  87. /// </summary>
  88. /// <param name="jsonElement"></param>
  89. /// <returns></returns>
  90. [ProducesDefaultResponseType]
  91. [HttpPost("get-weekcount")]
  92. public async Task<IActionResult> GetWeekCount(JsonElement jsonElement)
  93. {
  94. jsonElement.TryGetProperty("areaId", out JsonElement areaId);
  95. jsonElement.TryGetProperty("isJoin", out JsonElement isJoin);
  96. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  97. //Dictionary<int, double> weeks = new();
  98. List<double> weeks = new();
  99. var cosmosClient = _azureCosmos.GetCosmosClient();
  100. ////分开部署,就不需要,一站多用时,取消注释
  101. //if ($"{site}".Equals(BIConst.Global))
  102. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  103. int year = DateTimeOffset.UtcNow.Year;
  104. int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
  105. int currentTime = DateTimeOffset.UtcNow.DayOfYear / 7 + 1;
  106. int currentTime1 = DateTimeOffset.UtcNow.DayOfYear / 7;
  107. var sqlTxts = "select value(c) from c";
  108. List<LessonCount> scount = new();
  109. List<LessonCount> tcount = new();
  110. StringBuilder sqlTxt = new("select value(c.id) from c");
  111. if (!string.IsNullOrEmpty($"{areaId}"))
  112. sqlTxt.Append($" where c.areaId='{areaId}'");
  113. else
  114. {
  115. if ($"{isJoin}".Equals("noJoin"))
  116. sqlTxt.Append($" where c.areaId = null or c.areaId = ''");
  117. }
  118. List<string> schools = await CommonFind.GetValueSingle(cosmosClient, "School",sqlTxt.ToString(), "Base");
  119. foreach (var sId in schools)
  120. {
  121. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<LessonCount>(queryText: sqlTxts, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{sId}-{year}") }))
  122. {
  123. scount.Add(item);
  124. }
  125. }
  126. List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, schools);
  127. foreach (var tId in teacIds)
  128. {
  129. var sqlTxtt = $"select value(c) from c where c.id='{tId}'";
  130. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIteratorSql<LessonCount>(queryText: sqlTxtt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{year}") }))
  131. {
  132. tcount.Add(item);
  133. }
  134. }
  135. int days = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? days = 366 : days = 365;
  136. List<List<double>> lessons = new();
  137. if (scount.Count > 0)
  138. {
  139. foreach (LessonCount item in scount)
  140. {
  141. lessons.Add(item.beginCount);
  142. }
  143. }
  144. if (tcount.Count > 0)
  145. {
  146. foreach (LessonCount item in tcount)
  147. {
  148. lessons.Add(item.beginCount);
  149. }
  150. }
  151. if (lessons.Count > 0)
  152. {
  153. var bmatrix = DenseMatrix.OfColumns(lessons);
  154. //开学第一周周内开课
  155. if (dayOfweek == 0)
  156. {
  157. dayOfweek = 7;
  158. }
  159. //第一周多少天
  160. var dd = 7 - dayOfweek + 1;
  161. //一年有几周
  162. int sweeks = days / 7;
  163. //查询天数
  164. int dayYear = 0;
  165. if (currentTime > 0)
  166. {
  167. for (int i = 0; i <= currentTime; i++)
  168. {
  169. if (i == 0)
  170. {
  171. var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  172. dayYear += dd;
  173. //weeks.Add(i, bsum);
  174. weeks.Add(bsum);
  175. }
  176. else
  177. {
  178. var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  179. dayYear += 7;
  180. //weeks.Add(i, bsum);
  181. weeks.Add(bsum);
  182. }
  183. }
  184. }
  185. //最后一周是否有余
  186. int stary = days - dayYear;
  187. if (stary > 0 && stary < 7)
  188. {
  189. var bsum = bmatrix.SubMatrix(dayYear, stary - 1, 0, bmatrix.ColumnCount).ColumnSums().Sum();
  190. //weeks.Add((sweeks + 1), bsum);
  191. weeks.Add(bsum);
  192. }
  193. }
  194. return Ok(new { state = 200, weeks });
  195. }
  196. /// <summary>
  197. /// 统计所有区级的课例和活动 //已对接
  198. /// </summary>
  199. /// <returns></returns>
  200. [ProducesDefaultResponseType]
  201. [HttpPost("get-allarea")]
  202. public async Task<IActionResult> GetAllArea(JsonElement jsonElement)
  203. {
  204. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  205. var cosmosClient = _azureCosmos.GetCosmosClient();
  206. //if ($"{site}".Equals(BIConst.Global))
  207. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  208. List<AllAreaInfo> areaInfos = new();
  209. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<AllAreaInfo>(queryText: $"select c.id,c.name,c.standard,c.standardName from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  210. {
  211. areaInfos.Add(item);
  212. }
  213. foreach (var area in areaInfos)
  214. {
  215. string comSql = $"select value(c.id) from c where c.areaId='{area.id}'";
  216. List<string> scIds = await CommonFind.GetValueSingle(cosmosClient, "School", comSql, "Base");
  217. int tLessCnt = 0;
  218. int tActCnt = 0;
  219. string Sql = $"select value(c.id) from c where c.areaId='{area.id}'";
  220. if (scIds.Count > 0)
  221. {
  222. comSql = BICommonWay.ManyScSql("c.school", scIds);
  223. string lesSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {comSql}";
  224. tLessCnt = await CommonFind.GetSqlValueCount(cosmosClient, new List<string>() { "School", "Teacher" }, lesSql);
  225. comSql = BICommonWay.ManyScSql(" and c.school", scIds);
  226. tActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: comSql);
  227. }
  228. area.lessCnt = tLessCnt;
  229. area.actCnt = tActCnt;
  230. area.allCnt = tLessCnt + tActCnt;
  231. }
  232. areaInfos = areaInfos.Where(w => w.lessCnt != 0 && w.actCnt != 0).ToList();
  233. return Ok(new { state = 200, areaInfos = areaInfos.OrderByDescending(ob => ob.allCnt).ToList() });
  234. }
  235. /// <summary>
  236. /// 查询课例数量
  237. /// </summary>
  238. /// <param name="jsonElement"></param>
  239. /// <returns></returns>
  240. [ProducesDefaultResponseType]
  241. [HttpPost("get-count")]
  242. public async Task<IActionResult> GetCount(JsonElement jsonElement)
  243. {
  244. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  245. if (!jsonElement.TryGetProperty("term", out JsonElement term)) return BadRequest();
  246. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  247. var cosmosClient = _azureCosmos.GetCosmosClient();
  248. //if ($"{site}".Equals(BIConst.Global))
  249. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  250. var (start, end) = TimeHelper.GetTermStartOrEnd(DateTime.Now);
  251. object totals = new();
  252. StringBuilder sqlTxt = new($"select value(COUNT(c.id)) from c where c.pk='LessonRecord'");
  253. if (!string.IsNullOrEmpty($"{tmdId}"))
  254. {
  255. List<SchoolLen> schoolLens = new();
  256. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  257. foreach (var itemId in schoolIds)
  258. {
  259. School school = new();
  260. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
  261. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  262. {
  263. using var json = await JsonDocument.ParseAsync(response.Content);
  264. school = json.ToObject<School>();
  265. }
  266. SchoolLen schoolLen = new()
  267. {
  268. id = itemId,
  269. name =
  270. school.name != null ? school.name : itemId
  271. };
  272. //string sqlTxt = $"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'";
  273. sqlTxt.Append($" WHERE c.code='LessonRecord-{itemId}'");
  274. if (bool.Parse($"{term}") == true)
  275. {
  276. sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
  277. }
  278. schoolLen.totals = await CommonFind.GetSqlValueCount(cosmosClient, "School", sqlTxt.ToString());
  279. schoolLens.Add(schoolLen);
  280. }
  281. totals = schoolLens;
  282. }
  283. else
  284. {
  285. sqlTxt.Append($" where c.pk='LessonRecord'");
  286. if (bool.Parse($"{term}") == true)
  287. {
  288. sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
  289. }
  290. totals = await CommonFind.GetSqlValueCount(cosmosClient, new List<string>() { "School", "Teacher" }, sqlTxt.ToString());
  291. }
  292. return Ok(new { state = 200, totals });
  293. }
  294. /// <summary>
  295. /// 管家所关联的课例数据
  296. /// </summary>
  297. /// <param name="jsonElement"></param>
  298. /// <returns></returns>
  299. [ProducesDefaultResponseType]
  300. [HttpPost("get-assiist")]
  301. public async Task<IActionResult> GetAssiist(JsonElement jsonElement)
  302. {
  303. try
  304. {
  305. if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
  306. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  307. var cosmosClient = _azureCosmos.GetCosmosClient();
  308. ////分开部署,就不需要,一站多用时,取消注释
  309. //if ($"{site}".Equals(BIConst.Global))
  310. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  311. List<SchoolLen> schoolLens = new();
  312. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  313. foreach (var itemId in schoolIds)
  314. {
  315. School school = new();
  316. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
  317. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  318. {
  319. using var json = await JsonDocument.ParseAsync(response.Content);
  320. school = json.ToObject<School>();
  321. }
  322. SchoolLen schoolLen = new() { id = itemId, name = school != null ? school.name : itemId };
  323. string sqlTxt = $"SELECT value(COUNT(c.id)) FROM c WHERE c.code='LessonRecord-{itemId}'";
  324. schoolLen.totals = await CommonFind.GetSqlValueCount(cosmosClient, "School", sqlTxt);
  325. schoolLens.Add(schoolLen);
  326. }
  327. return Ok(new { state = 200, schoolLens });
  328. }
  329. catch (Exception ex)
  330. {
  331. await _dingDing.SendBotMsg($"BI, {_option.Location} /lesson/get-assiist {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  332. return BadRequest();
  333. }
  334. }
  335. /// <summary>
  336. /// 统计所有的课例数据
  337. /// </summary>
  338. /// <returns></returns>
  339. [ProducesDefaultResponseType]
  340. [HttpPost("get-diccount")]
  341. public async Task<IActionResult> GetDicCount(JsonElement jsonElement)
  342. {
  343. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  344. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  345. var cosmosClient = _azureCosmos.GetCosmosClient();
  346. ////分开部署,就不需要,一站多用时,取消注释
  347. //if ($"{site}".Equals(BIConst.Global))
  348. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  349. if (!string.IsNullOrEmpty($"{tmdId}"))
  350. {
  351. jsonElement.TryGetProperty("years", out JsonElement _years);
  352. int years = DateTime.UtcNow.Year;
  353. if (!string.IsNullOrEmpty($"{_years}"))
  354. {
  355. years = _years.GetInt32();
  356. }
  357. List<SchoolLen> schoolLens = new();
  358. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  359. foreach (string schoolId in schoolIds)
  360. {
  361. School school = new();
  362. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
  363. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  364. {
  365. using var json = await JsonDocument.ParseAsync(response.Content);
  366. school = json.ToObject<School>();
  367. }
  368. SchoolLen schoolLen = new() { id = schoolId, name = school != null ? school.name : schoolId };
  369. List<List<double>> begin = new();
  370. await foreach (var lcount in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<LessonCount>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{schoolId}-{years}") }))
  371. {
  372. begin.Add(lcount.beginCount);
  373. }
  374. schoolLen.totals = (long)DenseMatrix.OfColumns(begin).ColumnSums().Sum();
  375. schoolLens.Add(schoolLen);
  376. }
  377. return Ok(new { state = 200, schoolLens });
  378. }
  379. else
  380. {
  381. List<List<double>> begin = new();
  382. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIteratorSql<LessonCount>(queryText: "select value(c) from c where c.pk='LessonCount'", requestOptions: new QueryRequestOptions() { }))
  383. {
  384. begin.Add(item.beginCount);
  385. }
  386. var count = DenseMatrix.OfColumns(begin).ColumnSums().Sum();
  387. return Ok(new { state = 200, count });
  388. }
  389. }
  390. /// <summary>
  391. /// 顾问关联的学校统计本学期的课例
  392. /// </summary>
  393. /// <param name="jsonElement"></param>
  394. /// <returns></returns>
  395. [HttpPost("get-termcount")]
  396. public async Task<IActionResult> GetTermCount(JsonElement jsonElement)
  397. {
  398. if (jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) BadRequest();
  399. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  400. var cosmosClient = _azureCosmos.GetCosmosClient();
  401. ////分开部署,就不需要,一站多用时,取消注释
  402. //if ($"{site}".Equals(BIConst.Global))
  403. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  404. List<SchoolLen> schoolLens = new();
  405. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
  406. foreach (var scid in schoolIds)
  407. {
  408. School school = new();
  409. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(scid, new PartitionKey("Base"));
  410. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  411. {
  412. using var json = await JsonDocument.ParseAsync(response.Content);
  413. school = json.ToObject<School>();
  414. }
  415. SchoolLen schoolLen = new() { id = scid, name = !string.IsNullOrEmpty(school.name) ? school.name : scid };
  416. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  417. int year = (dateTime.Month <= 8 && dateTime.Month >= 3) ? dateTime.Year : dateTime.Year - 1;
  418. long stime = DateTimeOffset.Parse($"{year}-9-1").ToUnixTimeMilliseconds();
  419. //long etime = DateTimeOffset.Parse($"{year}-2-{((year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 29 : 28)}").ToUnixTimeMilliseconds();
  420. double totals = 0;
  421. var syear = DateTimeOffset.FromUnixTimeMilliseconds(stime).Year;
  422. var tyear = DateTimeOffset.UtcNow.Year;
  423. var tday = DateTimeOffset.UtcNow.DayOfYear;
  424. //今年多少天
  425. int tdays = (tyear % 4 == 0 && tyear % 100 != 0 || tyear % 400 == 0) ? 366 : 365;
  426. //去年多少天
  427. int pydays = (syear % 4 == 0 && syear % 100 != 0 || syear % 400 == 0) ? 366 : 365;
  428. List<LessonCount> scount = new();
  429. List<LessonCount> tcount = new();
  430. DenseMatrix dense = null;
  431. var queryClass = $"select value(c) from c ";
  432. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonCount>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{syear}") }))
  433. {
  434. scount.Add(item);
  435. }
  436. if (tyear > syear)
  437. {
  438. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonCount>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{tyear}") }))
  439. {
  440. tcount.Add(item);
  441. }
  442. if (tcount.Count > 0)
  443. {
  444. List<List<double>> be = new();
  445. foreach (var item in tcount)
  446. {
  447. be.Add(item.beginCount);
  448. }
  449. dense = DenseMatrix.OfColumns(be);
  450. }
  451. }
  452. if (scount.Count > 0)
  453. {
  454. List<List<double>> begin = new();
  455. foreach (LessonCount lesson in scount)
  456. {
  457. begin.Add(lesson.beginCount);
  458. }
  459. var matrix = DenseMatrix.OfColumns(begin);
  460. //求本学期
  461. var sdays = DateTimeOffset.FromUnixTimeMilliseconds(stime).DayOfYear;
  462. if (tday - sdays < 0)
  463. {
  464. //var tmatrix = DenseMatrix.OfColumns(scount.beginCount);
  465. //跨年后开始到本学期结束
  466. double endMonth = 0;
  467. if (null != dense)
  468. {
  469. endMonth = dense.SubMatrix(0, tday, 0, dense.ColumnCount).ColumnSums().Sum();
  470. }
  471. var startMonth = matrix.SubMatrix(sdays - 1, pydays - sdays, 0, matrix.ColumnCount).ColumnSums().Sum();
  472. totals = (endMonth + startMonth);
  473. }
  474. else
  475. {
  476. var allMonth = matrix.SubMatrix(sdays - 1, tday - sdays + 1, 0, matrix.ColumnCount).ColumnSums().Sum();
  477. totals = allMonth;
  478. }
  479. }
  480. schoolLen.totals = (long)totals;
  481. schoolLens.Add(schoolLen);
  482. }
  483. return Ok(new { state = 200, schoolLens });
  484. }
  485. /// <summary>
  486. /// 统计区级课例
  487. /// </summary>
  488. /// <param name="jsonElement"></param>
  489. /// <returns></returns>
  490. [ProducesDefaultResponseType]
  491. [HttpPost("get-areacount")]
  492. public async Task<IActionResult> GetAreaCount(JsonElement jsonElement)
  493. {
  494. if(!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  495. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  496. List<string> schools = new();
  497. var cosmosClient = _azureCosmos.GetCosmosClient();
  498. ////分开部署,就不需要,一站多用时,取消注释
  499. //if ($"{site}".Equals(BIConst.Global))
  500. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  501. StringBuilder scSqlTxt = new("select value(c.id) from c");
  502. if (!string.IsNullOrEmpty($"{areaId}"))
  503. {
  504. scSqlTxt.Append($" where c.areaId='{areaId}'");
  505. }
  506. schools = await CommonFind.FindScIds(cosmosClient, scSqlTxt.ToString(), "Base");
  507. //所有的课程记录
  508. List<LessonRecord> records = new();
  509. List<string> tecIds = new();
  510. foreach (var school in schools)
  511. {
  512. string sqlTxt = $"select value(c) from c where c.code='LessonRecord-{school}'";
  513. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonRecord>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
  514. {
  515. records.Add(item);
  516. }
  517. }
  518. tecIds = await CommonFind.FindRolesId(cosmosClient, schools);
  519. foreach (var tecId in tecIds)
  520. {
  521. string sqlTxt = $"select value(c) from c where c.id='{tecId}'";
  522. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<LessonRecord>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord") }))
  523. {
  524. records.Add(item);
  525. }
  526. }
  527. int dayCount = 0;
  528. var (dayStart, dayEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
  529. records.ForEach(x => { if (x.startTime >= dayStart && x.startTime <= dayEnd) dayCount += 1; });
  530. int weekCount = 0;
  531. var (weekStart, weekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
  532. records.ForEach(x => { if (x.startTime >= weekStart && x.startTime <= weekEnd) weekCount += 1; });
  533. int monthCount = 0;
  534. var (monthStart, monthEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
  535. records.ForEach(x => { if (x.startTime >= monthStart && x.startTime <= monthEnd) monthCount += 1; });
  536. int termCount = 0;
  537. var (termStart, termEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
  538. records.ForEach(x => { if (x.startTime >= termStart && x.startTime <= termEnd) termCount += 1; });
  539. double teachCount = records.Where(r => r.tmdid != null).Where((x, i) => records.FindIndex(z => z.tmdid == x.tmdid) == i).ToList().Count;
  540. return Ok(new { state = 200, lessonCount = records.Count, teachCount, dayCount, weekCount, monthCount, termCount });
  541. }
  542. /// <summary>
  543. /// 依据课例Id获取课例详情 数据管理工具——查询工具
  544. /// </summary>
  545. /// <param name="jsonElement"></param>
  546. /// <returns></returns>
  547. [ProducesDefaultResponseType]
  548. [HttpPost("get-info")]
  549. public async Task<IActionResult> GetInfo(JsonElement jsonElement)
  550. {
  551. if (!jsonElement.TryGetProperty("lessonId", out JsonElement lessonId)) return BadRequest();
  552. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  553. var cosmosClient = _azureCosmos.GetCosmosClient();
  554. ////分开部署,就不需要,一站多用时,取消注释
  555. //if ($"{site}".Equals(BIConst.Global))
  556. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  557. List<object> lessons = new();
  558. string sqlTxt = $"select * from c where c.id='{lessonId}'";
  559. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIteratorSql(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { }))
  560. {
  561. using var json = await JsonDocument.ParseAsync(item.Content);
  562. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  563. {
  564. lessons.Add(obj.ToObject<object>());
  565. }
  566. }
  567. return Ok(new { state = 200, lessons });
  568. }
  569. /// <summary>
  570. /// 获取课例统计数据
  571. /// </summary>
  572. /// <param name="jsonElement"></param>
  573. /// <returns></returns>
  574. [ProducesDefaultResponseType]
  575. [HttpPost("get-less")]
  576. public async Task<IActionResult> GetLess(JsonElement jsonElement)
  577. {
  578. if (!jsonElement.TryGetProperty("school", out JsonElement school)) return BadRequest();
  579. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIStats");
  580. var tableSql = $" PartitionKey eq 'LessonHour' and school eq '{school}'";
  581. //lambda 表达式排序
  582. var lessStats = await table.QueryWhereString<LessStats>(tableSql.ToString());
  583. DenseMatrix openDense = null;
  584. DenseMatrix lessDense = null;
  585. List<List<double>> tempOpens = new();
  586. List<List<double>> tempLesss = new();
  587. foreach (var item in lessStats)
  588. {
  589. if (item.open != null)
  590. {
  591. List<double> opens = item.open.Split(',').ToList().ConvertAll(c => Convert.ToDouble(c));
  592. tempOpens.Add(opens);
  593. }
  594. if (item.lesson != null)
  595. {
  596. List<double> lesss = item.lesson.Split(',').ToList().ConvertAll(c => Convert.ToDouble(c));
  597. tempLesss.Add(lesss);
  598. }
  599. }
  600. openDense = DenseMatrix.OfColumns(tempOpens);
  601. lessDense = DenseMatrix.OfColumns(tempLesss);
  602. return Ok(new { state = 200, openDense, lessDense });
  603. }
  604. /// <summary>
  605. /// 测试 通过时间戳保存统计类型接口
  606. /// </summary>
  607. /// <param name="jsonElement"></param>
  608. /// <returns></returns>
  609. [ProducesDefaultResponseType]
  610. [HttpPost("set-bilessonstats")]
  611. public async Task<IActionResult> SetBILeesonStats(JsonElement jsonElement)
  612. {
  613. if (!jsonElement.TryGetProperty("unix", out JsonElement unix)) return BadRequest();
  614. if (!jsonElement.TryGetProperty("num", out JsonElement num)) return BadRequest();
  615. jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
  616. jsonElement.TryGetProperty("type", out JsonElement type);
  617. jsonElement.TryGetProperty("unixs", out JsonElement unixs);
  618. var cosmosClient = _azureCosmos.GetCosmosClient();
  619. DateTime expireYear = DateTime.UtcNow.AddYears(1); //一个月到期
  620. var UUID = Guid.NewGuid().ToString();
  621. List<long> unixsT = unixs.ToObject<List<long>>();
  622. RedisValue token = Environment.MachineName;
  623. foreach (var item in unixsT)
  624. {
  625. //await SetBILeesonStats(cosmosClient, item, num.GetInt32(), type: type.GetInt32(), schoolId: schoolId.GetString());
  626. //await BILeeson.SetCosmosDBStats(cosmosClient, _azureRedis, _dingDing, item, num.GetInt32(), type: type.GetInt32(), schoolId: schoolId.GetString());
  627. await BILeesonService.SetTableStats(_azureStorage, _azureRedis, _dingDing, item, num.GetInt32(), type: type.GetInt32(), "school", schoolId: schoolId.GetString());
  628. }
  629. //await BILeeson.SetBILeesonStats(cosmosClient, _azureRedis, unix.GetInt64(), num.GetInt32(), type: type.GetInt32(), schoolId: schoolId.GetString());
  630. //await SetBILeesonStats(cosmosClient, unix.GetInt64(), num.GetInt32(), type: -1, schoolId: schoolId.GetString());
  631. return Ok(new { state = 200 });
  632. }
  633. /// <summary>
  634. /// 通过时间戳保存统计类型
  635. /// </summary>
  636. /// <param name="cosmosClient">连接字符串</param>
  637. /// <param name="unix">时间戳</param>
  638. /// <param name="num">加减数量,可为负数</param>
  639. /// <param name="type">课例类型,0开课 1 课例</param>
  640. /// <param name="schoolId">学校ID,可不传</param>
  641. /// <returns></returns>
  642. public static async Task SetBILeesonStats(CosmosClient cosmosClient, long unix, int num, int type = 0, string schoolId = null)
  643. {
  644. //Monitor.TryEnter(unix); //锁对象
  645. SemaphoreSlim slimlock = new(1, 1); //对可同时访问资源或资源池的线程数加以限制
  646. await slimlock.WaitAsync();
  647. DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeMilliseconds(unix);
  648. int year, month, day, hour, days;
  649. year = dateTime.Year;
  650. month = dateTime.Month;
  651. day = dateTime.Day;
  652. hour = dateTime.Hour;
  653. string hourId = $"{year}{month.ToString().PadLeft(2, '0')}{day.ToString().PadLeft(2, '0')}";
  654. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  655. days = dateTime.DayOfYear;
  656. double[] daDays = new double[yearDays];
  657. daDays[days] = num;
  658. List<double> yDays = new(daDays);
  659. double[] daHours = new double[23];
  660. daHours[hour] = num;
  661. List<double> yHours = new(daHours);
  662. var openRes = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{year}", new PartitionKey("LessonYear"));
  663. if (openRes.StatusCode == System.Net.HttpStatusCode.OK)
  664. {
  665. using var json = await JsonDocument.ParseAsync(openRes.Content);
  666. LessonStats lessonYear = json.ToObject<LessonStats>();
  667. if (type == 0)
  668. {
  669. if (lessonYear.open.Count == 0)
  670. lessonYear.open = yDays;
  671. else lessonYear.open[days] = lessonYear.open[days] + num;
  672. }
  673. else if (type == 1)
  674. {
  675. if (lessonYear.lesson.Count == 0)
  676. lessonYear.lesson = yDays;
  677. else lessonYear.lesson[days] = lessonYear.lesson[days] + num;
  678. }
  679. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonYear, lessonYear.id, new PartitionKey($"{lessonYear.code}"));
  680. }
  681. else
  682. {
  683. LessonStats lessonYear = new();
  684. lessonYear.id = $"{year}";
  685. lessonYear.code = "LessonYear";
  686. lessonYear.pk = "LessonYear";
  687. if (type == 0)
  688. lessonYear.open = yDays;
  689. else if (type == 1)
  690. lessonYear.lesson = yDays;
  691. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(lessonYear, new PartitionKey($"{lessonYear.code}"));
  692. }
  693. var lessRes = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{hourId}", new PartitionKey("LessonHour"));
  694. if (lessRes.StatusCode == System.Net.HttpStatusCode.OK)
  695. {
  696. using var json = await JsonDocument.ParseAsync(lessRes.Content);
  697. LessonStats lessonHour = json.ToObject<LessonStats>();
  698. if (type == 0)
  699. {
  700. if (lessonHour.open.Count == 0)
  701. lessonHour.open = yHours;
  702. else lessonHour.open[hour] = lessonHour.open[hour] + num;
  703. }
  704. else if (type == 1)
  705. {
  706. if (lessonHour.lesson.Count == 0)
  707. lessonHour.lesson = yHours;
  708. else lessonHour.lesson[hour] = lessonHour.lesson[hour] + num;
  709. }
  710. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonHour, lessonHour.id, new PartitionKey($"LessonHour"));
  711. }
  712. else
  713. {
  714. LessonStats lessonHour = new();
  715. lessonHour.id = $"{hourId}";
  716. lessonHour.code = "LessonHour";
  717. lessonHour.pk = "LessonHour";
  718. if (type == 0)
  719. lessonHour.open = yDays;
  720. else if (type == 1)
  721. lessonHour.lesson = yDays;
  722. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(lessonHour, new PartitionKey("LessonHour"));
  723. }
  724. //学校统计
  725. if (!string.IsNullOrEmpty(schoolId))
  726. {
  727. var openResSc = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{year}", new PartitionKey($"LessonYear-{schoolId}"));
  728. if (openResSc.StatusCode == System.Net.HttpStatusCode.OK)
  729. {
  730. using var jsonSc = await JsonDocument.ParseAsync(openResSc.Content);
  731. LessonStats lessonYearSc = jsonSc.ToObject<LessonStats>();
  732. if (type == 0)
  733. if (lessonYearSc.open.Count == 0)
  734. lessonYearSc.open = yDays;
  735. else lessonYearSc.open[days] = lessonYearSc.open[days] + num;
  736. else if (type == 1)
  737. {
  738. if (lessonYearSc.lesson.Count == 0)
  739. lessonYearSc.lesson = yDays;
  740. else lessonYearSc.lesson[days] = lessonYearSc.lesson[days] + num;
  741. }
  742. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonYearSc, lessonYearSc.id, new PartitionKey($"LessonYear-{schoolId}"));
  743. }
  744. else
  745. {
  746. LessonStats lessonYearSc = new();
  747. lessonYearSc.id = $"{year}";
  748. lessonYearSc.code = $"LessonYear-{schoolId}";
  749. lessonYearSc.pk = "LessonYear";
  750. if (type == 0)
  751. lessonYearSc.open = yDays;
  752. else if (type == 1)
  753. lessonYearSc.lesson = yDays;
  754. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(lessonYearSc, new PartitionKey($"LessonYear-{schoolId}"));
  755. }
  756. var lessResSc = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{hourId}", new PartitionKey($"LessonHour-{schoolId}"));
  757. if (lessResSc.StatusCode == System.Net.HttpStatusCode.OK)
  758. {
  759. using var jsonSc = await JsonDocument.ParseAsync(lessResSc.Content);
  760. LessonStats lessonHourSc = jsonSc.ToObject<LessonStats>();
  761. if (type == 0)
  762. if (lessonHourSc.open.Count == 0)
  763. lessonHourSc.open = yDays;
  764. else lessonHourSc.open[days] = lessonHourSc.open[days] + num;
  765. else if (type == 1)
  766. {
  767. if (lessonHourSc.lesson.Count == 0)
  768. lessonHourSc.lesson = yHours;
  769. else lessonHourSc.lesson[hour] = lessonHourSc.lesson[hour] + num;
  770. }
  771. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonHourSc, lessonHourSc.id, new PartitionKey($"LessonHour-{schoolId}"));
  772. }
  773. else
  774. {
  775. LessonStats lessonYearSc = new();
  776. lessonYearSc.id = $"{hourId}";
  777. lessonYearSc.code = $"LessonHour-{schoolId}";
  778. lessonYearSc.pk = "LessonHour";
  779. if (type == 0)
  780. lessonYearSc.open = yHours;
  781. else if (type == 1)
  782. lessonYearSc.lesson = yHours;
  783. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(lessonYearSc, new PartitionKey($"LessonHour-{schoolId}"));
  784. }
  785. }
  786. slimlock.Release();
  787. //Monitor.Enter(unix);
  788. }
  789. /// <summary>
  790. /// 历史记录读取,并统计存储
  791. /// </summary>
  792. /// <param name="jsonElement"></param>
  793. /// <returns></returns>
  794. [ProducesDefaultResponseType]
  795. [HttpPost("get-alllesson")]
  796. public async Task<IActionResult> GetAllLessonRecords(JsonElement jsonElement)
  797. {
  798. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  799. var cosmosClient = _azureCosmos.GetCosmosClient();
  800. ////分开部署,就不需要,一站多用时,取消注释
  801. //if ($"{site}".Equals(BIConst.Global))
  802. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  803. List<LessonRecord> allLesson = new();
  804. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<LessonRecord>(queryText: $"select value(c) from c where c.pk='LessonRecord'", requestOptions: new QueryRequestOptions() { }))
  805. {
  806. allLesson.Add(item);
  807. }
  808. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<LessonRecord>(queryText: $"select value(c) from c where c.pk='LessonRecord'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("LessonRecord") }))
  809. {
  810. allLesson.Add(item);
  811. }
  812. (List<LessonStats> lessYears, List<LessonStats> lessHours) = await AllLessonStats(allLesson, _azureRedis);
  813. foreach (var itemY in lessYears)
  814. {
  815. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemY.id, new PartitionKey($"{itemY.code}"));
  816. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  817. {
  818. using var json = await JsonDocument.ParseAsync(response.Content);
  819. LessonStats lessonYear = json.ToObject<LessonStats>();
  820. lessonYear.open = itemY.open;
  821. lessonYear.lesson = itemY.lesson;
  822. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonYear, lessonYear.id, new PartitionKey($"{lessonYear.code}"));
  823. }
  824. else
  825. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(itemY, new PartitionKey($"{itemY.code}"));
  826. }
  827. foreach (var itemH in lessHours)
  828. {
  829. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemH.id, new PartitionKey($"{itemH.code}"));
  830. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  831. {
  832. using var json = await JsonDocument.ParseAsync(response.Content);
  833. LessonStats lessonHour = json.ToObject<LessonStats>();
  834. lessonHour.open = itemH.open;
  835. lessonHour.lesson = itemH.lesson;
  836. await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<LessonStats>(lessonHour, lessonHour.id, new PartitionKey($"{lessonHour.code}"));
  837. }
  838. else
  839. await cosmosClient.GetContainer("TEAMModelOS", "School").CreateItemAsync<LessonStats>(itemH, new PartitionKey($"{itemH.code}"));
  840. }
  841. return Ok(new { state = 200, ycnt = lessYears.Count, hcnt = lessHours.Count, lessYears, lessHours });
  842. }
  843. #region 课例历史记录统计
  844. /// <summary>
  845. /// 统计所有课例
  846. /// </summary>
  847. /// <param name="lessRecs"></param>
  848. /// <returns></returns>
  849. public static async Task<(List<LessonStats> lessonYears, List<LessonStats> lessonHours)> AllLessonStats(List<LessonRecord> lessRecs, AzureRedisFactory azureRedis)
  850. {
  851. //统计所有
  852. List<LessCnt> allLess = lessRecs.Select(item => new LessCnt { hour = TimeHelper.GetDateTime(item.startTime).ToString("yyyyMMddHH"), cat = item.id, upload = item.upload, schoolId = item.school }).ToList();
  853. var openL = allLess.FindAll(f => f.upload == 0).GroupBy(g => g.hour).Select(s => new AllLess { key = s.Key, cnt = s.Count() }).ToList();
  854. var lessL = allLess.FindAll(s => s.upload == 1).GroupBy(g => g.hour).Select(s => new AllLess { key = s.Key, cnt = s.Count() }).ToList();
  855. List<LessonStats> lessYears = new();
  856. List<LessonStats> lessHours = new();
  857. //统计开课记录
  858. openL.ForEach(x =>
  859. {
  860. var (year, month, day, days, hour) = TimeHelper.GetDateTime(x.key);
  861. string id = $"{year}{month.ToString().PadLeft(2, '0')}{day.ToString().PadLeft(2, '0')}";
  862. LessonStats finHour = lessHours.Find(f => f.id.Equals(id));
  863. if (finHour != null)
  864. {
  865. if (finHour.open.Count == 0)
  866. {
  867. double[] da = new double[23];
  868. da[hour] = x.cnt;
  869. List<double> tempDays = new(da);
  870. finHour.open = tempDays;
  871. }
  872. else finHour.open[hour] = x.cnt;
  873. azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"BILesson:All:Open:{finHour.id}", $"{hour}", x.cnt);//一天24小时课例数 有上传 base.josn 小时为单位
  874. }
  875. else
  876. {
  877. //小时统计
  878. LessonStats lessonHour = new();
  879. lessonHour.id = id;
  880. lessonHour.code = "LessonHour";
  881. lessonHour.pk = "LessonHour";
  882. double[] daHours = new double[23];
  883. daHours[hour] = x.cnt;
  884. List<double> hourDays = new(daHours);
  885. lessonHour.open = hourDays;
  886. //lessonHour.ttl = 24 * 60 * 60 * 8; //设置过期时间 8天后自动删除
  887. lessHours.Add(lessonHour);
  888. }
  889. LessonStats findLess = lessYears.Find(f => f.id.Equals($"{year}"));
  890. if (findLess != null)
  891. {
  892. if (findLess.open.Count == 0)
  893. {
  894. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  895. double[] da = new double[yearDays];
  896. da[days] = x.cnt;
  897. List<double> tempDays = new(da);
  898. findLess.open = tempDays;
  899. }
  900. else findLess.open[days] = x.cnt;
  901. }
  902. else
  903. {
  904. LessonStats lessonYear = new();
  905. lessonYear.id = $"{year}";
  906. lessonYear.code = "LessonYear";
  907. lessonYear.pk = "LessonYear";
  908. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  909. double[] daDays = new double[yearDays];
  910. daDays[days] = x.cnt;
  911. List<double> yDays = new(daDays);
  912. lessonYear.open = yDays;
  913. lessYears.Add(lessonYear);
  914. }
  915. });
  916. //统计课例
  917. lessL.ForEach(x =>
  918. {
  919. var (year, month, day, days, hour) = TimeHelper.GetDateTime(x.key);
  920. string id = $"{year}{month.ToString().PadLeft(2, '0')}{day.ToString().PadLeft(2, '0')}";
  921. LessonStats finHour = lessHours.Find(f => f.id.Equals(id));
  922. if (finHour != null)
  923. {
  924. if (finHour.lesson.Count == 0)
  925. {
  926. double[] da = new double[23];
  927. da[hour] = x.cnt;
  928. List<double> tempDays = new(da);
  929. finHour.lesson = tempDays;
  930. }
  931. else finHour.lesson[hour] = x.cnt;
  932. }
  933. else
  934. {
  935. //小时统计
  936. LessonStats lessonHour = new();
  937. lessonHour.id = id;
  938. lessonHour.code = "LessonHour";
  939. lessonHour.pk = "LessonHour";
  940. double[] daHours = new double[23];
  941. daHours[hour] = x.cnt;
  942. List<double> hourDays = new(daHours);
  943. lessonHour.lesson = hourDays;
  944. lessHours.Add(lessonHour);
  945. }
  946. LessonStats findLess = lessYears.Find(f => f.id.Equals($"{year}"));
  947. if (findLess != null)
  948. {
  949. if (findLess.lesson.Count == 0)
  950. {
  951. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  952. double[] da = new double[yearDays];
  953. da[days] = x.cnt;
  954. List<double> tempDays = new(da);
  955. findLess.lesson = tempDays;
  956. }
  957. else findLess.lesson[days] = x.cnt;
  958. }
  959. else
  960. {
  961. LessonStats lessonYear = new();
  962. lessonYear.id = $"{year}";
  963. lessonYear.code = "LessonYear";
  964. lessonYear.pk = "LessonYear";
  965. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  966. double[] da = new double[yearDays];
  967. da[days] = x.cnt;
  968. List<double> tempDays = new(da);
  969. lessonYear.lesson = tempDays;
  970. lessYears.Add(lessonYear);
  971. }
  972. });
  973. //统计学校课例
  974. var scLess = lessRecs.Select(item => new LessCnt { hour = TimeHelper.GetDateTime(item.startTime).ToString("yyyyMMddHH"), cat = item.id, upload = item.upload, schoolId = item.school }).GroupBy(g => g.schoolId).Select(s => new ScLess { key = s.Key, lessCnt = s.ToList() }).ToList();
  975. foreach (var itemLess in scLess)
  976. {
  977. var openSCL = itemLess.lessCnt.FindAll(f => f.upload == 0).GroupBy(g => g.hour).Select(s => new ScLesson { key = s.Key, schoolId = itemLess.key, cnt = s.Count() }).ToList();
  978. var lessSCL = itemLess.lessCnt.FindAll(f => f.upload == 1).GroupBy(g => g.hour).Select(s => new ScLesson { key = s.Key, schoolId = itemLess.key, cnt = s.Count() }).ToList();
  979. openSCL.ForEach(f =>
  980. {
  981. if (!string.IsNullOrEmpty(f.schoolId))
  982. {
  983. var (year, month, day, days, hour) = TimeHelper.GetDateTime(f.key);
  984. string id = $"{year}{month.ToString().PadLeft(2, '0')}{day.ToString().PadLeft(2, '0')}";
  985. string codeHour = $"LessonHour-{f.schoolId}";
  986. LessonStats finHour = lessHours.Find(f => f.id.Equals(id) && f.code.Equals(codeHour));
  987. if (finHour != null)
  988. {
  989. if (finHour.open.Count == 0)
  990. {
  991. double[] da = new double[23];
  992. da[hour] = f.cnt;
  993. List<double> tempDays = new(da);
  994. finHour.open = tempDays;
  995. }
  996. else finHour.open[hour] = f.cnt;
  997. }
  998. else
  999. {
  1000. //小时统计
  1001. LessonStats lessonHour = new();
  1002. lessonHour.id = id;
  1003. lessonHour.code = codeHour;
  1004. lessonHour.pk = "LessonHour";
  1005. double[] daHours = new double[23];
  1006. daHours[hour] = f.cnt;
  1007. List<double> hourDays = new(daHours);
  1008. lessonHour.open = hourDays;
  1009. //lessonHour.ttl = 24 * 60 * 60 * 8; //设置过期时间
  1010. lessHours.Add(lessonHour);
  1011. }
  1012. string codeYear = $"LessonYear-{f.schoolId}";
  1013. LessonStats findLess = lessYears.Find(f => f.id.Equals($"{year}") && f.code.Equals(codeYear));
  1014. if (findLess != null)
  1015. {
  1016. if (findLess.open.Count == 0)
  1017. {
  1018. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1019. double[] da = new double[yearDays];
  1020. da[days] = f.cnt;
  1021. List<double> tempDays = new(da);
  1022. findLess.open = tempDays;
  1023. }
  1024. else findLess.open[days] = f.cnt;
  1025. }
  1026. else
  1027. {
  1028. LessonStats lessonYear = new();
  1029. lessonYear.id = $"{year}";
  1030. lessonYear.code = codeYear;
  1031. lessonYear.code = "LessonYear";
  1032. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1033. double[] daDays = new double[yearDays];
  1034. daDays[days] = f.cnt;
  1035. List<double> yDays = new(daDays);
  1036. lessonYear.open = yDays;
  1037. lessYears.Add(lessonYear);
  1038. }
  1039. }
  1040. });
  1041. lessSCL.ForEach(x =>
  1042. {
  1043. if (!string.IsNullOrEmpty(x.schoolId))
  1044. {
  1045. if (!string.IsNullOrEmpty(x.schoolId))
  1046. {
  1047. var (year, month, day, days, hour) = TimeHelper.GetDateTime(x.key);
  1048. string id = $"{year}{month.ToString().PadLeft(2, '0')}{day.ToString().PadLeft(2, '0')}";
  1049. string codeHour = $"LessonHour-{x.schoolId}";
  1050. LessonStats finHour = lessHours.Find(f => f.id.Equals(id) && f.code.Equals(codeHour));
  1051. if (finHour != null)
  1052. {
  1053. if (finHour.lesson.Count == 0)
  1054. {
  1055. double[] da = new double[23];
  1056. da[hour] = x.cnt;
  1057. List<double> tempDays = new(da);
  1058. finHour.lesson = tempDays;
  1059. }
  1060. else finHour.lesson[hour] = x.cnt;
  1061. }
  1062. else
  1063. {
  1064. //小时统计
  1065. LessonStats lessonHour = new();
  1066. lessonHour.id = id;
  1067. lessonHour.code = codeHour;
  1068. lessonHour.pk = "LessonHour";
  1069. double[] daHours = new double[23];
  1070. daHours[hour] = x.cnt;
  1071. List<double> hourDays = new(daHours);
  1072. lessonHour.lesson = hourDays;
  1073. lessHours.Add(lessonHour);
  1074. }
  1075. string codeYear = $"LessonYear-{x.schoolId}";
  1076. LessonStats findLess = lessYears.Find(f => f.id.Equals($"{year}") && f.code.Equals(codeYear));
  1077. if (findLess != null)
  1078. {
  1079. if (findLess.lesson.Count == 0)
  1080. {
  1081. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1082. double[] da = new double[yearDays];
  1083. da[days] = x.cnt;
  1084. List<double> tempDays = new(da);
  1085. findLess.lesson = tempDays;
  1086. }
  1087. else findLess.lesson[days] = x.cnt;
  1088. }
  1089. else
  1090. {
  1091. LessonStats lessonYear = new();
  1092. lessonYear.id = $"{year}";
  1093. lessonYear.code = codeYear;
  1094. lessonYear.pk = "LessonYear";
  1095. var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1096. double[] da = new double[yearDays];
  1097. da[days] = x.cnt;
  1098. List<double> tempDays = new(da);
  1099. lessonYear.lesson = tempDays;
  1100. lessYears.Add(lessonYear);
  1101. }
  1102. }
  1103. }
  1104. });
  1105. };
  1106. //openL.ForEach(x => {
  1107. // var (year, days, hour) = TimeHelper.GetDateTime(x.key);
  1108. // LessonYear findLess = lessYears.Find(f => f.id.Equals($"{year}"));
  1109. // if (findLess != null)
  1110. // {
  1111. // if (findLess.openYear.Count == 0)
  1112. // {
  1113. // var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1114. // double[] da = new double[yearDays];
  1115. // da[days] = x.cnt;
  1116. // List<double> tempDays = new(da);
  1117. // findLess.openYear = tempDays;
  1118. // }
  1119. // else findLess.openYear[days] = x.cnt;
  1120. // }
  1121. // else
  1122. // {
  1123. // LessonYear lessonYear = new();
  1124. // lessonYear.id = $"{year}";
  1125. // lessonYear.code = "LessonYear";
  1126. // var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1127. // double[] da = new double[yearDays];
  1128. // da[days] = x.cnt;
  1129. // List<double> tempDays = new(da);
  1130. // lessonYear.openYear = tempDays;
  1131. // lessYears.Add(lessonYear);
  1132. // }
  1133. //});
  1134. //lessL.ForEach(x => {
  1135. // var (year, days, hour) = TimeHelper.GetDateTime(x.key);
  1136. // LessonYear findLess = lessYears.Find(f => f.id.Equals($"{year}"));
  1137. // if (findLess != null)
  1138. // {
  1139. // if (findLess.lessonYear.Count == 0)
  1140. // {
  1141. // var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1142. // double[] da = new double[yearDays];
  1143. // da[days] = x.cnt;
  1144. // List<double> tempDays = new(da);
  1145. // findLess.lessonYear = tempDays;
  1146. // }
  1147. // else findLess.lessonYear[days] = x.cnt;
  1148. // }
  1149. // else
  1150. // {
  1151. // LessonYear lessonYear = new();
  1152. // lessonYear.id = $"{year}";
  1153. // lessonYear.code = "LessonYear";
  1154. // var yearDays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  1155. // double[] da = new double[yearDays];
  1156. // da[days] = x.cnt;
  1157. // List<double> tempDays = new(da);
  1158. // lessonYear.lessonYear = tempDays;
  1159. // lessYears.Add(lessonYear);
  1160. // }
  1161. //});
  1162. return (lessYears, lessHours);
  1163. }
  1164. /// <summary>
  1165. /// 统计学校课例
  1166. /// </summary>
  1167. public record ScLesson
  1168. {
  1169. public string key { get; set; }
  1170. public string schoolId { get; set; }
  1171. public int cnt { get; set; }
  1172. }
  1173. /// <summary>
  1174. /// 统计学校课例详细信息
  1175. /// </summary>
  1176. public record ScLess
  1177. {
  1178. public string key { get; set; }
  1179. public List<LessCnt> lessCnt { get; set; }
  1180. }
  1181. /// <summary>
  1182. /// 统计所有课例
  1183. /// </summary>
  1184. public record AllLess
  1185. {
  1186. public string key { get; set; }
  1187. public int cnt { get; set; }
  1188. }
  1189. /// <summary>
  1190. /// 统计所有课例详细
  1191. /// </summary>
  1192. public record LessCnt
  1193. {
  1194. public string hour { get; set; }
  1195. public string schoolId { get; set; }
  1196. public string cat { get; set; }
  1197. public int upload { get; set; }
  1198. }
  1199. #endregion
  1200. public record AreaSchools
  1201. {
  1202. public string id { get; set; }
  1203. public string name { get; set; }
  1204. public string picture { get; set; }
  1205. public int allCnt { get; set; }
  1206. public int weekCnt { get; set; }
  1207. public int monthCnt { get; set; }
  1208. }
  1209. public record AllAreaInfo
  1210. {
  1211. public string id { get; set; }
  1212. public string name { get; set; }
  1213. public string standard { get; set; }
  1214. public string standardName { get; set; }
  1215. public int lessCnt { get; set; }
  1216. public int actCnt { get; set; }
  1217. public int allCnt { get; set; }
  1218. }
  1219. public record SchoolLen
  1220. {
  1221. public string id { get; set; }
  1222. public string name { get; set;}
  1223. public long totals { get; set; }
  1224. }
  1225. }
  1226. }