BatchAreaController.cs 58 KB

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