InitialAreaController.cs 17 KB

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