BatchAreaController.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using TEAMModelOS.Models;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Models;
  12. using Azure.Cosmos;
  13. using System.Text.Json;
  14. using HTEXLib.COMM.Helpers;
  15. using TEAMModelOS.SDK.Models.Cosmos.Common;
  16. using TEAMModelOS.SDK.Models.Cosmos.BI;
  17. using Azure.Messaging.ServiceBus;
  18. using TEAMModelOS.SDK.Extension;
  19. using TEAMModelBI.Filter;
  20. using TEAMModelBI.Tool.Extension;
  21. using TEAMModelBI.Tool;
  22. using Azure.Storage.Blobs.Models;
  23. using Azure;
  24. using Azure.Storage.Blobs.Specialized;
  25. using System.Net.Http;
  26. using System.Net.Http.Json;
  27. using System.Net;
  28. using TEAMModelOS.SDK;
  29. using TEAMModelOS.SDK.Context.BI;
  30. using TEAMModelOS.SDK.DI.CoreAPI;
  31. namespace TEAMModelBI.Controllers.BINormal
  32. {
  33. [Route("batcharea")]
  34. [ApiController]
  35. public class BatchAreaController : ControllerBase
  36. {
  37. private readonly AzureCosmosFactory _azureCosmos;
  38. private readonly DingDing _dingDing;
  39. private readonly Option _option;
  40. private readonly AzureStorageFactory _azureStorage;
  41. private readonly IConfiguration _configuration;
  42. private readonly NotificationService _notificationService;
  43. private readonly AzureServiceBusFactory _serviceBus;
  44. private readonly IHttpClientFactory _http;
  45. private readonly CoreAPIHttpService _coreAPIHttpService;
  46. public BatchAreaController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, NotificationService notificationService, AzureServiceBusFactory serviceBus, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService)
  47. {
  48. _azureCosmos = azureCosmos;
  49. _dingDing = dingDing;
  50. _azureStorage = azureStorage;
  51. _option = option?.Value;
  52. _configuration = configuration;
  53. _notificationService = notificationService;
  54. _serviceBus = serviceBus;
  55. _http = http;
  56. _coreAPIHttpService = coreAPIHttpService;
  57. }
  58. /// <summary>
  59. /// 查询所有的区域标准 //已对接
  60. /// </summary>
  61. /// <returns></returns>
  62. [ProducesDefaultResponseType]
  63. [HttpPost("get-areas")]
  64. public async Task<IActionResult> GetArea(JsonElement jsonElement)
  65. {
  66. try
  67. {
  68. jsonElement.TryGetProperty("site", out JsonElement site);
  69. int? pageSize = null; //默认不指定返回大小
  70. string continuationToken = string.Empty; //返给前端分页token
  71. string pageToken = default;//接受前端的分页Tolen
  72. bool iscontinuation = false;//是否需要进行分页查询,默认不分页
  73. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  74. {
  75. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  76. {
  77. pageSize = tempPageSize;
  78. }
  79. }
  80. if (pageSize != null && pageSize.Value > 0)
  81. {
  82. iscontinuation = true;
  83. }
  84. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  85. {
  86. pageToken = ContToken.GetString();
  87. }
  88. List<RecArea> areas = new();
  89. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  90. var cosmosClient = _azureCosmos.GetCosmosClient();
  91. if ($"{site}".Equals(BIConst.Global))
  92. {
  93. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  94. table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("IESLogin");
  95. }
  96. string areaSql = $"select c.id,c.code,c.pk,c.name,c.provCode,c.provName,c.cityCode,c.cityName,c.standard,c.standardName,c.institution from c";
  97. await foreach (var itemArea in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryStreamIterator(queryText: areaSql, continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base-Area") }))
  98. {
  99. using var json = await JsonDocument.ParseAsync(itemArea.ContentStream);
  100. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  101. {
  102. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  103. {
  104. areas.Add(obj.ToObject<RecArea>());
  105. }
  106. if (iscontinuation)
  107. {
  108. continuationToken = itemArea.GetContinuationToken();
  109. break;
  110. }
  111. }
  112. }
  113. //areas.ForEach(async area =>
  114. //{
  115. // area.schoolCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c where c.areaId='{area.id}' and c.standard='{area.standard}'", "Base");
  116. // area.aquoteRec = await table.QueryWhereString<AreaQuoteRecord>($"PartitionKey eq 'QuoteRecord' and areaId eq '{area.id}'");
  117. // //List<AreaQuoteRecord> aqr = await table.QueryWhereString<AreaQuoteRecord>($"PartitionKey eq 'QuoteRecord' and areaId eq '{area.id}'");
  118. // //aqr.Sort((x, y) => y.RowKey.CompareTo(x.RowKey));
  119. // await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<string>(queryText: $"select value(c.accessConfig) from c where c.id='{area.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  120. // {
  121. // if (string.IsNullOrEmpty(item))
  122. // area.cutArea = false;
  123. // else
  124. // area.cutArea = true;
  125. // };
  126. //});
  127. foreach (var area in areas)
  128. {
  129. area.schoolCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c where c.areaId='{area.id}' and c.standard='{area.standard}'", "Base");
  130. area.aquoteRec = await table.QueryWhereString<AreaQuoteRecord>($"PartitionKey eq 'QuoteRecord' and areaId eq '{area.id}'");
  131. //List<AreaQuoteRecord> aqr = await table.QueryWhereString<AreaQuoteRecord>($"PartitionKey eq 'QuoteRecord' and areaId eq '{area.id}'");
  132. //aqr.Sort((x, y) => y.RowKey.CompareTo(x.RowKey));
  133. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<string>(queryText: $"select value(c.accessConfig) from c where c.id='{area.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  134. {
  135. if (string.IsNullOrEmpty(item))
  136. area.cutArea = false;
  137. else
  138. area.cutArea = true;
  139. };
  140. }
  141. return Ok(new { state = 200, areas, continuationToken });
  142. }
  143. catch (Exception ex)
  144. {
  145. await _dingDing.SendBotMsg($"BI,{_option.Location} batcharea/get-areas \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  146. return BadRequest();
  147. }
  148. }
  149. /// <summary>
  150. /// 批量创区 新接口 //已对接
  151. /// </summary>
  152. /// <param name="jsonElement"></param>
  153. /// <returns></returns>
  154. [ProducesDefaultResponseType]
  155. [AuthToken(Roles = "admin,rdc")]
  156. [HttpPost("batch-area")]
  157. public async Task<IActionResult> batchArea(JsonElement jsonElement)
  158. {
  159. try
  160. {
  161. if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
  162. jsonElement.TryGetProperty("provCode", out JsonElement provCode);
  163. jsonElement.TryGetProperty("provName", out JsonElement provName);
  164. jsonElement.TryGetProperty("cityCode", out JsonElement cityCode);
  165. jsonElement.TryGetProperty("cityName", out JsonElement cityName);
  166. jsonElement.TryGetProperty("areaAdmin", out JsonElement areadAdmin);
  167. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  168. if (!jsonElement.TryGetProperty("standardName", out JsonElement standardName)) return BadRequest();
  169. jsonElement.TryGetProperty("institution", out JsonElement institution);
  170. jsonElement.TryGetProperty("oldId", out JsonElement _oldId);
  171. jsonElement.TryGetProperty("oldStandard", out JsonElement oldStandard);
  172. jsonElement.TryGetProperty("oldName", out JsonElement oldName);
  173. jsonElement.TryGetProperty("site", out JsonElement site);
  174. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  175. //操作记录实体
  176. var tempStandard = !string.IsNullOrEmpty($"{oldStandard}") && !string.IsNullOrEmpty($"{_oldId}") ? $"{oldStandard}" : "standard2";
  177. var cosmosClient = _azureCosmos.GetCosmosClient();//数据库连接
  178. var tableClient = _azureStorage.GetCloudTableClient();
  179. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  180. ServiceBusClient serBusClient;
  181. try
  182. {
  183. serBusClient = _serviceBus.GetServiceBusClient();
  184. }
  185. catch
  186. {
  187. return Ok(new { state = 403, msg = "Functionn未启动,请联系管理员" });
  188. }
  189. var activeTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");//秘钥地址
  190. if ($"{site}".Equals(BIConst.Global))
  191. {
  192. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  193. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  194. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", name: BIConst.Global);
  195. }
  196. var table = tableClient.GetTableReference("IESLogin");
  197. //查询新的是否存在
  198. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: $"select value(c) from c where c.standard='{standard}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  199. {
  200. if (item.standard.Equals($"{standard}"))
  201. return Ok(new { state = 1, message = "新创区的standard已存在请检查" });
  202. }
  203. //区级的ID
  204. string areaId = Guid.NewGuid().ToString();
  205. Area addArea = new Area()
  206. {
  207. id = areaId,
  208. code = $"Base-Area",
  209. name = $"{name}",
  210. provCode = $"{provCode}",
  211. provName = $"{provName}",
  212. cityCode = $"{cityCode}",
  213. cityName = $"{cityName}",
  214. standard = $"{standard}",
  215. standardName = $"{standardName}",
  216. institution = $"{institution}"
  217. };
  218. #region 区级管理员
  219. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{areadAdmin}" } }, _option.Location, _configuration);
  220. if (coreUser == null || coreUser.id == null)
  221. return Ok(new { state = 404, msg = "未找到改账户的管理员" });
  222. //string tmdId = !string.IsNullOrEmpty(tempTmdId) ? tempTmdId : $"{areadAdmin}";
  223. Teacher teacher = null;
  224. try
  225. {
  226. //查询该教师是否存在
  227. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{coreUser.id}", new PartitionKey("Base"));
  228. }
  229. catch
  230. {
  231. }
  232. if (teacher != null)
  233. {
  234. //教师存在,在该教师信息中添加要管理的学校信息
  235. teacher.areas.Add(new Teacher.TeacherArea { areaId = addArea.id, status = "join", name = addArea.name });
  236. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  237. }
  238. else
  239. {
  240. teacher.id = coreUser.id;
  241. teacher.name = coreUser.name;
  242. teacher.picture = coreUser.picture;
  243. teacher.pk = "Base";
  244. teacher.code = "Base";
  245. teacher.size = 1;
  246. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  247. //教师存在,在该教师信息中添加要管理的学校信息
  248. teacher.areas.Add(new Teacher.TeacherArea { areaId = addArea.id, status = "join", name = addArea.name });
  249. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  250. }
  251. #endregion
  252. //创建区域
  253. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync<Area>(addArea, new PartitionKey("Base-Area"));
  254. //保存引用记录
  255. await table.SaveOrUpdate<AreaQuoteRecord>(new AreaQuoteRecord() { PartitionKey = "QuoteRecord", RowKey = $"{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", areaId = $"{areaId}", quoteId = $"{_oldId}", quoteName = $"{oldName}", standard = tempStandard });
  256. //消息分区键
  257. string partitionCode = "copyAbility-mark";
  258. #region 使用Function创区
  259. //string areaCode = "copyArea-mark";
  260. //BatchCopyAreaRelevant bCopyArea = new BatchCopyAreaRelevant()
  261. //{
  262. // tmdid = $"{_tmdId}",
  263. // tmdName = $"{_tmdName}",
  264. // codeKey = areaCode,
  265. // tmdIds = new List<string> { $"{_tmdId}"},
  266. // oldStandard = $"{oldStandard}",
  267. // oldId = $"{_oldId}",
  268. // standard = $"{standard}",
  269. // areaId = areaId,
  270. // cut="",
  271. //};
  272. //var messageBatchCopyArea = new ServiceBusMessage(bCopyArea.ToJsonString());
  273. //messageBatchCopyArea.ApplicationProperties.Add("name", "CopyAreaRelevant");
  274. //var activeTaskArea = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  275. //await _serviceBus.GetServiceBusClient().SendMessageAsync(activeTaskArea, messageBatchCopyArea);
  276. #endregion
  277. #region 旧的批量创区
  278. List<Task<ItemResponse<Ability>>> abilities = new List<Task<ItemResponse<Ability>>>(); //存储区域数据
  279. List<Task<ItemResponse<AbilityTask>>> abilityTasks = new List<Task<ItemResponse<AbilityTask>>>(); //存储章节
  280. if (!string.IsNullOrEmpty($"{oldStandard}") && !string.IsNullOrEmpty($"{_oldId}"))
  281. {
  282. //查询要复制区域的能力标准点
  283. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{oldStandard}") }))
  284. {
  285. if (!string.IsNullOrEmpty(item.blob))
  286. {
  287. item.blob = item.blob.Replace($"/{oldStandard}/", $"/{standard}/");
  288. };
  289. item.standard = $"{standard}";
  290. item.code = $"Ability-{standard}";
  291. item.school = $"{standard}";
  292. //添加区能力标准点
  293. abilities.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(item, new PartitionKey($"Ability-{standard}")));
  294. }
  295. try
  296. {
  297. if (abilities.Count < 256)
  298. {
  299. await Task.WhenAll(abilities);
  300. }
  301. else
  302. {
  303. int pages = (abilities.Count + 255) / 256;
  304. for (int i = 0; i < pages; i++)
  305. {
  306. List<Task<ItemResponse<Ability>>> tempAbility = abilities.Skip((i) * 256).Take(256).ToList();
  307. await Task.WhenAll(tempAbility);
  308. }
  309. }
  310. }
  311. catch
  312. {
  313. return Ok(new { state = 200, msg = "创区成功,能力标准点复制失败,遗留数据影响!" });
  314. }
  315. try
  316. {
  317. //微能力点
  318. await foreach (var atask in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{oldStandard}") }))
  319. {
  320. List<Tnode> tnodes = new List<Tnode>();
  321. foreach (Tnode tnode in atask.children)
  322. {
  323. if (tnode.rnodes != null)
  324. {
  325. List<Rnode> rnodes = new List<Rnode>();
  326. foreach (Rnode rnode in tnode.rnodes)
  327. {
  328. if (!string.IsNullOrEmpty($"{rnode.link}"))
  329. {
  330. rnode.link = rnode.link.Replace($"/{oldStandard}/", $"/{standard}/");
  331. }
  332. rnodes.Add(rnode);
  333. }
  334. tnode.rnodes = rnodes;
  335. }
  336. tnodes.Add(tnode);
  337. }
  338. atask.children = tnodes;
  339. atask.code = $"AbilityTask-{standard}";
  340. atask.standard = $"{standard}";
  341. atask.codeval = $"{standard}";
  342. //添加区能力标准点中的节点
  343. //abilityTasks.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}")));
  344. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}"));
  345. }
  346. }
  347. catch
  348. {
  349. return Ok(new { state = 200, msg = "创区成功,能力标准创建成功,微能力点复制失败,遗留数据影响!" });
  350. }
  351. //if (abilityTasks.Count > 0)
  352. //{
  353. // for (int i = 0; i < abilityTasks.Count; i++)
  354. // {
  355. // List<Task<ItemResponse<AbilityTask>>> tempAbilityTasks = abilityTasks.Skip((i)).Take(1).ToList();
  356. // await Task.WhenAll(tempAbilityTasks);
  357. // }
  358. //}
  359. //新政策文件
  360. await foreach (StandardFile standardFile in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<StandardFile>(queryText: $"select value(c) from c where c.id='{_oldId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StandardFile") }))
  361. {
  362. if (standardFile != null)
  363. {
  364. standardFile.standard = $"{standard}";
  365. standardFile.id = areaId;
  366. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(standardFile, new PartitionKey($"StandardFile"));
  367. }
  368. }
  369. //新的区域设置
  370. await foreach (AreaSetting areaSetting in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: $"select value(c) from c where c.id='{_oldId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  371. {
  372. if (areaSetting != null)
  373. {
  374. areaSetting.accessConfig = null;
  375. areaSetting.id = areaId;
  376. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(areaSetting, new PartitionKey($"AreaSetting"));
  377. }
  378. }
  379. }
  380. else
  381. {
  382. Area area = null;
  383. await foreach (var tempArea in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: $"select value(c) from c where c.standard='standard2'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  384. {
  385. area = tempArea;
  386. }
  387. if (area != null)
  388. {
  389. //查询要复制区域的能力标准点
  390. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{area.standard}") }))
  391. {
  392. if (!string.IsNullOrEmpty(item.blob))
  393. {
  394. item.blob = item.blob.Replace($"/{area.standard}/", $"/{standard}/");
  395. };
  396. item.standard = $"{standard}";
  397. item.code = $"Ability-{standard}";
  398. item.school = $"{standard}";
  399. //添加区能力标准点
  400. abilities.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(item, new PartitionKey($"Ability-{standard}")));
  401. }
  402. try
  403. {
  404. if (abilities.Count < 256)
  405. {
  406. await Task.WhenAll(abilities);
  407. }
  408. else
  409. {
  410. int pages = (abilities.Count + 255) / 256;
  411. for (int i = 0; i < pages; i++)
  412. {
  413. List<Task<ItemResponse<Ability>>> tempAbility = abilities.Skip((i) * 256).Take(256).ToList();
  414. await Task.WhenAll(tempAbility);
  415. }
  416. }
  417. }
  418. catch
  419. {
  420. return Ok(new { state = 200, msg = "创区成功,能力标准点复制失败,遗留数据影响!" });
  421. }
  422. try
  423. {
  424. //微能力点
  425. await foreach (var atask in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
  426. {
  427. List<Tnode> tnodes = new List<Tnode>();
  428. foreach (Tnode tnode in atask.children)
  429. {
  430. if (tnode.rnodes != null)
  431. {
  432. List<Rnode> rnodes = new List<Rnode>();
  433. foreach (Rnode rnode in tnode.rnodes)
  434. {
  435. if (!string.IsNullOrEmpty($"{rnode.link}"))
  436. {
  437. rnode.link = rnode.link.Replace($"/{area.standard}/", $"/{standard}/");
  438. }
  439. rnodes.Add(rnode);
  440. }
  441. tnode.rnodes = rnodes;
  442. }
  443. tnodes.Add(tnode);
  444. }
  445. atask.children = tnodes;
  446. atask.code = $"AbilityTask-{standard}";
  447. atask.standard = $"{standard}";
  448. atask.codeval = $"{standard}";
  449. //添加区能力标准点中的节点
  450. //abilityTasks.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}")));
  451. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}"));
  452. }
  453. }
  454. catch
  455. {
  456. return Ok(new { state = 200, msg = "创区成功,能力标准创建成功,微能力点复制失败,遗留数据影响!" });
  457. }
  458. //if (abilityTasks.Count > 0)
  459. //{
  460. // for (int i = 0; i < abilityTasks.Count; i++)
  461. // {
  462. // List<Task<ItemResponse<AbilityTask>>> tempAbilityTasks = abilityTasks.Skip(i).Take(1).ToList();
  463. // await Task.WhenAll(tempAbilityTasks);
  464. // }
  465. //}
  466. //新政策文件
  467. await foreach (StandardFile standardFile in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<StandardFile>(queryText: $"select value(c) from c where c.id='{area.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StandardFile") }))
  468. {
  469. if (standardFile != null)
  470. {
  471. standardFile.standard = $"{standard}";
  472. standardFile.id = areaId;
  473. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(standardFile, new PartitionKey($"StandardFile"));
  474. }
  475. }
  476. //新的区域设置
  477. await foreach (AreaSetting areaSetting in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: $"select value(c) from c where c.id='{area.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  478. {
  479. if (areaSetting != null)
  480. {
  481. areaSetting.accessConfig = null;
  482. areaSetting.id = areaId;
  483. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(areaSetting, new PartitionKey($"AreaSetting"));
  484. }
  485. }
  486. }
  487. else return Ok(new { state = 201, message = "未找到默认能力点!" });
  488. }
  489. #endregion
  490. //执行复制操作
  491. BatchCopyFile batchCopyFile = new BatchCopyFile();
  492. batchCopyFile.blobCntr = "teammodelos";
  493. batchCopyFile.oldFileName = $"{oldStandard}";
  494. batchCopyFile.newFileName = $"{standard}";
  495. batchCopyFile.tmdid = $"{_tmdId}";
  496. batchCopyFile.tmdIds = new List<string> { $"{ _tmdId}" };
  497. batchCopyFile.codeKey = partitionCode;
  498. batchCopyFile.tmdName = $"{_tmdName}";
  499. var messageBatchCopyFile = new ServiceBusMessage(batchCopyFile.ToJsonString());
  500. messageBatchCopyFile.ApplicationProperties.Add("name", "CopyStandardFile");
  501. //var activeTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  502. try
  503. {
  504. //await _serviceBus.GetServiceBusClient().SendMessageAsync(activeTask, messageBatchCopyFile);
  505. await serBusClient.SendMessageAsync(activeTask, messageBatchCopyFile);
  506. }
  507. catch (Exception)
  508. {
  509. return Ok(new { state = 201, msg = "能力点复制成功,复制能力点的文件失败," });
  510. }
  511. //发送消息实体
  512. Notification notification = new Notification
  513. {
  514. hubName = "hita",
  515. type = "msg",
  516. from = $"BI:{_option.Location}:private",
  517. to = new List<string> { $"{ _tmdId}" },
  518. label = $"{partitionCode}_start",
  519. body = new { location = _option.Location, biz = partitionCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  520. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  521. };
  522. var notiUrl = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  523. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  524. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  525. var location = _option.Location;
  526. await _notificationService.SendNotification(clientID, clientSecret, location, notiUrl, notification); //站内发送消息
  527. //保存操作记录
  528. //await _azureStorage.SaveBILog("area-add", $"{_tmdName}【{_tmdId}】已操作创区功能模块:{name},当前标准【{standard}】,复制的微能力点:{tempStandard}", _dingDing, httpContext: HttpContext);
  529. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "area-add", $"{_tmdName}【{_tmdId}】已操作创区功能模块:{name},当前标准【{standard}】,复制的微能力点:{tempStandard}", _dingDing, httpContext: HttpContext);
  530. return Ok(new { state = 200, area = addArea });
  531. }
  532. catch (Exception ex)
  533. {
  534. await _dingDing.SendBotMsg($"BI,{_option.Location} /batcharea/batch-area \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  535. return BadRequest();
  536. }
  537. }
  538. /// <summary>
  539. /// 创区后切换能力点, 先删除原来的能力点,后复制新的能力点 //已对接
  540. /// </summary>
  541. /// <param name="jsonElement"></param>
  542. /// <returns></returns>
  543. [ProducesDefaultResponseType]
  544. [AuthToken(Roles = "admin,rdc")]
  545. [HttpPost("cut-standard")]
  546. public async Task<IActionResult> CutStandard(JsonElement jsonElement)
  547. {
  548. try
  549. {
  550. if (!jsonElement.TryGetProperty("oldId", out JsonElement _oldId)) return BadRequest();
  551. if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
  552. if (!jsonElement.TryGetProperty("newId", out JsonElement _newId)) return BadRequest();
  553. if (!jsonElement.TryGetProperty("newStandard", out JsonElement _newStandard)) return BadRequest();
  554. jsonElement.TryGetProperty("newName", out JsonElement newName);
  555. jsonElement.TryGetProperty("site", out JsonElement site);
  556. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  557. //操作记录实体
  558. string blobOrTable = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
  559. var tableClient = _azureStorage.GetCloudTableClient();
  560. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  561. var cosmosClient = _azureCosmos.GetCosmosClient();
  562. var serBusClient = _serviceBus.GetServiceBusClient();
  563. var activeTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");//秘钥地址
  564. if ($"{site}".Equals(BIConst.Global))
  565. {
  566. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  567. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  568. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  569. serBusClient = _serviceBus.GetServiceBusClient(BIConst.Global); //暂未确定使用默认
  570. //activeTask = _configuration.GetValue<string>("GlobalAzure:ServiceBus:ActiveTask"); //暂未确定使用默认
  571. }
  572. var table = tableClient.GetTableReference("IESLogin");
  573. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{_oldId}", new PartitionKey("AreaSetting"));
  574. if (responseSet.Status == 200)
  575. {
  576. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  577. AreaSetting delSet = fileJson.ToObject<AreaSetting>();
  578. if (!string.IsNullOrEmpty(delSet.accessConfig))
  579. return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
  580. }
  581. //保存引用记录
  582. //await table.SaveOrUpdate<AreaQuoteRecord>(new AreaQuoteRecord() { PartitionKey = "QuoteRecord", RowKey = $"{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}", areaId = $"{_oldId}", quoteId = $"{_newId}", quoteName = $"{newName}", standard = $"{_newStandard}" });
  583. List<string> abilityIds = new List<string>(); //册别的ID集合
  584. //查询册别信息
  585. await foreach (var tempAbility in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{_oldStandard}") }))
  586. {
  587. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  588. }
  589. //删除册别
  590. if (abilityIds.IsNotEmpty())
  591. {
  592. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
  593. }
  594. List<string> abilityTaskIds = new List<string>(); //章节ID集合
  595. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{_oldStandard}") }))
  596. {
  597. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  598. }
  599. //删除章节
  600. if (abilityTaskIds.IsNotEmpty())
  601. {
  602. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
  603. }
  604. List<Task<ItemResponse<Ability>>> abilities = new List<Task<ItemResponse<Ability>>>(); //存储册别数据
  605. List<Task<ItemResponse<AbilityTask>>> abilityTasks = new List<Task<ItemResponse<AbilityTask>>>(); //存储章节
  606. //查询要复制区域的能力标准点
  607. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{_newStandard}") }))
  608. {
  609. if (!string.IsNullOrEmpty(item.blob))
  610. {
  611. item.blob = item.blob.Replace($"/{_newStandard}/", $"/{_oldStandard}/");
  612. };
  613. item.standard = $"{_oldStandard}";
  614. item.code = $"Ability-{_oldStandard}";
  615. item.school = $"{_oldStandard}";
  616. //添加区能力标准点
  617. abilities.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(item, new PartitionKey($"Ability-{_oldStandard}")));
  618. }
  619. try
  620. {
  621. if (abilities.Count < 256)
  622. {
  623. await Task.WhenAll(abilities);
  624. }
  625. else
  626. {
  627. int pages = (abilities.Count + 255) / 256;
  628. for (int i = 0; i < pages; i++)
  629. {
  630. List<Task<ItemResponse<Ability>>> tempAbility = abilities.Skip((i) * 256).Take(256).ToList();
  631. await Task.WhenAll(tempAbility);
  632. }
  633. }
  634. }
  635. catch
  636. {
  637. return Ok(new { state = 200, msg = "创区成功,能力标准点复制失败,遗留数据影响!" });
  638. }
  639. try
  640. {
  641. //微能力点
  642. await foreach (var atask in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{_newStandard}") }))
  643. {
  644. List<Tnode> tnodes = new();
  645. foreach (Tnode tnode in atask.children)
  646. {
  647. if (tnode.rnodes != null)
  648. {
  649. List<Rnode> rnodes = new();
  650. foreach (Rnode rnode in tnode.rnodes)
  651. {
  652. if (!string.IsNullOrEmpty($"{rnode.link}"))
  653. {
  654. rnode.link = rnode.link.Replace($"/{_newStandard}/", $"/{_oldStandard}/");
  655. }
  656. rnodes.Add(rnode);
  657. }
  658. tnode.rnodes = rnodes;
  659. }
  660. tnodes.Add(tnode);
  661. }
  662. atask.children = tnodes;
  663. atask.code = $"AbilityTask-{_oldStandard}";
  664. atask.standard = $"{_oldStandard}";
  665. atask.codeval = $"{_oldStandard}";
  666. ////添加区能力标准点中的节点
  667. //abilityTasks.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{_oldStandard}")));
  668. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{_oldStandard}"));
  669. }
  670. }
  671. catch
  672. {
  673. return Ok(new { state = 200, msg = "创区成功,能力标准创建成功,微能力点复制失败,遗留数据影响!" });
  674. }
  675. StandardFile saveFile = new();
  676. //新政策文件
  677. await foreach (StandardFile standardFile in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<StandardFile>(queryText: $"select value(c) from c where c.id='{_newId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StandardFile") }))
  678. {
  679. if (standardFile != null)
  680. {
  681. standardFile.standard = $"{_oldStandard}";
  682. standardFile.id = $"{_oldId}";
  683. saveFile = standardFile;
  684. }
  685. }
  686. StandardFile tempFile = new();
  687. try
  688. {
  689. tempFile = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<StandardFile>(saveFile.id, new PartitionKey("StandardFile"));
  690. }
  691. catch
  692. {
  693. }
  694. if (tempFile.id != null)
  695. {
  696. if (tempFile.id.Equals(saveFile.id))
  697. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReplaceItemAsync<StandardFile>(saveFile, saveFile.id, new PartitionKey("StandardFile")); //直接替换以前的数据
  698. else
  699. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(saveFile, new PartitionKey($"StandardFile")); // 需要删除原来的政策文件数据在进行添加
  700. }
  701. //新的区域设置
  702. AreaSetting saveSetting = new AreaSetting();
  703. await foreach (AreaSetting areaSetting in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: $"select value(c) from c where c.id='{_newId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  704. {
  705. if (areaSetting != null)
  706. {
  707. areaSetting.accessConfig = null;
  708. areaSetting.id = $"{_oldId}";
  709. saveSetting = areaSetting;
  710. }
  711. }
  712. AreaSetting tempSetting = new();
  713. try
  714. {
  715. tempSetting = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(saveSetting.id, new PartitionKey("StandardFile"));
  716. }
  717. catch
  718. {
  719. }
  720. if (tempSetting.id != null)
  721. {
  722. if (tempSetting.id.Equals(saveSetting.id))
  723. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReplaceItemAsync<AreaSetting>(saveSetting, saveSetting.id, new PartitionKey($"AreaSetting")); //直接替换以前的数据
  724. else
  725. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(saveSetting, new PartitionKey($"AreaSetting")); //需要删除原来的区域设置数据在进行添加
  726. }
  727. //发送消息分区键
  728. string partitionCode = "DelBeforeCopyAbility-mark";
  729. //执行复制操作
  730. BatchCopyFile batchCopyFile = new();
  731. batchCopyFile.blobCntr = "teammodelos";
  732. batchCopyFile.oldFileName = $"{_newStandard}";
  733. batchCopyFile.newFileName = $"{_oldStandard}";
  734. batchCopyFile.tmdid = $"{_tmdId}";
  735. batchCopyFile.tmdIds = new List<string> { $"{ _tmdId}" };
  736. batchCopyFile.codeKey = partitionCode;
  737. batchCopyFile.tmdName = $"{_tmdName}";
  738. var messageBatchCopyFile = new ServiceBusMessage(batchCopyFile.ToJsonString());
  739. messageBatchCopyFile.ApplicationProperties.Add("name", "CopyStandardFile");
  740. try
  741. {
  742. //await _serviceBus.GetServiceBusClient().SendMessageAsync(activeTask, messageBatchCopyFile); //先执行删除操作,在执行复制 单一
  743. await serBusClient.SendMessageAsync(activeTask, messageBatchCopyFile); //先执行删除操作,在执行复制
  744. }
  745. catch (Exception)
  746. {
  747. return Ok(new { state = 201 ,msg = "能力点复制成功,复制能力点的文件失败," });
  748. }
  749. //发送消息实体
  750. Notification notification = new()
  751. {
  752. hubName = "hita",
  753. type = "msg",
  754. from = $"BI:{_option.Location}:private",
  755. to = new List<string> { $"{ _tmdId}" },
  756. label = $"{partitionCode}_start",
  757. body = new { location = _option.Location, biz = partitionCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  758. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  759. };
  760. var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  761. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  762. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  763. var location = _option.Location;
  764. await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //发送站内发送消息
  765. //保存操作记录
  766. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "area-cut", $"{_tmdName}【{_tmdId}】已操作【{_oldStandard}】切换至{_newStandard}微能力点,复制标准:{_newStandard}", _dingDing, httpContext: HttpContext);
  767. return Ok(new { state = 200 });
  768. }
  769. catch (Exception ex)
  770. {
  771. await _dingDing.SendBotMsg($"BI,{_option.Location} batcharea/cut-standard \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  772. return BadRequest();
  773. }
  774. }
  775. /// <summary>
  776. /// 删除区域和区域的册别、能力点、区域文件、区域设置
  777. /// </summary>
  778. /// <param name="jsonElement"></param>
  779. /// <returns></returns>
  780. [ProducesDefaultResponseType]
  781. [HttpPost("del-area")]
  782. public async Task<IActionResult> DelArea(JsonElement jsonElement)
  783. {
  784. if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  785. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  786. jsonElement.TryGetProperty("site", out JsonElement site);
  787. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "teammodelos");
  788. var cosmosClient = _azureCosmos.GetCosmosClient();
  789. if ($"{site}".Equals(BIConst.Global))
  790. {
  791. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  792. blobClient = _azureStorage.GetBlobContainerClient(containerName: "teammodelos", BIConst.Global);
  793. }
  794. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{areaId}", new PartitionKey("Base-Area"));
  795. if (response.Status == 200)
  796. {
  797. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  798. Area area = json.ToObject<Area>();
  799. if (area.standard == $"{standard}")
  800. {
  801. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemAsync<Area>(area.id, new PartitionKey("Base-Area")); //删除区
  802. List<Teacher> teachers = new();
  803. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(queryText: $"SELECT distinct value(c) FROM c join a in c.areas join s in c.schools where a.areaId='{area.id}' or s.areaId='{area.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  804. {
  805. teachers.Add(item);
  806. }
  807. foreach (var item in teachers)
  808. {
  809. var tempArea = item.areas.Find(f => f.areaId.Equals(area.id));
  810. if (tempArea != null)
  811. {
  812. item.areas.Remove(tempArea);
  813. }
  814. item.schools.ForEach(fe => { if (fe.areaId.Equals(area.id)) fe.areaId = ""; });
  815. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
  816. }
  817. List<string> scIds = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{area.id}' and c.standard ='{area.standard}'", "Base");
  818. foreach (var item in scIds)
  819. {
  820. School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(item, new PartitionKey("Base"));
  821. school.areaId = "";
  822. school.standard = "";
  823. school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
  824. }
  825. List<string> abilityIds = new(); //册别的ID集合
  826. List<string> abilityTaskIds = new(); //章节ID集合
  827. //查询册别信息
  828. await foreach (var tempAbility in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{area.standard}") }))
  829. {
  830. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  831. }
  832. //删除册别
  833. if (abilityIds.IsNotEmpty())
  834. {
  835. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{area.standard}");
  836. }
  837. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
  838. {
  839. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  840. }
  841. //删除章节
  842. if (abilityTaskIds.IsNotEmpty())
  843. {
  844. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{standard}");
  845. }
  846. //区域政策文件
  847. StandardFile delFile = new();
  848. var responseFile = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync(area.id, new PartitionKey("StandardFile"));
  849. if(responseFile.Status == 200)
  850. {
  851. using var fileJson = await JsonDocument.ParseAsync(responseFile.ContentStream);
  852. delFile = fileJson.ToObject<StandardFile>();
  853. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemAsync<StandardFile>(delFile.id, new PartitionKey("StandardFile"));
  854. }
  855. //区域设置
  856. AreaSetting delSet = new();
  857. var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync(area.id, new PartitionKey("AreaSetting"));
  858. if (responseSet.Status == 200)
  859. {
  860. using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
  861. delSet = fileJson.ToObject<AreaSetting>();
  862. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemAsync<AreaSetting>(delSet.id, new PartitionKey("AreaSetting"));
  863. }
  864. List<object> fileobj = new();
  865. //先删除原有的文件
  866. List<Task<Response<bool>>> DelList = new();
  867. await foreach (BlobItem blobItem in blobClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"yxpt/{area.standard}/"))
  868. {
  869. fileobj.Add(blobItem.Name);
  870. DelList.Add(blobClient.GetBlobBaseClient(blobItem.Name).DeleteIfExistsAsync());
  871. }
  872. if (DelList.Count <= 256)
  873. {
  874. await Task.WhenAll(DelList);
  875. }
  876. else
  877. {
  878. int pages = (DelList.Count + 255) / 256;
  879. for (int i = 0; i < pages; i++)
  880. {
  881. List<Task<Response<bool>>> delList = DelList.Skip((i) * 256).Take(256).ToList();
  882. await Task.WhenAll(delList);
  883. }
  884. }
  885. return Ok(new { state = 200,area, scIds, abilityIds, abilityTaskIds, delFile, delSet, fileobj });
  886. }
  887. else return Ok(new { state = 400, msg = "id和standard不匹配!" });
  888. }
  889. else return Ok(new { state = 404,msg="依据Id未找到该区!" });
  890. }
  891. /// <summary>
  892. /// 区域列表
  893. /// </summary>
  894. public record RecArea
  895. {
  896. public string id { get; set; }
  897. public string code { get; set; }
  898. public string pk { get; set; }
  899. public string name { get; set; }
  900. public string provCode { get; set; }
  901. public string provName { get; set; }
  902. public string cityCode { get; set; }
  903. public string cityName { get; set; }
  904. public string standard { get; set; }
  905. public string standardName { get; set; }
  906. public string institution { get; set; }
  907. public int schoolCount { get; set; }
  908. public bool cutArea { get; set; } = false;
  909. public List<AreaQuoteRecord> aquoteRec { get; set; } = new List<AreaQuoteRecord>();
  910. }
  911. }
  912. }