ItemInfoController.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. using Microsoft.AspNetCore.Mvc;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.Models;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  9. using TEAMModelOS.SDK.DI;
  10. using System.Text.Json;
  11. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  12. using TEAMModelOS.Models.CommonInfo;
  13. using Microsoft.AspNetCore.Http;
  14. using TEAMModelOS.SDK.Extension;
  15. using Azure.Cosmos;
  16. using Microsoft.AspNetCore.Authentication;
  17. using System.Text;
  18. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  19. namespace TEAMModelOS.Controllers
  20. {
  21. [ProducesResponseType(StatusCodes.Status200OK)]
  22. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  23. //[Authorize(Roles = "IES5")]
  24. [Route("common/item")]
  25. //[Route("api/[controller]")]
  26. [ApiController]
  27. public class ItemInfoController : ControllerBase
  28. {
  29. private readonly SnowflakeId _snowflakeId;
  30. private readonly AzureCosmosFactory _azureCosmos;
  31. public ItemInfoController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId)
  32. {
  33. _azureCosmos = azureCosmos;
  34. _snowflakeId = snowflakeId;
  35. }
  36. /// <summary>
  37. /// 批量保存题目
  38. /// </summary>
  39. /// <param name="request"></param>
  40. /// <returns></returns>
  41. [ProducesDefaultResponseType]
  42. [HttpPost("upsert-all")]
  43. public async Task<IActionResult> UpsertAll(List<ItemInfo> request)
  44. {
  45. // ResponseBuilder builder = ResponseBuilder.custom();
  46. request.ForEach(x => {
  47. if (string.IsNullOrEmpty(x.id)) {
  48. x.id = _snowflakeId.NextId()+"";
  49. x.code = typeof(ItemInfo).Name + "-" + x.code;
  50. };
  51. x.createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  52. });
  53. return Ok(await _azureCosmos.SaveOrUpdateAll(request));
  54. }
  55. [ProducesDefaultResponseType]
  56. [HttpPost("upsert")]
  57. public async Task<IActionResult> Upsert(JsonElement request)
  58. {
  59. ResponseBuilder builder = ResponseBuilder.custom();
  60. /* if (string.IsNullOrEmpty(request.id))
  61. {
  62. request.id = _snowflakeId.NextId() + "";
  63. request.code = typeof(ItemInfo).Name + "-" + request.code;
  64. };
  65. request.createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  66. return Ok(await _azureCosmos.SaveOrUpdate(request));*/
  67. var client = _azureCosmos.GetCosmosClient();
  68. if (!request.TryGetProperty("itemInfo", out JsonElement item)) return BadRequest();
  69. if (!request.TryGetProperty("option", out JsonElement option)) return BadRequest();
  70. ItemInfo itemInfo;
  71. itemInfo = item.ToObject<ItemInfo>();
  72. itemInfo.ttl = -1;
  73. itemInfo.pk = "Item";
  74. if (option.ToString().Equals("insert"))
  75. {
  76. itemInfo.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  77. //new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds();
  78. itemInfo.code = "Item-" + itemInfo.code;
  79. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  80. if (response.Status == 200)
  81. {
  82. return Ok();
  83. }
  84. else {
  85. if (itemInfo.scope.Equals("private"))
  86. {
  87. itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(itemInfo, new PartitionKey($"{itemInfo.code}"));
  88. }
  89. else
  90. {
  91. itemInfo = await client.GetContainer("TEAMModelOS", "School").CreateItemAsync(itemInfo, new PartitionKey($"{itemInfo.code}"));
  92. }
  93. }
  94. }
  95. else
  96. {
  97. itemInfo.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  98. if (itemInfo.scope.Equals("private"))
  99. {
  100. if (!itemInfo.code.Contains("Item"))
  101. {
  102. itemInfo.code = "Item-" + itemInfo.code;
  103. // itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  104. }
  105. itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  106. }
  107. else
  108. {
  109. if (!itemInfo.code.Contains("Item"))
  110. {
  111. itemInfo.code = "Item-" + itemInfo.code;
  112. //itemInfo = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  113. }
  114. itemInfo = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  115. }
  116. }
  117. return Ok(new { itemInfo });
  118. }
  119. /// <summary>
  120. //获取题目摘要信息
  121. /// </summary>
  122. /// <param name="request"></param>
  123. /// <returns></returns>
  124. [ProducesDefaultResponseType]
  125. //[AuthToken(Roles = "teacher")]
  126. [HttpPost("find-summary")]
  127. public async Task<IActionResult> FindSummary(JsonElement requert)
  128. {
  129. var client = _azureCosmos.GetCosmosClient();
  130. StringBuilder sql = new StringBuilder();
  131. sql.Append("select c.id, c.question,c.useCount,c.level,c.field,c.points,c.type,c.option,c.createTime from c ");
  132. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  133. /* if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  134. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();*/
  135. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  136. if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  137. List<object> summary = new List<object>();
  138. Dictionary<string, object> dict = new Dictionary<string, object>();
  139. /* dict.Add("@CURRPAGE", page.GetInt32());
  140. dict.Add("@PAGESIZE", size.GetInt32());*/
  141. dict.Add("@DESC", desc.ToString());
  142. if (requert.TryGetProperty("periodId", out JsonElement periodId))
  143. {
  144. dict.Add("periodId", periodId);
  145. }
  146. if (requert.TryGetProperty("subjectId", out JsonElement subjectId))
  147. {
  148. dict.Add("subjectId", subjectId);
  149. }
  150. if (requert.TryGetProperty("level", out JsonElement level))
  151. {
  152. dict.Add("level", level);
  153. }
  154. if (requert.TryGetProperty("type", out JsonElement type))
  155. {
  156. dict.Add("type", type);
  157. }
  158. if (requert.TryGetProperty("field", out JsonElement field))
  159. {
  160. dict.Add("field", field);
  161. }
  162. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  163. //List<object> items = new List<object>();
  164. if (scope.ToString().Equals("private"))
  165. {
  166. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  167. {
  168. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  169. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  170. {
  171. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  172. {
  173. summary.Add(obj.ToObject<object>());
  174. }
  175. }
  176. }
  177. }
  178. if (scope.ToString().Equals("school"))
  179. {
  180. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  181. {
  182. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  183. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  184. {
  185. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  186. {
  187. summary.Add(obj.ToObject<object>());
  188. }
  189. }
  190. }
  191. }
  192. return Ok(new { summary });
  193. }
  194. /// <summary>
  195. /// 手动挑题
  196. /// </summary>
  197. /// <param name="request"></param>
  198. /// <returns></returns>
  199. [ProducesDefaultResponseType]
  200. //[AuthToken(Roles = "teacher")]
  201. [HttpPost("find-by-ids")]
  202. public async Task<IActionResult> FindByIds(List<string> request)
  203. {
  204. ResponseBuilder builder = ResponseBuilder.custom();
  205. List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
  206. return Ok(items);
  207. }
  208. /// <summary>
  209. /// 删除
  210. /// </summary>
  211. /// <param name="request"></param>
  212. /// <returns></returns>
  213. [ProducesDefaultResponseType]
  214. //[AuthToken(Roles = "teacher")]
  215. [HttpPost("delete")]
  216. public async Task<IActionResult> Delete(JsonElement request)
  217. {
  218. try {
  219. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  220. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  221. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  222. var client = _azureCosmos.GetCosmosClient();
  223. if (scope.ToString().Equals("school"))
  224. {
  225. var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
  226. return Ok(new { code = response.Status });
  227. }
  228. else {
  229. var response = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
  230. return Ok(new { code = response.Status });
  231. }
  232. } catch (Exception e) {
  233. return BadRequest();
  234. }
  235. /* ResponseBuilder builder = ResponseBuilder.custom();
  236. IdPk idPk = await _azureCosmos.DeleteAsync<ItemInfo>( request );
  237. return Ok(idPk);*/
  238. }
  239. /// <summary>
  240. /// 删除
  241. /// </summary>
  242. /// <param name="request"></param>
  243. /// <returns></returns>
  244. [ProducesDefaultResponseType]
  245. //[AuthToken(Roles = "teacher")]
  246. [HttpPost("delete-all")]
  247. public async Task<IActionResult> DeleteAll(JsonElement request)
  248. {
  249. ResponseBuilder builder = ResponseBuilder.custom();
  250. List<IdPk> idPk = await _azureCosmos.DeleteAll<ItemInfo>(request);
  251. return Ok(idPk);
  252. }
  253. /// <summary>
  254. /// 手动挑题
  255. /// </summary>
  256. /// <param name="request"></param>
  257. /// <returns></returns>
  258. [ProducesDefaultResponseType]
  259. //[AuthToken(Roles = "teacher")]
  260. [HttpPost("find")]
  261. public async Task<IActionResult> Find(JsonElement requert)
  262. {
  263. var client = _azureCosmos.GetCosmosClient();
  264. StringBuilder sql = new StringBuilder();
  265. sql.Append("select c.id,c.code,c.repairResource, c.periodId,c.question,c.useCount,c.level,c.field,c.points,c.type,c.option,c.createTime,c.answer,c.explain,c.children,c.score,c.gradeIds,c.subjectId,c.blob,c.scope from c ");
  266. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  267. /* if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  268. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();*/
  269. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  270. if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  271. Dictionary<string, object> dict = new Dictionary<string, object>();
  272. /*var emobj = requert.EnumerateObject();
  273. while (emobj.MoveNext())
  274. {
  275. dict[emobj.Current.Name] = emobj.Current.Value;
  276. }
  277. //处理code
  278. if (dict.TryGetValue("code", out object _))
  279. {
  280. dict.Remove("code");
  281. }*/
  282. /* dict.Add("@CURRPAGE", page.GetInt32());
  283. dict.Add("@PAGESIZE", size.GetInt32());*/
  284. dict.Add("@DESC", desc.ToString());
  285. if (requert.TryGetProperty("periodId", out JsonElement periodId))
  286. {
  287. dict.Add("periodId", periodId);
  288. }
  289. if (requert.TryGetProperty("subjectId", out JsonElement subjectId))
  290. {
  291. dict.Add("subjectId", subjectId);
  292. }
  293. if (requert.TryGetProperty("level", out JsonElement level))
  294. {
  295. dict.Add("level", level);
  296. }
  297. if (requert.TryGetProperty("type", out JsonElement type))
  298. {
  299. dict.Add("type", type);
  300. }
  301. if (requert.TryGetProperty("field", out JsonElement field))
  302. {
  303. dict.Add("field", field);
  304. }
  305. if (requert.TryGetProperty("gradeIds[*]", out JsonElement gradeIds))
  306. {
  307. dict.Add("gradeIds[*]", gradeIds);
  308. }
  309. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  310. List<object> items = new List<object>();
  311. if (scope.ToString().Equals("private"))
  312. {
  313. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  314. {
  315. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  316. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  317. {
  318. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  319. {
  320. items.Add(obj.ToObject<object>());
  321. }
  322. }
  323. }
  324. }
  325. if(scope.ToString().Equals("school")) {
  326. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  327. {
  328. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  329. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  330. {
  331. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  332. {
  333. items.Add(obj.ToObject<object>());
  334. }
  335. }
  336. }
  337. }
  338. //ResponseBuilder builder = ResponseBuilder.custom();
  339. /* List<ItemInfo> items = new List<ItemInfo>();
  340. if (StringHelper.getKeyCount(requert) > 0)
  341. {
  342. items = await _azureCosmos.FindByDict<ItemInfo>(requert);
  343. }*/
  344. return Ok(new { items });
  345. //return builder.Data(items).build();
  346. }
  347. /// <summary>
  348. /// 手动挑题
  349. /// </summary>
  350. /// <param name="request"></param>
  351. /// <returns></returns>
  352. [ProducesDefaultResponseType]
  353. //[AuthToken(Roles = "teacher")]
  354. [HttpPost("Find-cache-shell")]
  355. public async Task<IActionResult> FindCacheShell(JsonElement requert)
  356. {
  357. var client = _azureCosmos.GetCosmosClient();
  358. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  359. if (!requert.TryGetProperty("ids", out JsonElement id)) return BadRequest();
  360. //List<string> ids = new List<string>();
  361. string info = "";
  362. for (int i = 0; i < id.GetArrayLength(); i++) {
  363. //ids.Add(id[i].ToJsonString());
  364. info += id[i].ToJsonString() + ",";
  365. }
  366. List<object> items = new List<object>();
  367. var query = $"select c.id, c.question,c.useCount,c.level,c.field,c.points,c.type,c.option,c.createTime from c where c.id in ({info[0..^1]})";
  368. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ItemInfo-{school_code}") }))
  369. {
  370. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  371. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  372. {
  373. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  374. {
  375. items.Add(obj.ToObject<object>());
  376. }
  377. }
  378. }
  379. return Ok(new { items });
  380. /* ResponseBuilder builder = ResponseBuilder.custom();
  381. List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
  382. //List<string> ps = new List<string>() { "6f705b1b-8221-5307-18da-13da05adf91e", "c3e1e95a-561e-fabf-cce3-3a564782e443" };
  383. //
  384. //
  385. //Random random = new Random();
  386. //items.ForEach(x => { x.usageCount = random.Next(0, 300);x.createTime = random.Next(1426668584, 1584521384);x.order = random.Next(1, items.Count); });
  387. //await cosmosDBV3Repository.SaveOrUpdateAll(items);
  388. return builder.Data(items).build();*/
  389. }
  390. /// <summary>
  391. /// 自动组题
  392. /// </summary>
  393. /// <param name="request"></param>
  394. /// <returns></returns>
  395. [HttpPost("Automatic")]
  396. public async Task<IActionResult> Automatic(List<Compose> request)
  397. {
  398. //ResponseBuilder builder = ResponseBuilder.custom();
  399. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  400. var client = _azureCosmos.GetCosmosClient();
  401. for (int i = 0; i < request.Count; i++) {
  402. ///处理知识点均分问题
  403. int avg = 0;
  404. Dictionary<string, int> point = new Dictionary<string, int>();
  405. if (request[i].points.IsNotEmpty())
  406. {
  407. avg = (int)Math.Ceiling(request[i].count * 1.0 / request[i].points.Count);
  408. foreach (string p in request[i].points)
  409. {
  410. point.TryAdd(p, avg);
  411. }
  412. }
  413. List<ItemInfo> retnInfos = new List<ItemInfo>();
  414. List<ItemInfo> itemInfos = new List<ItemInfo>();
  415. List<TempItem> tempItems = new List<TempItem>();
  416. if (request[i].quInfos.IsNotEmpty())
  417. {
  418. List<string> types = new List<string>();
  419. List<int> levels = new List<int>();
  420. foreach (QuInfo quInfo in request[i].quInfos)
  421. {
  422. StringBuilder sql = new StringBuilder();
  423. sql.Append("select c.id,c.code,c.repairResource, c.periodId,c.question,c.useCount,c.level,c.field,c.points,c.type,c.option,c.createTime,c.answer,c.explain,c.children,c.score,c.gradeIds,c.subjectId,c.blob,c.scope from c ");
  424. // 自定义
  425. if (quInfo.custom.IsNotEmpty() && quInfo.policy.Equals("custom"))
  426. {
  427. foreach (Custom custom in quInfo.custom)
  428. {
  429. for (int j = 0; j < custom.count; j++)
  430. {
  431. tempItems.Add(new TempItem { level = custom.level, type = quInfo.type });
  432. }
  433. Dictionary<string, object> dict = new Dictionary<string, object>();
  434. if (!string.IsNullOrEmpty(request[i].code))
  435. {
  436. dict.Add("code", request[i].code);
  437. }
  438. if (!string.IsNullOrEmpty(request[i].period))
  439. {
  440. dict.Add("periodId", request[i].period);
  441. }
  442. if (request[i].points.IsNotEmpty())
  443. {
  444. dict.Add("points[*]", request[i].points.ToArray());
  445. }
  446. dict.Add("lite", false);
  447. ///
  448. dict.Add("type", quInfo.type);
  449. dict.Add("level", custom.level);
  450. List<ItemInfo> items = new List<ItemInfo>();
  451. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  452. if (request[i].scope.Equals("school"))
  453. {
  454. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  455. {
  456. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  457. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  458. {
  459. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  460. {
  461. items.Add(obj.ToObject<ItemInfo>());
  462. }
  463. }
  464. }
  465. }
  466. else {
  467. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  468. {
  469. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  470. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  471. {
  472. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  473. {
  474. items.Add(obj.ToObject<ItemInfo>());
  475. }
  476. }
  477. }
  478. }
  479. //List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  480. //id去重
  481. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  482. ////均分知识点题目
  483. itemInfos.AddRange(items);
  484. }
  485. }
  486. else
  487. {
  488. Dictionary<string, object> dict = new Dictionary<string, object>();
  489. if (!string.IsNullOrEmpty(request[i].code))
  490. {
  491. dict.Add("code", request[i].code);
  492. }
  493. if (!string.IsNullOrEmpty(request[i].period))
  494. {
  495. dict.Add("periodId", request[i].period);
  496. }
  497. if (request[i].points.IsNotEmpty())
  498. {
  499. dict.Add("points[*]", request[i].points.ToArray());
  500. }
  501. if (!string.IsNullOrEmpty(request[i].subject))
  502. {
  503. dict.Add("subjectId", request[i].subject);
  504. }
  505. dict.Add("lite", false);
  506. dict.Add("type", quInfo.type);
  507. List<ItemInfo> items = new List<ItemInfo>();
  508. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  509. if (request[i].scope.Equals("school"))
  510. {
  511. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  512. {
  513. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  514. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  515. {
  516. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  517. {
  518. items.Add(obj.ToObject<ItemInfo>());
  519. }
  520. }
  521. }
  522. }
  523. else
  524. {
  525. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  526. {
  527. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  528. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  529. {
  530. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  531. {
  532. items.Add(obj.ToObject<ItemInfo>());
  533. }
  534. }
  535. }
  536. }
  537. //List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  538. //id去重
  539. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  540. itemInfos.AddRange(items);
  541. //均分
  542. if (quInfo.policy.Equals("average"))
  543. {
  544. //按等级去重 获取所有等级
  545. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  546. foreach (int k in lvls)
  547. {
  548. int count = quInfo.count / lvls.Count;
  549. for (int j = 0; j < count; j++)
  550. {
  551. tempItems.Add(new TempItem { level = k, type = quInfo.type });
  552. }
  553. }
  554. // 余数 取模 随机处理
  555. if (lvls.Count != 0)
  556. {
  557. int mod = quInfo.count % lvls.Count;
  558. for (int m = 0; m < mod; m++)
  559. {
  560. int lv = lvls.OrderBy(x => Guid.NewGuid()).Take(1).FirstOrDefault();
  561. tempItems.Add(new TempItem { level = lv, type = quInfo.type });
  562. lvls.Remove(lv);
  563. }
  564. }
  565. }
  566. //随机
  567. if (quInfo.policy.Equals("random"))
  568. {
  569. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  570. for (int n = 0; n < quInfo.count; n++)
  571. {
  572. int lv = lvls.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  573. tempItems.Add(new TempItem { level = lv, type = quInfo.type,policy = "random" });
  574. }
  575. }
  576. }
  577. }
  578. }
  579. itemInfos = itemInfos.OrderBy(x => Guid.NewGuid()).ToList();
  580. tempItems = tempItems.OrderBy(x => Guid.NewGuid()).ToList();
  581. foreach (TempItem temp in tempItems)
  582. {
  583. ItemInfo itemInfo = new ItemInfo();
  584. if (temp.policy != null && temp.policy.Equals("random"))
  585. {
  586. itemInfo = itemInfos.Where(x => x.type == temp.type).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  587. }
  588. else {
  589. itemInfo = itemInfos.Where(x => x.level == temp.level && x.type == temp.type).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  590. }
  591. if (itemInfo != null)
  592. {
  593. retnInfos.Add(itemInfo);
  594. itemInfos.Remove(itemInfo);
  595. }
  596. }
  597. List<List<ItemInfo>> listInfo = new List<List<ItemInfo>>();
  598. foreach (IGrouping<string, ItemInfo> group in retnInfos.GroupBy(c => c.type))
  599. {
  600. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  601. listInfo.Add(group.ToList());
  602. }
  603. foreach (List<ItemInfo> infos in listInfo)
  604. {
  605. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  606. foreach (IGrouping<int, ItemInfo> group in infos.GroupBy(c => c.level))
  607. {
  608. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  609. dictInfo.Add("level", group.Key);
  610. dictInfo.Add("count", group.Count());
  611. dict.Add(dictInfo);
  612. }
  613. Dictionary<string, object> typeDict = new Dictionary<string, object>();
  614. typeDict.Add("info", dict);
  615. typeDict.Add("item", infos);
  616. typeDict.Add("count", infos.Count);
  617. typeDict.Add("type", infos.FirstOrDefault().type);
  618. list.Add(typeDict);
  619. }
  620. }
  621. //return builder.Data(list).build();
  622. return Ok(list);
  623. }
  624. }
  625. public class TempItem
  626. {
  627. public string type { get; set; }
  628. public int level { get; set; }
  629. public ItemInfo itemInfo { get; set; }
  630. public string policy { get; set; }
  631. }
  632. public class Compose
  633. {
  634. /// <summary>
  635. /// 科目
  636. /// </summary>
  637. public string subject { get; set; }
  638. /// <summary>
  639. /// 来源,个人题库,校本题库
  640. /// </summary>
  641. public string code { get; set; }
  642. /// <summary>
  643. /// 适用学段,小学,初中,高中
  644. /// </summary>
  645. public string period { get; set; }
  646. /// <summary>
  647. /// 关联知识点
  648. /// </summary>
  649. public List<string> points { get; set; }
  650. /// <summary>
  651. /// 题目组合
  652. /// </summary>
  653. public List<QuInfo> quInfos { get; set; }
  654. /// <summary>
  655. /// 题目总数
  656. /// </summary>
  657. public int count { get; set; }
  658. public string scope { get; set; }
  659. }
  660. public class QuInfo
  661. {
  662. /// <summary>
  663. /// 题目类型,单选,多选,判断,填空,问答,综合 Single单选,Multiple多选,Judge判断,Complete填空,Subjective问答,Compose综合
  664. /// </summary>
  665. public string type { get; set; }
  666. /// <summary>
  667. /// 随机 random 平均的 average ,自定义 custom
  668. /// </summary>
  669. public string policy { get; set; }
  670. /// <summary>
  671. /// 自定义题目类型
  672. /// </summary>
  673. public List<Custom> custom { get; set; }
  674. /// <summary>
  675. /// 总题
  676. /// </summary>
  677. public int count { get; set; }
  678. }
  679. public class Custom
  680. {
  681. /// <summary>
  682. /// 难易程度
  683. /// </summary>
  684. public int level { get; set; }
  685. /// <summary>
  686. /// 数量
  687. /// </summary>
  688. public int count { get; set; }
  689. }
  690. }