SchoolService.cs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  1. using Azure.Cosmos;
  2. using Azure.Storage.Blobs.Models;
  3. using DocumentFormat.OpenXml.Bibliography;
  4. using DocumentFormat.OpenXml.Drawing.Charts;
  5. using HTEXLib.COMM.Helpers;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Hosting;
  9. using Microsoft.International.Converters.PinYinConverter;
  10. using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Configuration;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Text.RegularExpressions;
  19. using System.Threading.Tasks;
  20. using TEAMModelOS.Models;
  21. using TEAMModelOS.SDK.DI;
  22. using TEAMModelOS.SDK.Extension;
  23. using TEAMModelOS.SDK.Models;
  24. using Period = TEAMModelOS.SDK.Models.Period;
  25. namespace TEAMModelOS.SDK
  26. {
  27. public class SchoolService
  28. {
  29. public static async Task<(int code, string msg, object data)> JoinScool(string school, string id, string name, string picture, long ts,
  30. AzureCosmosFactory _azureCosmos,AzureStorageFactory _azureStorage,CoreAPIHttpService _coreAPIHttpService,DingDing _dingDing,Option _option,IConfiguration _configuration, IWebHostEnvironment _environment)
  31. {
  32. SchoolTeacher schoolTeacher = null;
  33. School schoolInfo = null;
  34. long nowTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  35. try
  36. {
  37. if (nowTime - ts > 3600000)
  38. {
  39. return (1, "超时!", null);
  40. }
  41. var client = _azureCosmos.GetCosmosClient();
  42. try
  43. {
  44. schoolInfo = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{school}", new PartitionKey("Base"));
  45. }
  46. catch (CosmosException ex)
  47. {
  48. if (ex.Status == 404)
  49. {
  50. return (2, "该学校不存在!", null);
  51. }
  52. }
  53. Teacher teacher = null;
  54. try
  55. {
  56. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{id}", new PartitionKey("Base"));
  57. var sch = teacher.schools.Find(x => x.schoolId.Equals($"{school}"));
  58. if (sch != null)
  59. {
  60. if (sch.status.Equals("join"))
  61. {
  62. return (3, "该教师之前已经加入学校!", null);
  63. }
  64. else
  65. {
  66. sch.status = "join";
  67. sch.time = nowTime;
  68. sch.name = schoolInfo?.name;
  69. sch.picture = schoolInfo?.picture;
  70. sch.areaId = schoolInfo?.areaId;
  71. }
  72. }
  73. else
  74. {
  75. teacher.schools.Add(new Teacher.TeacherSchool { areaId = schoolInfo?.areaId, schoolId = schoolInfo.id, status = "join", name = schoolInfo.name, picture = schoolInfo.picture, time = nowTime });
  76. }
  77. if (teacher.size < 2)
  78. {
  79. teacher.size = 2;
  80. }
  81. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey($"Base"));
  82. }
  83. catch (CosmosException ex)
  84. {
  85. if (ex.Status == 404)
  86. {
  87. //如果沒有,則初始化Teacher基本資料到Cosmos
  88. teacher = new Teacher
  89. {
  90. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  91. id = id,
  92. pk = "Base",
  93. code = "Base",
  94. name = name?.ToString(),
  95. // picture = picture?.ToString(),
  96. //创建账号并第一次登录IES5则默认赠送1G
  97. defaultSchool = null,
  98. size = 2,
  99. schools = new List<Teacher.TeacherSchool>() { new Teacher.TeacherSchool { areaId = schoolInfo?.areaId, schoolId = schoolInfo.id, status = "join", name = schoolInfo.name, picture = schoolInfo.picture, time = nowTime } }
  100. };
  101. var container = _azureStorage.GetBlobContainerClient(id);
  102. await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
  103. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  104. }
  105. }
  106. Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{schoolInfo.id}"));
  107. if (response.Status != 200)
  108. {
  109. schoolTeacher = new SchoolTeacher
  110. {
  111. id = teacher.id,
  112. pk = "Teacher",
  113. name = teacher.name,
  114. picture = teacher.picture,
  115. size = 0,
  116. roles = new List<string> { "teacher" },
  117. permissions = new List<string>(),
  118. status = "join",
  119. createTime = nowTime,
  120. code = $"Teacher-{schoolInfo.id}",
  121. ttl = -1
  122. };
  123. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{schoolInfo.id}"));
  124. }
  125. else
  126. {
  127. JsonElement data = JsonDocument.Parse(response.ContentStream).RootElement;
  128. schoolTeacher = data.ToObject<SchoolTeacher>();
  129. schoolTeacher.status = "join";
  130. schoolTeacher.name = schoolInfo.name;
  131. schoolTeacher.picture = schoolInfo.picture;
  132. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{schoolInfo.id}"));
  133. }
  134. //通知管理员
  135. string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
  136. List<string> ids = new List<string>();
  137. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
  138. requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
  139. {
  140. ids.Add(item);
  141. }
  142. string bizcode = "scan-join";
  143. string tsql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
  144. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  145. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  146. .GetItemQueryIterator<IdNameCode>(queryText: tsql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  147. {
  148. idNameCodes.Add(item);
  149. }
  150. _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
  151. new Dictionary<string, object> { { "tmdname", teacher.name }, { "schoolName", schoolInfo.name }, { "schoolId", $"{school}" }, { "tmdid", teacher.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  152. }
  153. catch (Exception ae)
  154. {
  155. await _dingDing.SendBotMsg($"HiTA扫码加入学校失败!{ae.Message},{ae.StackTrace}", GroupNames.成都开发測試群組);
  156. }
  157. return (200, "ok", new { schoolTeacher.roles, schoolTeacher.status, school = $"{school}", schoolInfo.name, schoolInfo.picture });
  158. }
  159. /// <summary>
  160. /// 根据年级获取入学年
  161. /// </summary>
  162. /// <param name="semesterList"></param>
  163. /// <returns></returns>
  164. public static (List<KeyValuePair<int, int>> gradeYear, HashSet<int> years) GetYears(School school, string periodId, IEnumerable<int> grades, long time = 0) {
  165. var date = DateTimeOffset.UtcNow;
  166. //2001-09-09 09:46:40
  167. if (time > 1000000000000)
  168. {
  169. date = DateTimeOffset.FromUnixTimeMilliseconds(time);
  170. }
  171. //年级算法
  172. var period = school.period.Find(x => x.id.Equals(periodId));
  173. int Day = date.Day;
  174. int Month = date.Month;
  175. int Year = date.Year;
  176. int start = int.Parse($"{Year}0901");
  177. var se = period.semesters.Find(x => x.start == 1);
  178. if (se == null)
  179. {
  180. se = period.semesters.First();
  181. }
  182. string sm = "09";
  183. string sd = "01";
  184. if (se != null)
  185. {
  186. sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  187. sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  188. start = int.Parse($"{Year}{sm}{sd}");
  189. }
  190. int curr = int.Parse(date.ToString("yyyyMMdd"));
  191. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  192. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  193. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  194. int dis = start - curr;
  195. List<int > years= new List<int>();
  196. List<KeyValuePair<int, int>> gradeYear = new List<KeyValuePair<int, int>>();
  197. foreach (int grade in grades) {
  198. int year = 0;
  199. if (dis > 0)
  200. {
  201. year = Year - grade -1;
  202. }
  203. else {
  204. year= Year - grade ;
  205. }
  206. years.Add(year);
  207. gradeYear.Add(new KeyValuePair<int, int>(grade,year ));
  208. }
  209. return (gradeYear,years.ToHashSet());
  210. }
  211. /// <summary>
  212. /// 根据年份获取年级,只返回time 或当前时间以前入学的学生年级。
  213. /// </summary>
  214. /// <param name="semesterList"></param>
  215. /// <returns></returns>
  216. public static (List<KeyValuePair<int, string>> yearGrade,HashSet<string> grades) GetGrades(School school,string periodId , IEnumerable<int> years,long time =0) {
  217. var date = DateTimeOffset.UtcNow;
  218. //2001-09-09 09:46:40
  219. if (time > 1000000000000) {
  220. date = DateTimeOffset.FromUnixTimeMilliseconds(time);
  221. }
  222. //年级算法
  223. var period = school.period.Find(x => x.id.Equals(periodId));
  224. int? Count = period?.grades?.Count;
  225. List<KeyValuePair<int, string>> yearGrades = new List<KeyValuePair<int, string>>();
  226. if (Count.HasValue)
  227. {
  228. int Day = date.Day;
  229. int Month = date.Month;
  230. int Year = date.Year;
  231. int start = int.Parse($"{Year}0901");
  232. var se = period.semesters.Find(x => x.start == 1);
  233. if (se == null)
  234. {
  235. se = period.semesters.First();
  236. }
  237. string sm = "09";
  238. string sd = "01";
  239. if (se != null)
  240. {
  241. sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  242. sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  243. start = int.Parse($"{Year}{sm}{sd}");
  244. }
  245. int curr = int.Parse(date.ToString("yyyyMMdd"));
  246. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  247. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 1 则当前20221203是2022年入学的,
  248. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  249. int dis = start - curr;
  250. foreach (int year in years)
  251. {
  252. if (int.Parse($"{year}{sm}{sd}") < curr) {
  253. int grade;
  254. if (dis > 0)
  255. {
  256. grade = Math.Abs((Year - year - 1)) % Count.Value;
  257. }
  258. else
  259. {
  260. grade = Math.Abs((Year - year)) % Count.Value;
  261. }
  262. yearGrades.Add(new KeyValuePair<int, string>(year, $"{grade}"));
  263. }
  264. }
  265. }
  266. return (yearGrades, yearGrades.Select(z=>z.Value).ToHashSet());
  267. }
  268. /// <summary>
  269. /// 根据指定时间或者当前时间获取学期信息
  270. /// </summary>
  271. /// <param name="semesterList"></param>
  272. /// <returns></returns>
  273. public static (Semester currSemester, int studyYear, DateTimeOffset date, DateTimeOffset nextSemester) GetSemester( Period period, long timestamp = 0, string time =null) {
  274. //string time = "2023/05-11";
  275. DateTimeOffset date = default;
  276. if (timestamp > 1000000000) {
  277. //毫秒级
  278. if (timestamp > 1000000000000)
  279. {
  280. date = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
  281. }
  282. //秒级
  283. else {
  284. date = DateTimeOffset.FromUnixTimeSeconds(timestamp);
  285. }
  286. }
  287. if (!(!string.IsNullOrWhiteSpace(time) && DateTimeOffset.TryParse(time, out date)))
  288. {
  289. //date = DateTimeOffset.FromUnixTimeSeconds(1672506061);
  290. //date = DateTimeOffset.UtcNow;
  291. date = DateTimeOffset.FromUnixTimeSeconds(1662688000);
  292. }
  293. //年级算法
  294. //var period = school.period.Find(x => x.id.Equals(periodId));
  295. List<KeyValuePair<int, string>> yearGrades = new List<KeyValuePair<int, string>>();
  296. int Day = date.Day;
  297. int Month = date.Month;
  298. int Year = date.Year;
  299. string sm = "09";
  300. string sd = "01";
  301. int start = int.Parse($"{Year}{sm}{sd}");
  302. var se = period.semesters.Find(x => x.start == 1);
  303. if (se == null)
  304. {
  305. se = period.semesters.First();
  306. }
  307. if (se != null)
  308. {
  309. sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  310. sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  311. start = int.Parse($"{Year}{sm}{sd}");
  312. }
  313. int curr = int.Parse(date.ToString("yyyyMMdd"));
  314. //新学年开学时间大于当前时间,计算年级需要减1 20220901-20220408 > 0 则当前20220408是2021年入学的,
  315. //当前时间大于新学年开学时间,计算年级则不需要 20220901-20221203 < 0 则当前20221203是2022年入学的,
  316. //20230901-20230101 > 0 则当前20230101是2022年入学的,
  317. int dis = start - curr;
  318. //学年
  319. int studyYear= date.Year;
  320. if (dis > 0)
  321. {
  322. studyYear = Year - 1;
  323. }
  324. else
  325. {
  326. studyYear = Year;
  327. }
  328. Semester semester= null;
  329. //当前学期的下一个学期,默认加180天
  330. DateTimeOffset nextSemester = date.AddDays(180);
  331. var sortSemesters= SortSemester(period.semesters);
  332. int len = sortSemesters.Count;
  333. for (int i = 0; i < len; i++) {
  334. int next= i + 1;
  335. if (next>= len)
  336. {
  337. semester = sortSemesters[i];
  338. nextSemester = DateTimeOffset.Parse($"{studyYear+1}/{sortSemesters[0].month}/{sortSemesters[0].day}");
  339. break;
  340. }
  341. else {
  342. var fdate= DateTimeOffset.Parse($"{studyYear}/{sortSemesters[i].month}/{sortSemesters[i].day}");
  343. long lf = fdate.ToUnixTimeSeconds();
  344. var ndate = DateTimeOffset.Parse($"{studyYear}/{sortSemesters[next].month}/{sortSemesters[next].day}");
  345. long ln = ndate.ToUnixTimeSeconds();
  346. //代表有跨年
  347. if (lf > ln) {
  348. ndate = DateTimeOffset.Parse($"{studyYear+1}/{sortSemesters[next].month}/{sortSemesters[next].day}");
  349. ln = ndate.ToUnixTimeSeconds();
  350. }
  351. var cdate = DateTimeOffset.Parse($"{Year}/{Month}/{Day}");
  352. long lc = fdate.ToUnixTimeSeconds();
  353. if (lc >= lf && lc < ln) {
  354. semester = sortSemesters[i];
  355. nextSemester = DateTimeOffset.Parse($"{studyYear}/{sortSemesters[next].month}/{sortSemesters[next].day}");
  356. //nextSemester = sortSemesters[next];
  357. break;
  358. }
  359. //if (sortSemesters[i].month <=Month && sortSemesters[i].day >= Day && sortSemesters[next].month < Month && sortSemesters[next].day < Day)
  360. //{
  361. // semester = sortSemesters[i];
  362. // nextSemester = DateTimeOffset.Parse($"{studyYear}/{sortSemesters[next].month}/{sortSemesters[next].day}");
  363. // break;
  364. //}
  365. }
  366. }
  367. return (semester,studyYear,date, nextSemester);
  368. }
  369. /// <summary>
  370. /// 处理学期排序
  371. /// </summary>
  372. /// <param name="semesterList"></param>
  373. /// <returns></returns>
  374. public static List<Semester> SortSemester(List<Semester> semesterList)
  375. {
  376. int Year = DateTimeOffset.UtcNow.Year;
  377. List<KeyValuePair<int, Semester>> pairs = new List<KeyValuePair<int, Semester>>();
  378. semesterList.ForEach(se => {
  379. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  380. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  381. int order = int.Parse($"{Year}{sm}{sd}");
  382. pairs.Add(new KeyValuePair<int, Semester>(order, se));
  383. });
  384. var orderPairs = pairs.OrderBy(z => z.Key);
  385. semesterList = orderPairs.Select(z => z.Value).ToList();
  386. int startIndex = semesterList.FindIndex(z => z.start == 1);
  387. if (startIndex == -1)
  388. {
  389. //未设置学期的情况默认9月份开始的。
  390. startIndex = semesterList.FindIndex(z => z.month == 9);
  391. //如果还未找到,就以排序结果为准
  392. if (startIndex == -1)
  393. {
  394. startIndex = 0;
  395. }
  396. }
  397. if (startIndex > 0)
  398. {
  399. List<Semester> before = semesterList.Take(startIndex).ToList();
  400. List<Semester> after = semesterList.Skip(startIndex).ToList();
  401. semesterList = new List<Semester>();
  402. semesterList.AddRange(after);
  403. semesterList.AddRange(before);
  404. return semesterList;
  405. }
  406. else
  407. {
  408. return semesterList;
  409. }
  410. }
  411. /// <summary>
  412. /// 校验
  413. /// </summary>
  414. /// <param name="courseTaskInsert"></param>
  415. public static ScheduleTaskDto CheckCourseTask(string scope, ScheduleTaskDto courseTaskInsert, string school, List<GroupListDto> groupListDtos, List<Room> rooms,
  416. List<SchoolTeacher> schoolTeachers, List<Teacher> teachers)
  417. {
  418. if (scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  419. {
  420. //教师
  421. var schoolteachers = schoolTeachers.Where(z => z.id.Equals(courseTaskInsert.teacherId));
  422. if (!schoolteachers.Any())
  423. {
  424. courseTaskInsert.invalidCode = 2;//教师不存在
  425. return courseTaskInsert;
  426. }
  427. var invalidAssistants= courseTaskInsert.assistants.Except(schoolTeachers.Select(x => x.id));
  428. if (invalidAssistants != null && invalidAssistants.Any())
  429. {
  430. courseTaskInsert.invalidCode = 21;
  431. courseTaskInsert.invalidMsg = $"{string.Join(",", invalidAssistants)}";
  432. return courseTaskInsert;
  433. }
  434. }
  435. else
  436. {
  437. //教师
  438. var teachersbase = teachers.Where(z => z.id.Equals(courseTaskInsert.teacherId));
  439. if (!teachersbase.Any())
  440. {
  441. courseTaskInsert.invalidCode = 2;//教师不存在
  442. return courseTaskInsert;
  443. }
  444. var invalidAssistants = courseTaskInsert.assistants.Except(teachers.Select(x => x.id));
  445. if (invalidAssistants != null && invalidAssistants.Any())
  446. {
  447. courseTaskInsert.invalidCode = 21;
  448. courseTaskInsert.invalidMsg = $"{string.Join(",", invalidAssistants)}";
  449. return courseTaskInsert;
  450. }
  451. }
  452. //名单
  453. var groupList = groupListDtos.Where(z => z.id.Equals(courseTaskInsert.groupId) && z.type.Equals(courseTaskInsert.type));
  454. if (!groupList.Any())
  455. {
  456. courseTaskInsert.invalidCode = 3;//名单不存在
  457. return courseTaskInsert;
  458. }
  459. else
  460. {
  461. if (scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  462. {
  463. if (!groupList.First().scope.Equals("private", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(school) && school.Equals(groupList.First().school))
  464. {
  465. courseTaskInsert.school = school;
  466. }
  467. }
  468. else
  469. {
  470. courseTaskInsert.school = school;
  471. }
  472. }
  473. //教室
  474. if (!string.IsNullOrWhiteSpace(courseTaskInsert.roomId))
  475. {
  476. var room = rooms.Where(z => z.id.Equals(courseTaskInsert.roomId));
  477. if (!room.Any())
  478. {
  479. courseTaskInsert.invalidCode = 4;//教室不存在
  480. return courseTaskInsert;
  481. }
  482. }
  483. courseTaskInsert.invalidCode = 0;
  484. return courseTaskInsert;
  485. }
  486. /// <summary>
  487. /// 校验
  488. /// </summary>
  489. /// <param name="courseTaskInsert"></param>
  490. public static CourseTaskChanged CheckCourseTaskInsertOrChanged(string grant_type, string scope , CourseTaskChanged courseTaskInsert,string school,Period period, List<CourseBase> courseBases, List<GroupListDto> groupListDtos, List<Room> rooms,
  491. List<SchoolTeacher> schoolTeachers,List<Teacher> teachers)
  492. {
  493. if (scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  494. { //学年
  495. if (courseTaskInsert.year < 2000)
  496. {
  497. courseTaskInsert.invalidCode = 17;//学年应大于2000
  498. return courseTaskInsert;
  499. }
  500. //学期
  501. var semester = period.semesters.Where(z => z.id.Equals(courseTaskInsert.semesterId));
  502. if (!semester.Any())
  503. {
  504. courseTaskInsert.invalidCode = 16;//学期不存在
  505. return courseTaskInsert;
  506. }
  507. //教师
  508. var schoolteachers = schoolTeachers.Where(z => z.id.Equals(courseTaskInsert.teacherId));
  509. if (!schoolteachers.Any())
  510. {
  511. courseTaskInsert.invalidCode = 2;//教师不存在
  512. return courseTaskInsert;
  513. }
  514. }
  515. else {
  516. //教师
  517. var teachersbase = teachers.Where(z => z.id.Equals(courseTaskInsert.teacherId));
  518. if (!teachersbase.Any())
  519. {
  520. courseTaskInsert.invalidCode = 2;//教师不存在
  521. return courseTaskInsert;
  522. }
  523. }
  524. //课程
  525. var courseBase = courseBases.Where(z => z.id.Equals(courseTaskInsert.courseId));
  526. if (!courseBase.Any())
  527. {
  528. courseTaskInsert.invalidCode = 1;//课程不存在
  529. return courseTaskInsert;
  530. }
  531. //名单
  532. var groupList = groupListDtos.Where(z => z.id.Equals(courseTaskInsert.groupId) && z.type.Equals(courseTaskInsert.type));
  533. if (!groupList.Any())
  534. {
  535. courseTaskInsert.invalidCode = 3;//名单不存在
  536. return courseTaskInsert;
  537. }
  538. else {
  539. if (scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  540. {
  541. if (!groupList.First().scope.Equals("private", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(school) && school.Equals(groupList.First().school))
  542. {
  543. courseTaskInsert.school = school;
  544. }
  545. }
  546. else {
  547. courseTaskInsert.school = school;
  548. }
  549. }
  550. //教室
  551. if (!string.IsNullOrWhiteSpace(courseTaskInsert.roomId))
  552. {
  553. var room = rooms.Where(z => z.id.Equals(courseTaskInsert.roomId));
  554. if (!room.Any())
  555. {
  556. courseTaskInsert.invalidCode = 4;//教室不存在
  557. return courseTaskInsert;
  558. }
  559. }
  560. if (grant_type.Equals("change-scheduleTask", StringComparison.OrdinalIgnoreCase)) {
  561. if (!string.IsNullOrWhiteSpace(courseTaskInsert.teacherIdChanged) || (!string.IsNullOrWhiteSpace(courseTaskInsert.groupIdChanged) && !string.IsNullOrWhiteSpace(courseTaskInsert.typeChanged)))
  562. {
  563. if (!string.IsNullOrWhiteSpace(courseTaskInsert.teacherIdChanged)) {
  564. if (scope.Equals("school", StringComparison.OrdinalIgnoreCase))
  565. {
  566. //教师
  567. var schoolteachers = schoolTeachers.Where(z => z.id.Equals(courseTaskInsert.teacherIdChanged));
  568. if (!schoolteachers.Any())
  569. {
  570. courseTaskInsert.invalidCode = 19;//教师不存在
  571. return courseTaskInsert;
  572. }
  573. }
  574. else {
  575. //教师
  576. var teachersbase = teachers.Where(z => z.id.Equals(courseTaskInsert.teacherIdChanged));
  577. if (!teachersbase.Any())
  578. {
  579. courseTaskInsert.invalidCode = 19;//教师不存在
  580. return courseTaskInsert;
  581. }
  582. }
  583. }
  584. if (!string.IsNullOrWhiteSpace(courseTaskInsert.groupIdChanged) && !string.IsNullOrWhiteSpace(courseTaskInsert.typeChanged)) {
  585. //名单
  586. var groupListChanged = groupListDtos.Where(z => z.id.Equals(courseTaskInsert.groupIdChanged) && z.type.Equals(courseTaskInsert.typeChanged));
  587. if (!groupListChanged.Any())
  588. {
  589. courseTaskInsert.invalidCode = 18;//名单不存在
  590. return courseTaskInsert;
  591. }
  592. else
  593. {
  594. if (scope.Equals("private", StringComparison.OrdinalIgnoreCase))
  595. {
  596. if (!groupListChanged.First().scope.Equals("private", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(school) && school.Equals(groupList.First().school))
  597. {
  598. courseTaskInsert.school = school;
  599. }
  600. }
  601. else
  602. {
  603. courseTaskInsert.school = school;
  604. }
  605. }
  606. }
  607. }
  608. else {
  609. courseTaskInsert.invalidCode = 17;
  610. }
  611. }
  612. courseTaskInsert.invalidCode = 0;
  613. return courseTaskInsert;
  614. }
  615. public static async Task<(List<Class> school_classes, List<Class> graduate_classes)> DoGraduateClasses(HttpTrigger _httpTrigger, AzureCosmosFactory _azureCosmos, List<string> periodIds, School school_base, Option _option,DingDing _dingDing, int waite = 0) {
  616. List<Class> school_classes = new List<Class>();
  617. List<Class> graduate_classes = new List<Class>();
  618. try
  619. {
  620. var client = _azureCosmos.GetCosmosClient();
  621. //取得班级
  622. int nowYear = DateTimeOffset.UtcNow.Year;
  623. int nowMonth = DateTimeOffset.UtcNow.Month;
  624. int nowDay = DateTimeOffset.UtcNow.Day;
  625. //因为修改年级,而导致取消的
  626. List<Class> cancel_graduate_classes = new List<Class>();
  627. string sql = $"SELECT value c FROM c where (c.graduate = 0 or IS_DEFINED(c.graduate) = false) ";
  628. if (periodIds.IsNotEmpty())
  629. {
  630. sql = $"SELECT value c FROM c where c.periodId in ({string.Join(",", periodIds.Select(x => $"'{x}'"))}) ";
  631. }
  632. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Class>
  633. //(queryText: $"SELECT value c FROM c where (c.graduate = 0 or IS_DEFINED(c.graduate) = false)",
  634. (queryText: sql,
  635. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school_base.id}") }))
  636. {
  637. bool isgraduate = false;
  638. if (!string.IsNullOrWhiteSpace(item.periodId))
  639. {
  640. var period = school_base.period.Find(x => x.id.Equals(item.periodId));
  641. if (period != null)
  642. {
  643. var gradeCount = period.grades.Count();
  644. //2022-2016=6(待判断月份日期是否是毕业) 2022-2017=5(未毕业)
  645. if (nowYear - item.year > gradeCount)
  646. {
  647. isgraduate = true;
  648. }
  649. else if (nowYear - item.year == gradeCount)
  650. {
  651. var semester = period.semesters.Find(x => x.start == 1);
  652. if (semester != null)
  653. {
  654. if (nowMonth > semester.month)
  655. {
  656. isgraduate = true;
  657. }
  658. else if (nowMonth == semester.month)
  659. {
  660. if (nowDay >= semester.day)
  661. {
  662. isgraduate = true;
  663. }
  664. else
  665. {
  666. }
  667. }
  668. else { isgraduate = false; }
  669. }
  670. }
  671. else
  672. {
  673. isgraduate = false;
  674. }
  675. }
  676. }
  677. if (isgraduate)
  678. {
  679. graduate_classes.Add(item);
  680. }
  681. else
  682. {
  683. if (item.graduate == 1)
  684. {
  685. item.graduate = 0;
  686. cancel_graduate_classes.Add(item);
  687. }
  688. school_classes.Add(item);
  689. }
  690. }
  691. if (graduate_classes.Any() || cancel_graduate_classes.Any())
  692. {
  693. if (waite == 0)
  694. {
  695. _ = _httpTrigger.RequestHttpTrigger(new { graduate_classes = graduate_classes, cancel_graduate_classes = cancel_graduate_classes, schoolId = $"{school_base.id}" }, _option.Location, "graduate-change");
  696. }
  697. else
  698. {
  699. await _httpTrigger.RequestHttpTrigger(new { graduate_classes = graduate_classes, cancel_graduate_classes = cancel_graduate_classes, schoolId = $"{school_base.id}" }, _option.Location, "graduate-change");
  700. }
  701. }
  702. } catch (Exception ex) {
  703. await _dingDing.SendBotMsg($"{_option.Location},{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  704. }
  705. return (school_classes,graduate_classes);
  706. }
  707. public static async Task<object> DoScsApiSchool(HttpTrigger _httpTrigger,Dictionary<string,object> dict, Option _option, List<IdNameCode> ignore,
  708. string areaId,string city,string dist, AzureStorageFactory _azureStorage ,DingDing _dingDing, IWebHostEnvironment _environment
  709. )
  710. {
  711. List<ScSchool> tbschools = null;
  712. List<ScSchool> matchSchools = null;
  713. List<ScSchool> schools = null;
  714. List<ScSchool> saveschools = null;
  715. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  716. // 5.3.1.18根据机构ID、项目ID、子项目ID返回学校列表
  717. ( int status, string json) = await _httpTrigger.RequestHttpTrigger(dict, _option.Location, "GetSchoolList");
  718. if (status == 200)
  719. {
  720. schools = json.ToObject<List<ScSchool>>(new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
  721. if (ignore.IsNotEmpty())
  722. {
  723. matchSchools = schools.FindAll(x => ignore.Select(y => y.name).Contains(x.schoolname));
  724. if (matchSchools.IsNotEmpty())
  725. {
  726. if (matchSchools.Count != ignore.Count)
  727. {
  728. var matched = matchSchools.Select(x => x.schoolname);
  729. var unmatch = ignore.Select(y => y.name).Except(matched);
  730. List<string> scschoolUnmatch = schools.Select(y => y.schoolname).Except(matched).ToList();
  731. if (scschoolUnmatch.IsNotEmpty())
  732. {
  733. return new { matched, unmatch, scschoolUnmatch };
  734. }
  735. }
  736. else
  737. {
  738. matchSchools.ForEach(x => {
  739. var exschool = ignore.Find(y => y.name.Equals(x.schoolname));
  740. if (exschool != null)
  741. {
  742. x.schoolCode = exschool.id;
  743. x.areaId = $"{areaId}";
  744. x.city = $"{city}";
  745. x.dist = $"{dist}";
  746. }
  747. });
  748. }
  749. }
  750. else
  751. {
  752. return new { unmatch = ignore, schools };
  753. }
  754. }
  755. //数据校验
  756. tbschools = await table.FindListByDict<ScSchool>(new Dictionary<string, object>() { { "PartitionKey", "ScSchool" } });
  757. if (tbschools.IsNotEmpty())
  758. {
  759. var a = tbschools.Select(y => $"{y.RowKey}").ToList();
  760. saveschools = schools.Where(x => !a.Exists(z => z.Equals($"{x.schoolid}"))).ToList();
  761. List<SchoolData> schoolDatas = new List<SchoolData>();
  762. saveschools.ForEach(x =>
  763. {
  764. x.RowKey = $"{x.schoolid}";
  765. x.PartitionKey = "ScSchool";
  766. x.areaId = $"{areaId}";
  767. x.city = $"{city}";
  768. x.dist = $"{dist}";
  769. if (string.IsNullOrEmpty(x.schoolCode))
  770. {
  771. if (string.IsNullOrEmpty(x.schoolCode))
  772. {
  773. schoolDatas.Add(new SchoolData { uid = $"{x.schoolid}", province = "四川省", city = $"{city}", name = x.schoolname });
  774. }
  775. }
  776. });
  777. schoolDatas = await SchoolService.GenerateSchoolCode(schoolDatas, _dingDing, _environment);
  778. saveschools.ForEach(x => {
  779. var schoolData = schoolDatas.Find(y => y.uid.Equals($"{x.schoolid}"));
  780. if (schoolData != null && !string.IsNullOrEmpty(schoolData.id))
  781. {
  782. x.schoolCode = schoolData.id;
  783. x.areaId = $"{areaId}";
  784. x.city = $"{city}";
  785. x.dist = $"{dist}";
  786. }
  787. });
  788. saveschools.RemoveAll(x => string.IsNullOrEmpty(x.schoolCode));
  789. saveschools.RemoveAll(x => tbschools.FindAll(z => !string.IsNullOrEmpty(z.schoolCode)).Exists(y => y.schoolCode.Equals(x.schoolCode)));
  790. saveschools = await table.SaveAll(saveschools);
  791. }
  792. else
  793. {
  794. List<SchoolData> schoolDatas = new List<SchoolData>();
  795. schools.ForEach(x =>
  796. {
  797. x.RowKey = $"{x.schoolid}";
  798. x.PartitionKey = "ScSchool";
  799. x.areaId = $"{areaId}";
  800. x.city = $"{city}";
  801. x.dist = $"{dist}";
  802. var a = ignore.Find(z => z.name.Equals(x.schoolname));
  803. if (a != null)
  804. {
  805. x.schoolCode = a.id;
  806. }
  807. else
  808. {
  809. if (string.IsNullOrEmpty(x.schoolCode))
  810. {
  811. schoolDatas.Add(new SchoolData { uid = $"{x.schoolid}", province = "四川省", city = $"{city}", name = x.schoolname });
  812. }
  813. }
  814. });
  815. schoolDatas = await SchoolService.GenerateSchoolCode(schoolDatas, _dingDing, _environment);
  816. schools.ForEach(x => {
  817. var schoolData = schoolDatas.Find(y => y.uid.Equals($"{x.schoolid}"));
  818. if (schoolData != null && !string.IsNullOrEmpty(schoolData.id))
  819. {
  820. x.schoolCode = schoolData.id;
  821. x.areaId = $"{areaId}";
  822. x.city = $"{city}";
  823. x.dist = $"{dist}";
  824. }
  825. });
  826. schools.RemoveAll(x => string.IsNullOrEmpty(x.schoolCode));
  827. saveschools = await table.SaveOrUpdateAll(schools);
  828. }
  829. }
  830. return null;
  831. }
  832. public static async Task<List<SchoolData>> GenerateSchoolCode(List<SchoolData> schools, DingDing _dingDing, IWebHostEnvironment _environment)
  833. {
  834. string path = $"{_environment.ContentRootPath}/JsonFile/Core/region.json";
  835. //var schools = jsonstr.ToObject<JsonElement>().GetProperty("schools").ToObject<List<SchoolData>>();
  836. schools = schools.Where((x, i) => schools.FindIndex(n => n.name.Equals(x.name)) == i).ToList();
  837. StreamReader streamReader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  838. StringBuilder stringBuilder = new StringBuilder();
  839. string text;
  840. while ((text = streamReader.ReadLine()) != null)
  841. {
  842. stringBuilder.Append(text.ToString());
  843. }
  844. streamReader.Close();
  845. string input = stringBuilder.ToString();
  846. List<Region> region = input.ToObject<List<Region>>();
  847. try
  848. {
  849. schools.ForEach(x =>
  850. {
  851. x.province = ChineseConverter.Convert(x.province, ChineseConversionDirection.TraditionalToSimplified);
  852. if (String.IsNullOrEmpty(x.city))
  853. {
  854. x.city = x.province;
  855. }
  856. else
  857. {
  858. x.city = ChineseConverter.Convert(x.city, ChineseConversionDirection.TraditionalToSimplified);
  859. }
  860. x.name = ChineseConverter.Convert(x.name, ChineseConversionDirection.TraditionalToSimplified);
  861. comeRemoveStr.ForEach(c => { x.province = x.province.Replace(c, ""); });
  862. prvcRemoveStr.ForEach(c => { x.province = x.province.Replace(c, ""); });
  863. var province = region.Find(r => r.name.Contains(x.province));
  864. string tmpprovince = x.province;
  865. string tmpcity = x.city;
  866. if (province != null)
  867. {
  868. x.province = province.name;
  869. comeRemoveStr.ForEach(c => { x.city = x.city.Replace(c, ""); });
  870. cityRemoveStr.ForEach(c => { x.city = x.city.Replace(c, ""); });
  871. nationRemoveStr.ForEach(c => { x.city = x.city.Replace(c, ""); });
  872. tmpcity = x.city;
  873. var city = province.children.Find(r => r.name.Contains(x.city));
  874. if (city == null)
  875. {
  876. city = province.children.Find(r => r.name.Contains(x.city));
  877. if (city == null)
  878. {
  879. city = province.children.SelectMany(x => x.children).ToList().Find(r => r.name.Contains(x.city));
  880. }
  881. }
  882. if (city != null)
  883. {
  884. x.city = city.name;
  885. }
  886. }
  887. string name = x.name;
  888. //去除冗余的学校信息,只保留地名和校名关键信息
  889. schemoveStr.ForEach(str =>
  890. {
  891. name = name.Replace(str, "");
  892. });
  893. string[] names = name.Split("(");
  894. if (names.Length > 1)
  895. {
  896. name = $"{names[0]}";
  897. for (int index = 1; index < names.Length; index++)
  898. {
  899. name = $"{name}{names[index].Substring(0, 1)}";
  900. var afnames = names[index].Split(")");
  901. if (afnames.Length > 1)
  902. {
  903. for (int i = 1; i < afnames.Length; i++)
  904. {
  905. name = $"{name}{afnames[i]}";
  906. }
  907. }
  908. }
  909. }
  910. names = name.Split("(");
  911. if (names.Length > 1)
  912. {
  913. name = $"{names[0]}";
  914. for (int index = 1; index < names.Length; index++)
  915. {
  916. name = $"{name}{names[index].Substring(0, 1)}";
  917. var afnames = names[index].Split(")");
  918. if (afnames.Length > 1)
  919. {
  920. for (int i = 1; i < afnames.Length; i++)
  921. {
  922. name = $"{name}{afnames[i]}";
  923. }
  924. }
  925. }
  926. }
  927. name = Regex.Replace(name, "[ \\[ \\] \\^ \\-|()【】/' {}_*×――(^)$%~!@#$…&%¥—+=<>《》!!???::•`·、。,;,.;\"‘’“”-]", " ");
  928. //检查是否有英文
  929. if (Regex.Matches(name, "[a-zA-Z]").Count > 0)
  930. {
  931. var array = Regex.Split(name, "\\s+", RegexOptions.IgnoreCase);
  932. StringBuilder tmpname = new StringBuilder();
  933. if (array.Length > 1)
  934. {
  935. foreach (var item in array)
  936. {
  937. var arr = item.Select(x => $"{x}");
  938. int index = 0;
  939. foreach (var stra in arr)
  940. {
  941. if (Regex.Matches(stra, "[a-zA-Z]").Count > 0)
  942. {
  943. if (index == 1|| index == 0)
  944. {
  945. tmpname.Append(stra);
  946. }
  947. else
  948. {
  949. }
  950. }
  951. else
  952. {
  953. tmpname.Append(stra);
  954. }
  955. index++;
  956. }
  957. }
  958. }
  959. else
  960. {
  961. var arr = name.Select(x => $"{x}");
  962. int index = 0;
  963. foreach (var stra in arr)
  964. {
  965. if (Regex.Matches(stra, "[A-Z]").Count > 0)
  966. {
  967. tmpname.Append(stra);
  968. }
  969. else if (Regex.Matches(stra, "[a-z]").Count > 0)
  970. {
  971. }
  972. else
  973. {
  974. tmpname.Append(stra);
  975. }
  976. index++;
  977. }
  978. }
  979. name = tmpname.ToString();
  980. }
  981. name = Regex.Replace(name, @"\s", "");
  982. name = name.Replace("\\", "");
  983. if (name.Length > 6)
  984. {
  985. //新区,高新,产业等非新政单位
  986. areaRemoveStr.ForEach(str =>
  987. {
  988. name = name.Replace(str.Key, str.Value);
  989. });
  990. //去除冗余的学校信息,只保留地名和校名关键信息
  991. schooRemoveStr.ForEach(str =>
  992. {
  993. name = name.Replace(str, "");
  994. });
  995. //替换民族信息词
  996. if (name.Length > 6)
  997. {
  998. nationRemoveStr.ForEach(str =>
  999. {
  1000. name = name.Replace(str, "");
  1001. });
  1002. }
  1003. //替换学校信息的副词
  1004. if (name.Length > 6)
  1005. {
  1006. foreach (var str in schooReplaceStr)
  1007. {
  1008. if (name.Length <= 6)
  1009. {
  1010. break;
  1011. }
  1012. name = name.Replace(str.Key, str.Value);
  1013. }
  1014. }
  1015. //替换省简称信息词
  1016. string tmpname = name;
  1017. if (name.Length > 6)
  1018. {
  1019. proReplaceStr.ForEach(str =>
  1020. {
  1021. name = name.Replace(str.Key, str.Value);
  1022. });
  1023. //如果替换后仍然大于6位,则取消,直接替换省份完整的词
  1024. if (name.Length > 6)
  1025. {
  1026. name = tmpname.Replace(tmpprovince, "");
  1027. }
  1028. }
  1029. //替换城市信息词
  1030. if (name.Length > 6)
  1031. {
  1032. name = name.Replace(tmpcity, "");
  1033. }
  1034. }
  1035. int len = name.Length;
  1036. if (len > 6)
  1037. {
  1038. foreach (var str in afterSchoolRm)
  1039. {
  1040. if (name.Length <= 6)
  1041. {
  1042. break;
  1043. }
  1044. name = name.Replace(str, "");
  1045. }
  1046. }
  1047. len = name.Length;
  1048. if (len >= 6)
  1049. {
  1050. name = $"{name.Substring(0, 1)}{name.Substring(len - 5, 3)}{name.Substring(len - 2, 2)}";
  1051. }
  1052. //if (len <= 7 && len > 6)
  1053. //{
  1054. // name = name.Substring(len - 6);
  1055. //}
  1056. if (len <= 4)
  1057. {
  1058. name = $"{x.city.Substring(0, 2)}{name}";
  1059. }
  1060. if (len == 5)
  1061. {
  1062. name = $"{x.city.Substring(0, 1)}{name}";
  1063. }
  1064. string code = ToFirstPinYin(name);
  1065. x.aname = name;
  1066. x.id = code;
  1067. });
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. await _dingDing.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1072. }
  1073. string a_z = "abcdefghijklmnopqrstuvwxyz";
  1074. var data = schools.GroupBy(x => x.id).Select(x => new { key = x.Key, more = x.ToList().Count > 2, count = x.ToList().Count, list = x.ToList() }).ToList();
  1075. data.ForEach(x =>
  1076. {
  1077. if (x.count > 1)
  1078. {
  1079. var first = x.list.First();
  1080. var same = x.list.Skip(1).Take(x.count - 1).ToList();
  1081. var fs = first.aname.Select(x => x).ToArray();
  1082. same.ForEach(z =>
  1083. {
  1084. var sp = z.aname.Select(x => x).ToArray();
  1085. int len = sp.Length;
  1086. if (sp.Length >= fs.Length)
  1087. {
  1088. len = fs.Count();
  1089. }
  1090. for (int index = 0; index < len; index++)
  1091. {
  1092. if (!$"{sp[index]}".Equals($"{fs[index]}"))
  1093. {
  1094. short st = ChineseChar.GetStrokeNumber(sp[index]);
  1095. if (st > 0)
  1096. {
  1097. var ins = st % 27;
  1098. var insch = a_z[ins];
  1099. if (z.aname.EndsWith($"{insch}"))
  1100. {
  1101. ins = (st + 1) % 27;
  1102. insch = a_z[ins];
  1103. }
  1104. z.id = z.id.Insert(index, $"{insch}").Remove(index + 1, 1);
  1105. break;
  1106. }
  1107. }
  1108. }
  1109. });
  1110. }
  1111. });
  1112. var dataz = data.SelectMany(y=>y.list).GroupBy(x => x.id).Select(x => new { key = x.Key, more = x.ToList().Count > 2, count = x.ToList().Count, list = x.ToList() }).ToList();
  1113. dataz.ForEach(x =>
  1114. {
  1115. if (x.count > 1)
  1116. {
  1117. var first = x.list.First();
  1118. var same = x.list.Skip(1).Take(x.count - 1).ToList();
  1119. var fs = first.aname.Select(x => x).ToArray();
  1120. same.ForEach(z =>
  1121. {
  1122. var sp = z.aname.Select(x => x).ToArray();
  1123. int len = sp.Length;
  1124. if (sp.Length >= fs.Length)
  1125. {
  1126. len = fs.Count();
  1127. }
  1128. for (int index = 0; index < len; index++)
  1129. {
  1130. if (!$"{sp[index]}".Equals($"{fs[index]}"))
  1131. {
  1132. var spstr = ToPinYin($"{sp[index]}" );
  1133. var fsstr = ToPinYin($"{fs[index]}");
  1134. var insch= spstr.Select(x => $"{x}").Except( fsstr.Select(z => $"{z}"));
  1135. if (insch != null && insch.Count() > 0) {
  1136. if (index > 1)
  1137. {
  1138. z.id = z.id.Insert(index - 1, insch.First()).Remove(index, 1);
  1139. }
  1140. else if (index == 1)
  1141. {
  1142. z.id = z.id.Insert(index, insch.First()).Remove(index - 1, 1);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. });
  1148. }
  1149. });
  1150. var dataa = dataz.SelectMany(y => y.list).GroupBy(x => x.id).Select(x => new { key = x.Key, more = x.ToList().Count > 2, count = x.ToList().Count, list = x.ToList() }).ToList();
  1151. Random random = new Random();
  1152. List<SchoolData> list = new List<SchoolData>();
  1153. dataa.ForEach(x =>
  1154. {
  1155. if (x.count > 1)
  1156. {
  1157. x.list.ForEach(y => {
  1158. int r= random.Next(25);
  1159. int index= random.Next(5);
  1160. y.id = y.id.Insert(index - 1, $"{a_z[r]}").Remove(index, 1);
  1161. });
  1162. }
  1163. list.AddRange(x.list);
  1164. });
  1165. return list;
  1166. }
  1167. public static string ToPinYin(string val)
  1168. {
  1169. StringBuilder sb = new StringBuilder();
  1170. val.ToCharArray().ToList().ForEach(x =>
  1171. {
  1172. if (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z') || ('0' <= x && x <= '9'))
  1173. {
  1174. sb.Append(x);
  1175. }
  1176. else
  1177. {
  1178. try
  1179. {
  1180. ChineseChar cc = new ChineseChar(x);
  1181. if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
  1182. {
  1183. sb.Append(cc.Pinyins[0]);
  1184. }
  1185. }
  1186. catch (Exception ex)
  1187. {
  1188. }
  1189. }
  1190. });
  1191. return sb.ToString().ToLower();
  1192. }
  1193. public static string ToFirstPinYin(string val)
  1194. {
  1195. StringBuilder sb = new StringBuilder();
  1196. val.ToCharArray().ToList().ForEach(x =>
  1197. {
  1198. if (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z') || ('0' <= x && x <= '9'))
  1199. {
  1200. sb.Append(x);
  1201. }
  1202. else
  1203. {
  1204. try
  1205. {
  1206. ChineseChar cc = new ChineseChar(x);
  1207. if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
  1208. {
  1209. sb.Append(cc.Pinyins[0][0]);
  1210. }
  1211. }
  1212. catch (Exception ex)
  1213. {
  1214. }
  1215. }
  1216. });
  1217. return sb.ToString().ToLower();
  1218. }
  1219. public class SchoolData
  1220. {
  1221. public string province { get; set; }
  1222. public string id { get; set; }
  1223. public string name { get; set; }
  1224. public string city { get; set; }
  1225. public string aname { get; set; }
  1226. public string uid { get; set; }
  1227. }
  1228. public static List<string> comeRemoveStr = new List<string>() { "省", "市", "区", "州", "县", "旗", "盟", "自治" };
  1229. public static List<string> prvcRemoveStr = new List<string>() { "回族", "维吾尔", "壮族", };
  1230. public static List<string> cityRemoveStr = new List<string>() { "蒙古族", "地区", "壮族", "朝鲜族", "直辖" };
  1231. public static List<string> nationRemoveStr = new List<string> {
  1232. "维吾尔","回族", "自治", "满族", "蒙古", "壮族", "苗族" , "侗族", "瑶族",
  1233. "达斡尔","鄂温克","朝鲜","畲族","土家","各族","仫佬","毛南","羌族","彝族","仡佬","布依","水族",
  1234. "傣族","纳西","哈尼","拉祜","佤族","傈僳","独龙","怒族","白族","普米","固族","哈萨克","土族","撒拉","景颇","族"
  1235. };
  1236. public static List<string> schemoveStr = new List<string> { "第", "校区", "部", "楼", "与", "学校", "校园", };
  1237. public static List<string> schooRemoveStr = new List<string>() {"省", "市", "区", "州", "县", "旗", "盟","办事处","街道", "自治",
  1238. "镇","村","乡","街","路","站","馆"
  1239. };
  1240. public static List<string> afterSchoolRm = new List<string>() {"校","园","院", "湾","峡","沟","山","庄",
  1241. "堡","江","屯","岭","溪","河","桥","营","铺","坡","寨","场","湖","巷","集","关","庙","寺","矿","塘"};
  1242. public static List<KeyValuePair<string, string>> areaRemoveStr = new List<KeyValuePair<string, string>>{
  1243. new KeyValuePair<string, string>("高新技术产业开发区", "高") ,
  1244. new KeyValuePair<string, string>("经济技术开发区", "经") ,
  1245. new KeyValuePair<string, string>("国际", "际") ,
  1246. new KeyValuePair<string, string>("中国", ""),
  1247. new KeyValuePair<string, string>("国家", ""),
  1248. new KeyValuePair<string, string>("新区", ""),
  1249. new KeyValuePair<string, string>("高新", "高"),
  1250. new KeyValuePair<string, string>("园区", ""),
  1251. new KeyValuePair<string, string>("产业", "产"),
  1252. new KeyValuePair<string, string>("经济", "经"),
  1253. new KeyValuePair<string, string>("开发", "开"),
  1254. new KeyValuePair<string, string>("中心", "") ,
  1255. new KeyValuePair<string, string>("集团", "") ,
  1256. new KeyValuePair<string, string>("公司", "") ,
  1257. new KeyValuePair<string, string>("有限", "") ,
  1258. new KeyValuePair<string, string>("股份", "") ,
  1259. new KeyValuePair<string, string>("服务", "") ,
  1260. new KeyValuePair<string, string>("基地", "") ,
  1261. new KeyValuePair<string, string>("社区", "社") ,
  1262. new KeyValuePair<string, string>("职工", "") ,
  1263. new KeyValuePair<string, string>("专修", ""),
  1264. new KeyValuePair<string, string>("实验", "验"),
  1265. new KeyValuePair<string, string>("完全", ""),
  1266. new KeyValuePair<string, string>("一贯制", "") ,
  1267. new KeyValuePair<string, string>("联办", ""),
  1268. new KeyValuePair<string, string>("联合", ""),
  1269. new KeyValuePair<string, string>("完小", "小"),
  1270. new KeyValuePair<string, string>("义务", ""),
  1271. new KeyValuePair<string, string>("基础", ""),
  1272. new KeyValuePair<string, string>("制造", "")
  1273. };
  1274. public static List<KeyValuePair<string, string>> schooReplaceStr = new List<KeyValuePair<string, string>> {
  1275. new KeyValuePair<string, string>("分校", "分") ,
  1276. new KeyValuePair<string, string>("分园", "分") ,
  1277. new KeyValuePair<string, string>("分院", "分") ,
  1278. new KeyValuePair<string, string>("藏文", "藏"),
  1279. new KeyValuePair<string, string>("职业技术学院", "职") ,
  1280. new KeyValuePair<string, string>("创新创业", "创") ,
  1281. new KeyValuePair<string, string>("就业创业", "就") ,
  1282. new KeyValuePair<string, string>("应用核技术", "核") ,
  1283. new KeyValuePair<string, string>("职业学院", "职") ,
  1284. new KeyValuePair<string, string>("幼儿园", "幼") ,
  1285. new KeyValuePair<string, string>("幼儿", "幼") ,
  1286. new KeyValuePair<string, string>("小学", "小") ,
  1287. new KeyValuePair<string, string>("中学", "中") ,
  1288. new KeyValuePair<string, string>("中等", "中") ,
  1289. new KeyValuePair<string, string>("双语", "双") ,
  1290. new KeyValuePair<string, string>("初中", "初") ,
  1291. new KeyValuePair<string, string>("初级", "初") ,
  1292. new KeyValuePair<string, string>("广播", "广"),
  1293. new KeyValuePair<string, string>("高中", "高") ,
  1294. new KeyValuePair<string, string>("高级", "高") ,
  1295. new KeyValuePair<string, string>("大学", "大") ,
  1296. new KeyValuePair<string, string>("学院", "院") ,
  1297. new KeyValuePair<string, string>("综合", "综") ,
  1298. new KeyValuePair<string, string>("职业", "职") ,
  1299. new KeyValuePair<string, string>("技术", "技") ,
  1300. new KeyValuePair<string, string>("专科", "专") ,
  1301. new KeyValuePair<string, string>("外国语", "外") ,
  1302. new KeyValuePair<string, string>("九年", "九") ,
  1303. new KeyValuePair<string, string>("五年", "五") ,
  1304. new KeyValuePair<string, string>("年制", "制") ,
  1305. new KeyValuePair<string, string>("高等", "高") ,
  1306. new KeyValuePair<string, string>("院校", "院") ,
  1307. new KeyValuePair<string, string>("初等", "小") ,
  1308. new KeyValuePair<string, string>("附属", "附"),
  1309. new KeyValuePair<string, string>("寄宿制", "寄") ,
  1310. new KeyValuePair<string, string>("寄宿", "寄") ,
  1311. new KeyValuePair<string, string>("卫生", "卫") ,
  1312. new KeyValuePair<string, string>("创业", "创") ,
  1313. new KeyValuePair<string, string>("继续", "继") ,
  1314. new KeyValuePair<string, string>("开放", "开") ,
  1315. new KeyValuePair<string, string>("技师", "技") ,
  1316. new KeyValuePair<string, string>("成人", "成") ,
  1317. new KeyValuePair<string, string>("教育", "教") ,
  1318. new KeyValuePair<string, string>("科技", "科") ,
  1319. new KeyValuePair<string, string>("行政", "政") ,
  1320. new KeyValuePair<string, string>("生物", "生") ,
  1321. new KeyValuePair<string, string>("美术", "美") ,
  1322. new KeyValuePair<string, string>("设计", "设") ,
  1323. new KeyValuePair<string, string>("传播", "传") ,
  1324. new KeyValuePair<string, string>("计算机", "算") ,
  1325. new KeyValuePair<string, string>("土木", "土") ,
  1326. new KeyValuePair<string, string>("石油", "油") ,
  1327. new KeyValuePair<string, string>("科普", "普") ,
  1328. new KeyValuePair<string, string>("电信", "信") ,
  1329. new KeyValuePair<string, string>("联合", "联") ,
  1330. new KeyValuePair<string, string>("电商", "商") ,
  1331. new KeyValuePair<string, string>("纺织", "织") ,
  1332. new KeyValuePair<string, string>("服装", "服") ,
  1333. new KeyValuePair<string, string>("新闻", "新") ,
  1334. new KeyValuePair<string, string>("网络", "网") ,
  1335. new KeyValuePair<string, string>("应用", "应") ,
  1336. new KeyValuePair<string, string>("畜牧", "畜") ,
  1337. new KeyValuePair<string, string>("兽医", "兽") ,
  1338. new KeyValuePair<string, string>("师范", "师") ,
  1339. new KeyValuePair<string, string>("人文", "文") ,
  1340. new KeyValuePair<string, string>("创新", "创") ,
  1341. new KeyValuePair<string, string>("法官", "法") ,
  1342. new KeyValuePair<string, string>("邮电", "邮") ,
  1343. new KeyValuePair<string, string>("文化", "文") ,
  1344. new KeyValuePair<string, string>("函授", "函") ,
  1345. new KeyValuePair<string, string>("科学", "科") ,
  1346. new KeyValuePair<string, string>("信息", "息") ,
  1347. new KeyValuePair<string, string>("水利", "利") ,
  1348. new KeyValuePair<string, string>("水电", "电") ,
  1349. new KeyValuePair<string, string>("电力", "力") ,
  1350. new KeyValuePair<string, string>("环境", "环") ,
  1351. new KeyValuePair<string, string>("建材", "材") ,
  1352. new KeyValuePair<string, string>("机电", "机") ,
  1353. new KeyValuePair<string, string>("航空", "空") ,
  1354. new KeyValuePair<string, string>("航天", "天") ,
  1355. new KeyValuePair<string, string>("警察", "警") ,
  1356. new KeyValuePair<string, string>("警官", "警") ,
  1357. new KeyValuePair<string, string>("财贸", "财") ,
  1358. new KeyValuePair<string, string>("电子", "电") ,
  1359. new KeyValuePair<string, string>("建筑", "筑") ,
  1360. new KeyValuePair<string, string>("艺术", "艺") ,
  1361. new KeyValuePair<string, string>("体育", "体") ,
  1362. new KeyValuePair<string, string>("城市", "城") ,
  1363. new KeyValuePair<string, string>("地质", "地") ,
  1364. new KeyValuePair<string, string>("医药", "药") ,
  1365. new KeyValuePair<string, string>("政法", "法") ,
  1366. new KeyValuePair<string, string>("铁路", "铁") ,
  1367. new KeyValuePair<string, string>("铁道", "道") ,
  1368. new KeyValuePair<string, string>("轨道", "轨") ,
  1369. new KeyValuePair<string, string>("交通", "通") ,
  1370. new KeyValuePair<string, string>("医学院", "医") ,
  1371. new KeyValuePair<string, string>("医学", "医") ,
  1372. new KeyValuePair<string, string>("传媒", "媒") ,
  1373. new KeyValuePair<string, string>("工程", "程") ,
  1374. new KeyValuePair<string, string>("临床", "临") ,
  1375. new KeyValuePair<string, string>("化工", "化") ,
  1376. new KeyValuePair<string, string>("林业", "林") ,
  1377. new KeyValuePair<string, string>("老年", "老") ,
  1378. new KeyValuePair<string, string>("旅游", "游") ,
  1379. new KeyValuePair<string, string>("护理", "护") ,
  1380. new KeyValuePair<string, string>("贸易", "贸") ,
  1381. new KeyValuePair<string, string>("中医药", "中医") ,
  1382. new KeyValuePair<string, string>("资源", "源") ,
  1383. new KeyValuePair<string, string>("冶金", "冶") ,
  1384. new KeyValuePair<string, string>("能源", "能") ,
  1385. new KeyValuePair<string, string>("汽车", "车") ,
  1386. new KeyValuePair<string, string>("医科", "医") ,
  1387. new KeyValuePair<string, string>("机械", "械") ,
  1388. new KeyValuePair<string, string>("应用", "应") ,
  1389. new KeyValuePair<string, string>("电气", "电") ,
  1390. new KeyValuePair<string, string>("材料", "材") ,
  1391. new KeyValuePair<string, string>("劳动", "劳") ,
  1392. new KeyValuePair<string, string>("轻工", "轻") ,
  1393. new KeyValuePair<string, string>("农业", "农") ,
  1394. new KeyValuePair<string, string>("委员会", "委") ,
  1395. new KeyValuePair<string, string>("专业", "专") ,
  1396. new KeyValuePair<string, string>("广播", "广"),
  1397. new KeyValuePair<string, string>("电视", "电") ,
  1398. new KeyValuePair<string, string>("工商", "商") ,
  1399. new KeyValuePair<string, string>("工业", "工") ,
  1400. new KeyValuePair<string, string>("管理", "管") ,
  1401. new KeyValuePair<string, string>("社会主义", "社") ,
  1402. new KeyValuePair<string, string>("社会", "社") ,
  1403. new KeyValuePair<string, string>("自动化", "自") ,
  1404. };
  1405. public static List<KeyValuePair<string, string>> proReplaceStr = new List<KeyValuePair<string, string>> {
  1406. new KeyValuePair<string, string>("北京","京") ,
  1407. new KeyValuePair<string, string>("天津","津") ,
  1408. new KeyValuePair<string, string>("河北","冀") ,
  1409. new KeyValuePair<string, string>("山西","晋") ,
  1410. new KeyValuePair<string, string>("内蒙古","蒙") ,
  1411. new KeyValuePair<string, string>("辽宁","辽") ,
  1412. new KeyValuePair<string, string>("吉林","吉") ,
  1413. new KeyValuePair<string, string>("黑龙江","黑") ,
  1414. new KeyValuePair<string, string>("上海","沪") ,
  1415. new KeyValuePair<string, string>("江苏","苏") ,
  1416. new KeyValuePair<string, string>("浙江","浙") ,
  1417. new KeyValuePair<string, string>("安徽","皖") ,
  1418. new KeyValuePair<string, string>("福建","闽") ,
  1419. new KeyValuePair<string, string>("江西","赣") ,
  1420. new KeyValuePair<string, string>("山东","鲁") ,
  1421. new KeyValuePair<string, string>("河南","豫") ,
  1422. new KeyValuePair<string, string>("湖北","鄂") ,
  1423. new KeyValuePair<string, string>("湖南","湘") ,
  1424. new KeyValuePair<string, string>("广东","粤") ,
  1425. new KeyValuePair<string, string>("广西","桂") ,
  1426. new KeyValuePair<string, string>("海南","琼") ,
  1427. new KeyValuePair<string, string>("四川","川") ,
  1428. new KeyValuePair<string, string>("贵州","贵") ,
  1429. new KeyValuePair<string, string>("云南","云") ,
  1430. new KeyValuePair<string, string>("重庆","渝") ,
  1431. new KeyValuePair<string, string>("西藏","藏") ,
  1432. new KeyValuePair<string, string>("陕西","陕") ,
  1433. new KeyValuePair<string, string>("甘肃","甘") ,
  1434. new KeyValuePair<string, string>("青海","青") ,
  1435. new KeyValuePair<string, string>("宁夏","宁") ,
  1436. new KeyValuePair<string, string>("新疆","新") ,
  1437. new KeyValuePair<string, string>("香港","港") ,
  1438. new KeyValuePair<string, string>("澳门","澳") ,
  1439. new KeyValuePair<string, string>("台湾","台")
  1440. };
  1441. /*
  1442. [
  1443. {"method":"台北市","params":{"CountryId":"TW","CityId":"30"}},1
  1444. {"method":"新北市","params":{"CountryId":"TW","CityId":"01"}},1
  1445. {"method":"桃园市","params":{"CountryId":"TW","CityId":"03"}},1
  1446. {"method":"台中市","params":{"CountryId":"TW","CityId":"66"}},1
  1447. {"method":"台南市","params":{"CountryId":"TW","CityId":"67"}},1
  1448. {"method":"高雄市","params":{"CountryId":"TW","CityId":"64"}},1
  1449. {"method":"基隆市","params":{"CountryId":"TW","CityId":"17"}},1
  1450. {"method":"新竹市","params":{"CountryId":"TW","CityId":"18"}},1
  1451. {"method":"嘉义市","params":{"CountryId":"TW","CityId":"20"}},1
  1452. {"method":"新竹县","params":{"CountryId":"TW","CityId":"04"}},1
  1453. {"method":"苗栗县","params":{"CountryId":"TW","CityId":"05"}},1
  1454. {"method":"彰化县","params":{"CountryId":"TW","CityId":"07"}},1
  1455. {"method":"南投县","params":{"CountryId":"TW","CityId":"08"}},1
  1456. {"method":"云林县","params":{"CountryId":"TW","CityId":"09"}},1
  1457. {"method":"嘉义县","params":{"CountryId":"TW","CityId":"10"}},1
  1458. {"method":"屏东县","params":{"CountryId":"TW","CityId":"13"}},1
  1459. {"method":"宜兰县","params":{"CountryId":"TW","CityId":"02"}},1
  1460. {"method":"花莲县","params":{"CountryId":"TW","CityId":"15"}},1
  1461. {"method":"台东县","params":{"CountryId":"TW","CityId":"14"}},1
  1462. {"method":"澎湖县","params":{"CountryId":"TW","CityId":"16"}},1
  1463. {"method":"金门县","params":{"CountryId":"TW","CityId":"71"}},
  1464. {"method":"连江县","params":{"CountryId":"TW","CityId":"72"}}
  1465. ]
  1466. */
  1467. }
  1468. }