LessonSticsController.cs 62 KB

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