InitialAreaController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.Options;
  5. using System.Net.Http;
  6. using TEAMModelOS.SDK.DI;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.Models;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.SDK.Context.Constant;
  12. using Azure.Messaging.ServiceBus;
  13. using TEAMModelBI.Tool.Extension;
  14. using TEAMModelOS.SDK.Extension;
  15. using Microsoft.AspNetCore.Hosting;
  16. using TEAMModelOS.SDK.DI.CoreAPI;
  17. using TEAMModelOS.SDK.Models;
  18. using Azure.Cosmos;
  19. using System;
  20. using System.Collections.Generic;
  21. using TEAMModelOS.SDK.Models.Cosmos.Common;
  22. using System.Linq;
  23. using Pipelines.Sockets.Unofficial.Arenas;
  24. using TEAMModelOS.SDK.Models.Cosmos.BI;
  25. using TEAMModelBI.Filter;
  26. using HTEXLib.COMM.Helpers;
  27. namespace TEAMModelBI.Controllers.RepairApi
  28. {
  29. [Route("initialarea")]
  30. [ApiController]
  31. public class InitialAreaController : ControllerBase
  32. {
  33. private readonly AzureCosmosFactory _azureCosmos;
  34. private readonly DingDing _dingDing;
  35. private readonly Option _option;
  36. private readonly AzureStorageFactory _azureStorage;
  37. private readonly IConfiguration _configuration;
  38. private readonly NotificationService _notificationService;
  39. private readonly AzureServiceBusFactory _serviceBus;
  40. private readonly IHttpClientFactory _http;
  41. private readonly CoreAPIHttpService _coreAPIHttpService;
  42. private readonly IWebHostEnvironment _environment; //读取文件
  43. public InitialAreaController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, NotificationService notificationService, AzureServiceBusFactory serviceBus, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService, IWebHostEnvironment hostingEnvironment)
  44. {
  45. _azureCosmos = azureCosmos;
  46. _dingDing = dingDing;
  47. _azureStorage = azureStorage;
  48. _option = option?.Value;
  49. _configuration = configuration;
  50. _notificationService = notificationService;
  51. _serviceBus = serviceBus;
  52. _http = http;
  53. _coreAPIHttpService = coreAPIHttpService;
  54. _environment = hostingEnvironment;
  55. }
  56. /// <summary>
  57. /// 创建完整版的学区初始化
  58. /// </summary>
  59. /// <param name="jsonElement"></param>
  60. /// <returns></returns>
  61. [ProducesDefaultResponseType]
  62. [HttpPost("create-full-version")]
  63. public async Task<IActionResult> CreateFullVersion(JsonElement jsonElement)
  64. {
  65. if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
  66. jsonElement.TryGetProperty("provCode", out JsonElement provCode);
  67. jsonElement.TryGetProperty("provName", out JsonElement provName);
  68. jsonElement.TryGetProperty("cityCode", out JsonElement cityCode);
  69. jsonElement.TryGetProperty("cityName", out JsonElement cityName);
  70. jsonElement.TryGetProperty("areaAdmin", out JsonElement areadAdmin);
  71. if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
  72. if (!jsonElement.TryGetProperty("standardName", out JsonElement standardName)) return BadRequest();
  73. jsonElement.TryGetProperty("institution", out JsonElement institution);
  74. jsonElement.TryGetProperty("oldStandard", out JsonElement oldStandard);
  75. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  76. List<CopyStandard> copyStand = new();
  77. if (!string.IsNullOrEmpty($"{oldStandard}"))
  78. copyStand = oldStandard.ToObject<List<CopyStandard>>();
  79. var cosmosClient = _azureCosmos.GetCosmosClient(); //数据库连接
  80. var tableClient = _azureStorage.GetCloudTableClient();
  81. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  82. ServiceBusClient serBusClient;
  83. try
  84. {
  85. serBusClient = _serviceBus.GetServiceBusClient();
  86. }
  87. catch
  88. {
  89. return Ok(new { state = 403, msg = "Functionn未启动,请联系管理员" });
  90. }
  91. var activeTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  92. var table = tableClient.GetTableReference("IESLogin");
  93. //查询新的是否存在
  94. 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") }))
  95. {
  96. if (item.standard.Equals($"{standard}"))
  97. return Ok(new { state = 1, message = "新创区的standard已存在请检查" });
  98. }
  99. //区级的ID
  100. string areaId = Guid.NewGuid().ToString();
  101. Area addArea = new()
  102. {
  103. id = areaId,
  104. code = $"Base-Area",
  105. name = $"{name}",
  106. provCode = $"{provCode}",
  107. provName = $"{provName}",
  108. cityCode = $"{cityCode}",
  109. cityName = $"{cityName}",
  110. standard = $"{standard}",
  111. standardName = $"{standardName}",
  112. institution = $"{institution}"
  113. };
  114. #region 区级管理员
  115. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{areadAdmin}" } }, _option.Location, _configuration);
  116. if (coreUser == null || coreUser.id == null)
  117. return Ok(new { state = 404, msg = "未找到改账户的管理员" });
  118. //string tmdId = !string.IsNullOrEmpty(tempTmdId) ? tempTmdId : $"{areadAdmin}";
  119. Teacher teacher = null;
  120. try
  121. {
  122. //查询该教师是否存在
  123. teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{coreUser.id}", new PartitionKey("Base"));
  124. }
  125. catch
  126. {
  127. }
  128. if (teacher != null)
  129. {
  130. //教师存在,在该教师信息中添加要管理的学校信息
  131. teacher.areas.Add(new Teacher.TeacherArea { areaId = addArea.id, status = "join", name = addArea.name });
  132. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  133. }
  134. else
  135. {
  136. teacher.id = coreUser.id;
  137. teacher.name = coreUser.name;
  138. teacher.picture = coreUser.picture;
  139. teacher.pk = "Base";
  140. teacher.code = "Base";
  141. teacher.size = 1;
  142. teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  143. //教师存在,在该教师信息中添加要管理的学校信息
  144. teacher.areas.Add(new Teacher.TeacherArea { areaId = addArea.id, status = "join", name = addArea.name });
  145. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  146. }
  147. #endregion
  148. //创建区域
  149. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync<Area>(addArea, new PartitionKey("Base-Area"));
  150. //消息分区键
  151. string partitionCode = "copyAbility-mark";
  152. #region 复制微能力点到新区
  153. List<Task<ItemResponse<Ability>>> abilities = new(); //存储区域数据
  154. List<Task<ItemResponse<AbilityTask>>> abilityTasks = new(); //存储章节
  155. Area AreaS2 = null;
  156. List<Area> areas = new();
  157. await foreach (var itemArea 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") }))
  158. {
  159. areas.Add(itemArea);
  160. AreaS2 = itemArea;
  161. }
  162. await foreach (var itemArea in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Area>(queryText: $"select value(c) from c where c.standard='standard3'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  163. {
  164. areas.Add(itemArea);
  165. }
  166. foreach (var area in areas)
  167. {
  168. //查询要复制区域的能力标准点
  169. 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}") }))
  170. {
  171. if (!string.IsNullOrEmpty(item.blob))
  172. {
  173. item.blob = item.blob.Replace($"/{area.standard}/", $"/{standard}/");
  174. };
  175. item.standard = $"{standard}";
  176. item.code = $"Ability-{standard}";
  177. item.school = $"{standard}";
  178. //添加区能力标准点
  179. abilities.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(item, new PartitionKey($"Ability-{standard}")));
  180. }
  181. try
  182. {
  183. if (abilities.Count < 256)
  184. {
  185. await Task.WhenAll(abilities);
  186. }
  187. else
  188. {
  189. int pages = (abilities.Count + 255) / 256;
  190. for (int i = 0; i < pages; i++)
  191. {
  192. List<Task<ItemResponse<Ability>>> tempAbility = abilities.Skip((i) * 256).Take(256).ToList();
  193. await Task.WhenAll(tempAbility);
  194. }
  195. }
  196. }
  197. catch
  198. {
  199. return Ok(new { state = 200, msg = "创区成功,能力标准点复制失败,遗留数据影响!" });
  200. }
  201. try
  202. {
  203. //微能力点
  204. 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}") }))
  205. {
  206. List<Tnode> tnodes = new();
  207. foreach (Tnode tnode in atask.children)
  208. {
  209. if (tnode.rnodes != null)
  210. {
  211. List<Rnode> rnodes = new List<Rnode>();
  212. foreach (Rnode rnode in tnode.rnodes)
  213. {
  214. if (!string.IsNullOrEmpty($"{rnode.link}"))
  215. {
  216. rnode.link = rnode.link.Replace($"/{area.standard}/", $"/{standard}/");
  217. }
  218. rnodes.Add(rnode);
  219. }
  220. tnode.rnodes = rnodes;
  221. }
  222. tnodes.Add(tnode);
  223. }
  224. atask.children = tnodes;
  225. atask.code = $"AbilityTask-{standard}";
  226. atask.standard = $"{standard}";
  227. atask.codeval = $"{standard}";
  228. //添加区能力标准点中的节点
  229. //abilityTasks.Add(cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}")));
  230. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(atask, new PartitionKey($"AbilityTask-{standard}"));
  231. }
  232. }
  233. catch
  234. {
  235. return Ok(new { state = 200, msg = "创区成功,能力标准创建成功,微能力点复制失败,遗留数据影响!" });
  236. }
  237. //执行复制操作
  238. BatchCopyFile batchCopyFile = new();
  239. batchCopyFile.blobCntr = "teammodelos";
  240. batchCopyFile.oldFileName = $"{area.standard}";
  241. batchCopyFile.newFileName = $"{standard}";
  242. batchCopyFile.tmdid = $"{_tmdId}";
  243. batchCopyFile.tmdIds = new List<string> { $"{_tmdId}" };
  244. batchCopyFile.codeKey = partitionCode;
  245. batchCopyFile.tmdName = $"{_tmdName}";
  246. var messageBatchCopyFile = new ServiceBusMessage(batchCopyFile.ToJsonString());
  247. messageBatchCopyFile.ApplicationProperties.Add("name", "CopyStandardFile");
  248. //var activeTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  249. try
  250. {
  251. await _serviceBus.GetServiceBusClient().SendMessageAsync(activeTask, messageBatchCopyFile);
  252. await serBusClient.SendMessageAsync(activeTask, messageBatchCopyFile);
  253. }
  254. catch (Exception)
  255. {
  256. return Ok(new { state = 201, msg = "能力点复制成功,复制能力点的文件失败," });
  257. }
  258. //发送消息实体
  259. Notification notification = new()
  260. {
  261. hubName = "hita",
  262. type = "msg",
  263. from = $"BI:{_option.Location}:private",
  264. to = new List<string> { $"{_tmdId}" },
  265. label = $"{partitionCode}_start",
  266. body = new { location = _option.Location, biz = partitionCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
  267. expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
  268. };
  269. var notiUrl = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
  270. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  271. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  272. var location = _option.Location;
  273. await _notificationService.SendNotification(clientID, clientSecret, location, notiUrl, notification); //站内发送消息
  274. }
  275. if (AreaS2 != null)
  276. {
  277. //新政策文件
  278. await foreach (StandardFile standardFile in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<StandardFile>(queryText: $"select value(c) from c where c.id='{AreaS2.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StandardFile") }))
  279. {
  280. if (standardFile != null)
  281. {
  282. standardFile.standard = $"{standard}";
  283. standardFile.id = areaId;
  284. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(standardFile, new PartitionKey($"StandardFile"));
  285. }
  286. }
  287. //新的区域设置
  288. await foreach (AreaSetting areaSetting in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AreaSetting>(queryText: $"select value(c) from c where c.id='{AreaS2.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
  289. {
  290. if (areaSetting != null)
  291. {
  292. areaSetting.accessConfig = null;
  293. areaSetting.id = areaId;
  294. await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").CreateItemAsync(areaSetting, new PartitionKey($"AreaSetting"));
  295. }
  296. }
  297. }
  298. else return Ok(new { state = 201, message = "未找到默认能力点!" });
  299. #endregion
  300. return Ok(new { sate = RespondCode.Ok });
  301. }
  302. public record CopyStandard
  303. {
  304. public string id { get; set; }
  305. public string standard { get; set; }
  306. public string name { get; set; }
  307. }
  308. }
  309. }