LessonSticsController.cs 62 KB

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