BatchAreaController.cs 58 KB

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