MigrateService.cs 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777
  1. using Flyinsono.DBCopy.Tool.Entities;
  2. using Flyinsono.DBCopy.Tool.RpcService;
  3. using Flyinsono.DBCopy.Tool.Service.Repositories;
  4. using MongoDB.Driver;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Security;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using System.Windows.Controls;
  13. using System.Xml.Linq;
  14. using WingInterfaceLibrary.DTO.Common;
  15. using WingInterfaceLibrary.DTO.DataCenter;
  16. using WingInterfaceLibrary.DTO.Management;
  17. using WingInterfaceLibrary.DTO.Record;
  18. using WingInterfaceLibrary.Enum;
  19. using WingInterfaceLibrary.Enum.CourseEnum;
  20. using WingInterfaceLibrary.Internal.Request;
  21. using WingInterfaceLibrary.Request;
  22. using WingInterfaceLibrary.Request.DBCopy;
  23. using WingServerCommon.Mapper;
  24. using MongoDB.Bson.IO;
  25. using JsonConvert = Newtonsoft.Json.JsonConvert;
  26. using WingInterfaceLibrary.Request.AIDiagnosis;
  27. using DnsClient.Protocol;
  28. using System.Text.RegularExpressions;
  29. using WingInterfaceLibrary.Result.AppletAPI;
  30. using WingInterfaceLibrary.DTO.Comment;
  31. using WingInterfaceLibrary.Request.Report;
  32. using WingInterfaceLibrary.DTO.Report;
  33. using WingInterfaceLibrary.LiveConsultation.Consultation;
  34. using WingInterfaceLibrary.DTO.Consultation;
  35. using System.Net.Http;
  36. using System.Net;
  37. using WingInterfaceLibrary.Request.Storage;
  38. using SharpCompress.Common;
  39. using System.Security.Policy;
  40. using System.Net.Http.Headers;
  41. using WingServerCommon.Interfaces.FileTransfer;
  42. using WingInterfaceLibrary.LiveConsultation;
  43. using WingInterfaceLibrary.Request.Report;
  44. using WingInterfaceLibrary.DTO.Report;
  45. using WingInterfaceLibrary.LiveConsultation.Consultation;
  46. using WingInterfaceLibrary.DTO.Consultation;
  47. using WingInterfaceLibrary.Request.User;
  48. using MongoDB.Driver.Core.Operations;
  49. using Flyinsono.DBCopy.Tool.Utilities;
  50. using Flyinsono.DBCopy.Tool.Entities.Config;
  51. using System.Diagnostics;
  52. using Newtonsoft.Json.Linq;
  53. namespace Flyinsono.DBCopy.Tool.Service
  54. {
  55. internal partial class MigrateService
  56. {
  57. private JsonRpcProxy _jsonRpcProxy;
  58. public static HttpClient _httpClient = new HttpClient();
  59. private readonly string _tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DownloadTemp");
  60. private TerminalRecordDBRepository _terminalRecordDBRepository;
  61. private TerminalDatasDBRepository _terminalDatasDBRepository;
  62. private TerminalAIDatasDBRepository _terminalAIDatasDBRepository;
  63. private Carotid3dModelDatasDBRepository _carotid3dModelDatasDBRepository;
  64. private TerminalRecordReportStatesDBRepository _terminalRecordReportStatesDBRepository;
  65. private OrganizationsDBRepository _organizationsDBRepository;
  66. private TerminalsDBRepository _terminalsDBRepository;
  67. private PosterConfigsDBRepository _posterConfigsDBRepository;
  68. private MigrateRecordDTO _migrateRecord;
  69. private readonly string DefaultToken = "637f02a065ad47fbbe01b956919419c2";
  70. private ConsultationRecordDBRepository _consultationRecordDBRepository;
  71. private UsersDBRepository _usersDBRepository;
  72. private VideoDBRepository _videoDBRepository;
  73. private UserGroupDBRepository _userGroupDBRepository;
  74. private UltrasonicClassDBRepository _ultrasonicClassDBRepository;
  75. private CoursesDBRepository _coursesDBRepository;
  76. private AdminDBRepository _adminDBRepository;
  77. private ExaminationPaperDBPepository _examinationPaperDBPepository;
  78. private ExamScoreDBRepository _examScoreDBRepository;
  79. private ReportTemplateDBRepository _reportTemplateDBRepository;
  80. private ReportInfoResultDBRepository _reportInfoResultDBRepository;
  81. private CustomLabelDBRepository _customLabelDBRepository;
  82. protected readonly object locker = new object();
  83. protected ProbeAppHepler _probeAppHepler;
  84. public MigrateService(string dcServiceUrl)
  85. {
  86. _jsonRpcProxy = new JsonRpcProxy(dcServiceUrl);
  87. _httpClient.Timeout = TimeSpan.FromMinutes(15);
  88. _terminalRecordDBRepository = new TerminalRecordDBRepository();
  89. _terminalDatasDBRepository = new TerminalDatasDBRepository();
  90. _carotid3dModelDatasDBRepository = new Carotid3dModelDatasDBRepository();
  91. _terminalRecordReportStatesDBRepository = new TerminalRecordReportStatesDBRepository();
  92. _organizationsDBRepository = new OrganizationsDBRepository();
  93. _terminalsDBRepository = new TerminalsDBRepository();
  94. _posterConfigsDBRepository = new PosterConfigsDBRepository();
  95. _migrateRecord = GetQueryMigrateTimeRange();
  96. _terminalAIDatasDBRepository = new TerminalAIDatasDBRepository();
  97. _consultationRecordDBRepository = new ConsultationRecordDBRepository();
  98. _usersDBRepository = new UsersDBRepository();
  99. _videoDBRepository = new VideoDBRepository();
  100. _userGroupDBRepository = new UserGroupDBRepository();
  101. _ultrasonicClassDBRepository = new UltrasonicClassDBRepository();
  102. _coursesDBRepository = new CoursesDBRepository();
  103. _adminDBRepository = new AdminDBRepository();
  104. _examinationPaperDBPepository = new ExaminationPaperDBPepository();
  105. _examScoreDBRepository = new ExamScoreDBRepository();
  106. _reportTemplateDBRepository = new ReportTemplateDBRepository();
  107. _adminDBRepository = new AdminDBRepository();
  108. _reportInfoResultDBRepository = new ReportInfoResultDBRepository();
  109. _customLabelDBRepository = new CustomLabelDBRepository();
  110. _probeAppHepler = new ProbeAppHepler();
  111. }
  112. public async Task WriteMigrateStaticAsync()
  113. {
  114. Logger.WriteLineInfo($"Migrate Static Starting");
  115. Logger.WriteLineInfo($"terminal record totalCount:{_terminalRecordDBRepository.GetTerminalRecords(Builders<TerminalRecords>.Filter.Where(x => x.IsDelete == false)).Count()}");
  116. Logger.WriteLineInfo($"consultation record totalCount:{_consultationRecordDBRepository.GetTerminalRecords(Builders<ConsultationRecords>.Filter.Where(x => x.IsDeleted == false)).Count()}");
  117. Logger.WriteLineInfo($"video totalCount:{_videoDBRepository.GetVideos(Builders<Video>.Filter.Where(x => x.IsDeleted == false)).Count()}");
  118. Logger.WriteLineInfo($"course totalCount:{_coursesDBRepository.GetCourses(Builders<Courses>.Filter.Where(x => x.IsDeleted == false)).Count()}");
  119. Logger.WriteLineInfo($"exam paper totalCount:{_examinationPaperDBPepository.GetExaminationPapers(Builders<ExaminationPaper>.Filter.Where(x => x.IsDeleted == false)).Count()}");
  120. Logger.WriteLineInfo($"report totalCount:{_reportInfoResultDBRepository.GetReports(Builders<ReportInfoResults>.Filter.Where(x => true)).Count()}");
  121. Logger.WriteLineInfo($"terminal ai data totalCount:{_terminalAIDatasDBRepository.GetTerminalAIDatas(Builders<TerminalAIDatas>.Filter.Where(x => true)).Count()}");
  122. Logger.WriteLineInfo($"Migrate Static Successfully");
  123. }
  124. /// <summary>
  125. /// 查询同步数据的时间范围
  126. /// </summary>
  127. /// <returns></returns>
  128. private MigrateRecordDTO GetQueryMigrateTimeRange()
  129. {
  130. lock (locker)
  131. {
  132. if (_migrateRecord != null && _migrateRecord.EndTime > DateTime.MinValue)
  133. {
  134. return _migrateRecord;
  135. }
  136. var request = new QueryMigrateTimeRequest
  137. {
  138. Token = DefaultToken,
  139. IsInitMigreate = true
  140. };
  141. var result = _jsonRpcProxy.User.QueryMigrateTimeAsync(request).Result;
  142. return result;
  143. }
  144. }
  145. /// <summary>
  146. /// 备份库迁移分时诊断数据
  147. /// </summary>
  148. /// <returns></returns>
  149. public async Task MigrateRemoteDiagnosisInfosAsync()
  150. {
  151. Logger.WriteLineInfo($"Remote Diagnosis Infos Migrate Starting");
  152. var source = _terminalRecordDBRepository.GetTerminalRecords(Builders<TerminalRecords>.Filter.Where(x => x.IsDelete == false))
  153. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  154. OnMigrate("terminal record", source, SendRemoteDiagnosisInfos);
  155. source.Clear();
  156. Logger.WriteLineInfo($"Remote Diagnosis Infos Migrate Successfully");
  157. }
  158. /// <summary>
  159. /// 备份库迁移实时会诊数据
  160. /// </summary>
  161. /// <returns></returns>
  162. public async Task MigrateLiveConsultationInfosAsync()
  163. {
  164. Logger.WriteLineInfo($"Live Consultation Infos Migrate Starting");
  165. var source = _consultationRecordDBRepository.GetTerminalRecords(Builders<ConsultationRecords>.Filter.Where(x => x.IsDeleted == false))
  166. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  167. OnMigrate("consultation record", source, SendLiveConsultationInfos);
  168. source.Clear();
  169. Logger.WriteLineInfo($"Live Consultation Infos Migrate Successfully");
  170. }
  171. /// <summary>
  172. /// 备份库迁移在线视频数据
  173. /// </summary>
  174. /// <returns></returns>
  175. public async Task MigrateOnlineVideoInfosAsync()
  176. {
  177. Logger.WriteLineInfo($"Online Video Infos Migrate Starting");
  178. var videos = _videoDBRepository.GetVideos(Builders<Video>.Filter.Where(x => x.IsDeleted == false))
  179. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  180. OnMigrate("video", videos, SendVideoInfos);
  181. videos.Clear();
  182. Logger.WriteLineInfo($"Online Video Infos Migrate Successfully");
  183. }
  184. /// <summary>
  185. /// 备份库迁移在线培训数据
  186. /// </summary>
  187. /// <returns></returns>
  188. public async Task MigrateOnlineTrainingInfosAsync()
  189. {
  190. Logger.WriteLineInfo($"Online Training Infos Migrate Starting");
  191. var videos = _coursesDBRepository.GetCourses(Builders<Courses>.Filter.Where(x => x.IsDeleted == false))
  192. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  193. OnMigrate("course", videos, SendCourseInfos);
  194. videos.Clear();
  195. Logger.WriteLineInfo($"Online Training Infos Migrate Successfully");
  196. }
  197. /// <summary>
  198. /// 备份库迁移教培试卷数据
  199. /// </summary>
  200. /// <returns></returns>
  201. public async Task MigrateExamPaperInfosAsync()
  202. {
  203. Logger.WriteLineInfo($"Exam Paper Infos Migrate Starting");
  204. var examPapers = _examinationPaperDBPepository.GetExaminationPapers(Builders<ExaminationPaper>.Filter.Where(x => x.IsDeleted == false))
  205. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  206. OnMigrate("exam paper", examPapers, SendExaminationPaperInfos);
  207. examPapers.Clear();
  208. Logger.WriteLineInfo($"Exam Paper Infos Migrate Successfully");
  209. }
  210. /// <summary>
  211. /// 备份库迁移报告数据
  212. /// </summary>
  213. /// <returns></returns>
  214. public async Task MigrateReportInfosAsync()
  215. {
  216. Logger.WriteLineInfo($"Report Infos Migrate Starting");
  217. var reports = _reportInfoResultDBRepository.GetReports(Builders<ReportInfoResults>.Filter.Where(x => true))
  218. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  219. OnMigrate("report", reports, SendReportInfos);
  220. reports.Clear();
  221. Logger.WriteLineInfo($"Report Infos Migrate Successfully");
  222. }
  223. /// <summary>
  224. /// 备份库迁移图像诊断结果数据
  225. /// </summary>
  226. /// <returns></returns>
  227. public async Task MigrateTerminalAIDataInfosAsync()
  228. {
  229. Logger.WriteLineInfo($"Terminal AI Data Infos Migrate Starting");
  230. var terminalAIDatas = _terminalAIDatasDBRepository.GetTerminalAIDatas(Builders<TerminalAIDatas>.Filter.Where(x => true))
  231. .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
  232. OnMigrate("terminal ai data", terminalAIDatas, SendTerminalAIDataInfos);
  233. terminalAIDatas.Clear();
  234. Logger.WriteLineInfo($"Terminal AI Data Infos Migrate Successfully");
  235. }
  236. private void OnMigrate<IEntity>(string name, IList<IEntity> source, Action<IList<IEntity>, SyncDBEnum> migrateAction, SyncDBEnum syncType = SyncDBEnum.Migrate, int processNumber = 100)
  237. {
  238. Logger.WriteLineInfo($"{name} totalCount:{source.Count}");
  239. var totalCount = source.Count;
  240. var processedCount = 0;
  241. var minute = DateTime.Now.Minute;
  242. while (true)
  243. {
  244. var pendingRecords = source.Skip(processedCount).Take(processNumber)?.ToList() ?? new List<IEntity>();
  245. var pendingCount = pendingRecords.Count;
  246. if (pendingCount > 0)
  247. {
  248. migrateAction.Invoke(pendingRecords, syncType);
  249. processedCount += pendingCount;
  250. }
  251. if (DateTime.Now.Minute != minute)
  252. {
  253. minute = DateTime.Now.Minute;
  254. Logger.WriteLineInfo($"{name} processing: {processedCount * 100 / totalCount}%");
  255. }
  256. if (pendingCount < processNumber)
  257. {
  258. Logger.WriteLineInfo($"{name} processing: 100%");
  259. break;
  260. }
  261. }
  262. }
  263. private void SendRemoteDiagnosisInfos(IList<TerminalRecords> terminalRecords, SyncDBEnum syncType)
  264. {
  265. try
  266. {
  267. var terminalRecordCodes = terminalRecords.Select(x => x.Id).ToList();
  268. var terminalDatas = _terminalDatasDBRepository.GetTerminalDatasByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalDatas>();
  269. var terminalRecordStates = _terminalRecordReportStatesDBRepository.GetTerminalRecordReportStatesByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalRecordReportStates>();
  270. var deviceCodes = terminalRecords.Select(x => x.Terminal?.Id ?? string.Empty).ToList();
  271. var terminals = _terminalsDBRepository.GetTerminalByCodes(deviceCodes)?.ToList() ?? new List<Terminals>();
  272. var orgCodes = terminalRecords.Select(x => x.Organization?.Id ?? string.Empty).ToList();
  273. if (terminals.Any())
  274. {
  275. var terminalOrgs = terminals.Select(x => x.Organization?.Id ?? string.Empty);
  276. orgCodes = orgCodes.Union(terminalOrgs).ToList();
  277. }
  278. var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgCodes)?.ToList() ?? new List<Organizations>();
  279. var remoteDiagnosisInfos = new List<RemoteDiagnosisDTO>();
  280. foreach (var terminalRecord in terminalRecords)
  281. {
  282. var terminalRecordId = terminalRecord.Id;
  283. var patientInfo = terminalRecord.PatientInfo;
  284. var terminalDataInfos = terminalDatas.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalDatas>();
  285. var terminalRecordStateInfos = terminalRecordStates.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalRecordReportStates>();
  286. var remoteDiagnosisInfo = new RemoteDiagnosisDTO
  287. {
  288. Code = terminalRecordId,
  289. CreateTime = terminalRecord.CreateTime,
  290. UpdateTime = terminalRecord.UpdateTime,
  291. ExamId = terminalRecord.ExamId,
  292. OrganizationInfo = MapToOrganizationView(organizations, terminalRecord.Organization?.Id),
  293. DeviceInfo = MapToDeviceView(terminals, terminalRecord.Terminal?.Id),
  294. QualifiedInfo = new QualifiedView
  295. {
  296. QualifiedState = (WingInterfaceLibrary.Enum.QualifiedState)terminalRecord.QualifiedState,
  297. QualityType = (WingInterfaceLibrary.Enum.QualityType)terminalRecord.QualityType,
  298. },
  299. DiagnosisInfos = new List<DiagnosisView>(),
  300. ShareUserCodes = terminalRecord.SharerIds?.ToList() ?? new List<string>(),
  301. CustomDoctor = terminalRecord.CustomDoctor,
  302. CustomOrganzation = terminalRecord.CustomOrganzation,
  303. EquipmentSN = terminalRecord.EquipmentSN,
  304. FileInfos = terminalDataInfos.Select(x =>
  305. {
  306. var fileInfo = x.Files.FirstOrDefault(f => f.ImageQuality == ImageQuality.High);
  307. var fileUrl = GetFileUrl(fileInfo?.FileName);
  308. var terminalData = new RemoteDiagnosisFileView
  309. {
  310. DataType = (WingInterfaceLibrary.Enum.RemedicalFileDataTypeEnum)x.DataType,
  311. OriginalUrl = GetSourceUrl(fileUrl),
  312. CdnUrl = fileUrl,
  313. PreviewUrl = GetFileUrl(x.PreviewImageFileToken),
  314. ConverUrl = "",
  315. Application = x.Application,
  316. };
  317. if (x.ImageLocation != null)
  318. {
  319. if (x.ImageLocation is BreastImageLocation bi)
  320. {
  321. terminalData.ImageLocationInfo = new ImageLocationView
  322. {
  323. Group = "BreastImageLocation",
  324. Position = bi.Position.ToString(),
  325. Quadrant = bi.Quadrant.ToString(),
  326. };
  327. }
  328. if (x.ImageLocation is LiverImageLocation li)
  329. {
  330. terminalData.ImageLocationInfo = new ImageLocationView
  331. {
  332. Group = "LiverImageLocation",
  333. Position = li.Position.ToString(),
  334. };
  335. }
  336. if (x.ImageLocation is PositionImageLocation pi)
  337. {
  338. terminalData.ImageLocationInfo = new ImageLocationView
  339. {
  340. Group = pi.Position,
  341. Position = pi.Position.ToString(),
  342. };
  343. }
  344. }
  345. return terminalData;
  346. }).ToList(),
  347. CompletedUsers = terminalRecordStateInfos.Select(x => x.UserId).ToList(),
  348. };
  349. if (patientInfo != null)
  350. {
  351. remoteDiagnosisInfo.PatientInfo = new PatientView
  352. {
  353. IdentityCardId = patientInfo.IdentityCardId,
  354. Name = patientInfo.LastName,
  355. Gender = patientInfo.GenderType.ToString(),
  356. Age = patientInfo.Age,
  357. };
  358. }
  359. if (terminalRecord.TerminalRecordSource == TerminalRecordSource.Screenshot)
  360. {
  361. remoteDiagnosisInfo.ScreenshotInfo = new ScreenshotView
  362. {
  363. CreateUserCode = terminalRecord.CreatorUserId,
  364. CreateUserName = "",
  365. PrelDiagnosis = terminalRecord.PrelDiagnosis,
  366. ExamDoctor = terminalRecord.ExamDoctor,
  367. };
  368. }
  369. if (terminalRecord.AIDiagnosisInfos != null && terminalRecord.AIDiagnosisInfos.Any())
  370. {
  371. remoteDiagnosisInfo.DiagnosisInfos = terminalRecord.AIDiagnosisInfos.Select(x => new DiagnosisView
  372. {
  373. Organ = (WingInterfaceLibrary.Enum.DiagnosisOrganEnum)x.Organ,
  374. DiagnosisStatus = (WingInterfaceLibrary.Enum.DiagnosisConclusionEnum)x.Status,
  375. }).ToList();
  376. }
  377. remoteDiagnosisInfos.Add(remoteDiagnosisInfo);
  378. }
  379. var request = new ReceiveRemoteDiagnosisRequest
  380. {
  381. RemoteDiagnosisInfos = remoteDiagnosisInfos,
  382. };
  383. var result = _jsonRpcProxy.DataCenter.ReceiveRemoteDiagnosisAsync(request).Result;
  384. }
  385. catch (Exception ex)
  386. {
  387. Logger.WriteLineWarn($"SendRemoteDiagnosisInfos err, ex:{ex}");
  388. }
  389. }
  390. private void SendLiveConsultationInfos(IList<ConsultationRecords> consultationRecords, SyncDBEnum syncType)
  391. {
  392. try
  393. {
  394. var userIds = consultationRecords.Select(x => x.DoctorInfo?.ID ?? string.Empty)
  395. .Union(consultationRecords.Select(x => x.ExpertInfo?.ID ?? string.Empty))
  396. .Distinct().ToList();
  397. var users = _usersDBRepository.GetUserByCodes(userIds);
  398. var orgIds = consultationRecords.Select(x => x.PrimaryHosptial?.Id ?? string.Empty)
  399. .Union(consultationRecords.Select(x => x.CentralHospital?.Id ?? string.Empty))
  400. .Union(users.Select(x => x.HospitalId))
  401. .Distinct().ToList();
  402. var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
  403. var terminalIds = consultationRecords.Select(x => x.TerminalInfo?.Id ?? string.Empty).Distinct().ToList();
  404. var terminals = _terminalsDBRepository.GetTerminalByCodes(terminalIds);
  405. var liveConsultationInfos = new List<LiveConsultationDTO>();
  406. foreach (var consultationRecord in consultationRecords)
  407. {
  408. var patient = consultationRecord.PatientInfo;
  409. var liveConsultationInfo = new LiveConsultationDTO
  410. {
  411. Code = consultationRecord.Id,
  412. CreateTime = consultationRecord.CreateTime,
  413. UpdateTime = consultationRecord.UpdateTime,
  414. ScanUserName = consultationRecord.ScanDoctor,
  415. ConsultationTime = consultationRecord.AppointmentTime,
  416. DoctorInfo = MapToUserView(organizations, users, consultationRecord.DoctorInfo?.ID),
  417. ExpertInfo = MapToUserView(organizations, users, consultationRecord.ExpertInfo?.ID),
  418. PrimaryHosptial = MapToOrganizationView(organizations, consultationRecord.PrimaryHosptial?.Id),
  419. CentralHospital = MapToOrganizationView(organizations, consultationRecord.CentralHospital?.Id),
  420. DeviceInfo = MapToDeviceView(terminals, consultationRecord.TerminalInfo?.Id),
  421. CheckPoint = consultationRecord.CheckPoint,
  422. ConsultationNumber = consultationRecord.ConsultationNumber,
  423. QueuingNumber = consultationRecord.QueuingNumber,
  424. IsNeedFollowUpVisit = consultationRecord.IsNeedFollowUpVisit,
  425. State = (WingInterfaceLibrary.Enum.ConsultationState)consultationRecord.State,
  426. QualityType = (WingInterfaceLibrary.Enum.QualityType)consultationRecord.QualityType,
  427. FollowUpVisitStatus = (FollowUpVisitStatusEnum)consultationRecord.FollowUpVisitStatus,
  428. EvaluateGrade = (EvaluateGradeEnum)consultationRecord.EvaluateGrade,
  429. FileInfos = new List<LiveConsultationFileView>(),
  430. ReportConclusionInfos = new List<ReportConclusionView>(),
  431. };
  432. if (patient != null)
  433. {
  434. liveConsultationInfo.PatientInfo = new PatientView
  435. {
  436. IdentityCardId = patient.ID,
  437. Name = patient.Name,
  438. Mobile = patient.ContactInfo,
  439. Gender = patient.GenderType.ToString(),
  440. Age = patient.Age,
  441. //PastHistory = patient.PastHistory,
  442. //Diagnosis = patient.Diagnosis,
  443. };
  444. }
  445. if (consultationRecord.ImageTokens != null && consultationRecord.ImageTokens.Any())
  446. {
  447. foreach (var item in consultationRecord.ImageTokens)
  448. {
  449. liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
  450. {
  451. Type = "FileTokens",
  452. DataType = RemedicalFileDataTypeEnum.VinnoVidSingle,
  453. OriginalUrl = GetSourceUrl(item),
  454. CdnUrl = GetFileUrl(item),
  455. PreviewUrl = "",
  456. ConverUrl = "",
  457. });
  458. }
  459. }
  460. if (consultationRecord.VideoTokens != null && consultationRecord.VideoTokens.Any())
  461. {
  462. foreach (var item in consultationRecord.VideoTokens)
  463. {
  464. liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
  465. {
  466. Type = "FileTokens",
  467. DataType = RemedicalFileDataTypeEnum.VinnoVidMovie,
  468. OriginalUrl = GetSourceUrl(item.VideoToken),
  469. CdnUrl = GetFileUrl(item.VideoToken),
  470. PreviewUrl = GetFileUrl(item.PreviewImageToken),
  471. ConverUrl = "",
  472. });
  473. }
  474. }
  475. if (consultationRecord.GraphicData != null && consultationRecord.GraphicData.Any())
  476. {
  477. foreach (var item in consultationRecord.GraphicData)
  478. {
  479. liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
  480. {
  481. Type = "GraphicData",
  482. DataType = item.GraphicType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie,
  483. OriginalUrl = GetSourceUrl(item.GraphicToken),
  484. CdnUrl = GetFileUrl(item.GraphicToken),
  485. PreviewUrl = GetFileUrl(item.PreviewGraphicToken),
  486. ConverUrl = "",
  487. UserCode = item.UserId,
  488. });
  489. }
  490. }
  491. if (consultationRecord.PreFileItems != null && consultationRecord.PreFileItems.Any())
  492. {
  493. foreach (var item in consultationRecord.PreFileItems)
  494. {
  495. liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
  496. {
  497. Type = "PreFileItems",
  498. DataType = item.FileType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie,
  499. OriginalUrl = GetSourceUrl(item.OriginalFileUrl),
  500. CdnUrl = GetFileUrl(item.OriginalFileUrl),
  501. PreviewUrl = GetFileUrl(item.ThumbnailUrl),
  502. ConverUrl = "",
  503. UserCode = item.Uploader,
  504. FileName = item.FileName,
  505. });
  506. }
  507. }
  508. if (consultationRecord.ReportConclusionInfos != null && consultationRecord.ReportConclusionInfos.Any())
  509. {
  510. foreach (var item in consultationRecord.ReportConclusionInfos)
  511. {
  512. liveConsultationInfo.ReportConclusionInfos.Add(new ReportConclusionView
  513. {
  514. ReportId = item.ReportId,
  515. DiseaseName = item.DiseaseName,
  516. DiseaseConclusion = (WingInterfaceLibrary.Enum.DiseaseConclusion)item.DiseaseConclusion,
  517. });
  518. }
  519. }
  520. liveConsultationInfos.Add(liveConsultationInfo);
  521. }
  522. var request = new ReceiveLiveConsultationRequest
  523. {
  524. LiveConsultationInfos = liveConsultationInfos,
  525. };
  526. var result = _jsonRpcProxy.DataCenter.ReceiveLiveConsultationAsync(request).Result;
  527. }
  528. catch (Exception ex)
  529. {
  530. Logger.WriteLineWarn($"SendLiveConsultationInfos err, ex:{ex}");
  531. }
  532. }
  533. private void SendVideoInfos(IList<Video> videos, SyncDBEnum syncType)
  534. {
  535. try
  536. {
  537. var userIds = videos.Select(x => x.CreatorId)
  538. .Union(videos.SelectMany(x => x.UserIds ?? new List<string>()))
  539. .Union(videos.SelectMany(x => x.FinishedUserIds ?? new List<string>()))
  540. .Distinct().ToList();
  541. var users = _usersDBRepository.GetUserByCodes(userIds);
  542. var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
  543. var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
  544. var userGroupIds = videos.SelectMany(x => x.UserGroupIds ?? new List<string>()).Distinct().ToList();
  545. var userGroups = _userGroupDBRepository.GetUserGroupByCodes(userGroupIds);
  546. var classIds = videos.SelectMany(x => x.ClassIds ?? new List<string>()).Distinct().ToList();
  547. var classes = _ultrasonicClassDBRepository.GetUltrasonicClassByCodes(classIds);
  548. //var courseIds = videos.SelectMany(x => x.Courses ?? new List<VideoLinkCourseInfo>()).Select(x => x.Id).Distinct().ToList();
  549. //var courses = _coursesDBRepository.GetCourseByCodes(courseIds);
  550. var onlineVideoInfos = new List<OnlineVideoDTO>();
  551. foreach (var video in videos)
  552. {
  553. var creator = MapToUserView(organizations, users, video.CreatorId);
  554. var videoInfo = new OnlineVideoDTO
  555. {
  556. Code = video.Id,
  557. CreateTime = video.CreateTime,
  558. UpdateTime = video.UpdateTime,
  559. Name = video.Title,
  560. Poster = GetFileUrl(video.PosterToken),
  561. Duration = video.Duration,
  562. VideoSize = video.Size,
  563. Description = video.Description,
  564. VideoToken = video.Url,
  565. Importance = (VideoImportanceEnum)video.Importance,
  566. CreatorCode = video.CreatorId,
  567. CreatorName = creator?.Name,
  568. Permissions = (VideoPermissionsEnum)video.Permissions,
  569. Users = new List<UserView>(),
  570. UserGroups = new List<GroupView>(),
  571. Courses = new List<OnlineTrainingDTO>(),
  572. ClassInfos = new List<ClassView>(),
  573. Labels = new List<VideoLabelEnum>(),
  574. TeachingDocumentName = video.TeachingDocumentName,
  575. TeachingDocument = GetFileUrl(video.TeachingDocument),
  576. RealBrowsedCount = video.RealBrowsedCount,
  577. BaseBrowsedCount = video.BaseBrowsedCount,
  578. FinishedUsers = new List<UserView>(),
  579. };
  580. if (video.UserIds != null && video.UserIds.Any())
  581. {
  582. foreach (var item in video.UserIds)
  583. {
  584. var user = MapToUserView(organizations, users, item);
  585. if (user != null)
  586. {
  587. videoInfo.Users.Add(user);
  588. }
  589. }
  590. }
  591. if (video.FinishedUserIds != null && video.FinishedUserIds.Any())
  592. {
  593. foreach (var item in video.FinishedUserIds)
  594. {
  595. var user = MapToUserView(organizations, users, item);
  596. if (user != null)
  597. {
  598. videoInfo.FinishedUsers.Add(user);
  599. }
  600. }
  601. }
  602. if (video.Labels != null && video.Labels.Any())
  603. {
  604. foreach (var item in video.Labels)
  605. {
  606. videoInfo.Labels.Add((VideoLabelEnum)item);
  607. }
  608. }
  609. if (video.Courses != null && video.Courses.Any())
  610. {
  611. foreach (var item in video.Courses)
  612. {
  613. videoInfo.Courses.Add(new OnlineTrainingDTO
  614. {
  615. Code = item.Id,
  616. Name = item.Name,
  617. });
  618. }
  619. }
  620. if (video.UserGroupIds != null && video.UserGroupIds.Any())
  621. {
  622. foreach (var item in video.UserGroupIds)
  623. {
  624. var userGroup = MapToUserGroupView(userGroups, item);
  625. if (userGroup != null)
  626. {
  627. videoInfo.UserGroups.Add(userGroup);
  628. }
  629. }
  630. }
  631. if (video.ClassIds != null && video.ClassIds.Any())
  632. {
  633. foreach (var item in video.ClassIds)
  634. {
  635. var classInfo = MapToClassView(classes, item);
  636. if (classInfo != null)
  637. {
  638. videoInfo.ClassInfos.Add(classInfo);
  639. }
  640. }
  641. }
  642. onlineVideoInfos.Add(videoInfo);
  643. }
  644. var request = new ReceiveOnlineVideoRequest
  645. {
  646. OnlineVideoInfos = onlineVideoInfos,
  647. };
  648. var result = _jsonRpcProxy.DataCenter.ReceiveOnlineVideoAsync(request).Result;
  649. }
  650. catch (Exception ex)
  651. {
  652. Logger.WriteLineWarn($"SendVideoInfos err, ex:{ex}");
  653. }
  654. }
  655. private void SendCourseInfos(IList<Courses> courses, SyncDBEnum syncType)
  656. {
  657. try
  658. {
  659. var userIds = courses.SelectMany(x => x.AssistantIds ?? new List<string>())
  660. .Union(courses.SelectMany(x => x.GuestIds ?? new List<string>()))
  661. .Union(courses.SelectMany(x => x.MeetingMemberIds ?? new List<string>()))
  662. .Distinct().ToList();
  663. var users = _usersDBRepository.GetUserByCodes(userIds);
  664. var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
  665. var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
  666. var onlineTrainingInfos = new List<OnlineTrainingDTO>();
  667. foreach (var course in courses)
  668. {
  669. var teacher = course.Teacher;
  670. var createAdmin = course.CreateAdmin;
  671. var courseInfo = new OnlineTrainingDTO
  672. {
  673. Code = course.Id,
  674. CreateTime = course.CreateTime,
  675. UpdateTime = course.UpdateTime,
  676. Name = course.Name,
  677. CourseIntro = course.Information,
  678. Price = (decimal)course.Price,
  679. Status = (CourseStatusEnum)course.State,//TODO
  680. StartTime = course.StarTime,
  681. Duration = course.Duration,
  682. Deadline = course.Deadline,
  683. ApplyState = (ApplyStateEnum)course.ApplyState,//TODO
  684. Poster = GetFileUrl(course.Poster),
  685. Students = new List<SignStudentView>(),
  686. ConversationId = course.ConversationId,//TODO
  687. ChannelDatas = new List<ChannelDataView>(),
  688. Owners = new List<AdminView>(),
  689. TeacherOnlineState = course.TeacherState == TeacherState.OnLine,
  690. StartCourseInAdvance = course.StartCourseInAdvance,
  691. ActualStartTime = course.ActualStartTime ?? DateTime.MinValue,
  692. ActualEndTime = course.ActualEndTime ?? DateTime.MinValue,
  693. AssistantInfos = new List<UserView>(),
  694. GuestInfos = new List<UserView>(),
  695. CredentialCode = course.CredentialCode,
  696. CourseNotice = course.CourseNotice,
  697. MeetingMemberInfos = new List<UserView>(),
  698. };
  699. if (teacher != null)
  700. {
  701. var name = !string.IsNullOrWhiteSpace(teacher.FullName) ? teacher.FullName
  702. : !string.IsNullOrWhiteSpace(teacher.LastName) ? teacher.LastName
  703. : !string.IsNullOrWhiteSpace(teacher.FirstName) ? teacher.FirstName
  704. : !string.IsNullOrWhiteSpace(teacher.NickName) ? teacher.NickName
  705. : teacher.Name;
  706. courseInfo.TeacherCode = teacher.Id;
  707. courseInfo.TeacherName = name;
  708. }
  709. if (course.ChannelDatas != null && course.ChannelDatas.Any())
  710. {
  711. foreach (var item in course.ChannelDatas)
  712. {
  713. courseInfo.ChannelDatas.Add(new ChannelDataView
  714. {
  715. ChannelId = item.ChannelId,
  716. DownLoadUrl = item.DownLoadUrl,
  717. UpLoadUrl = item.UpLoadUrl,
  718. Description = (ChannelDescriptionEnum)item.Description,
  719. HttpUrl = item.HttpUrl,
  720. HlsUrl = item.HlsUrl,
  721. });
  722. }
  723. }
  724. if (course.Students != null && course.Students.Any())
  725. {
  726. foreach (var item in course.Students)
  727. {
  728. courseInfo.Students.Add(new SignStudentView
  729. {
  730. StudentCode = item.Id,
  731. StudentName = item.Name,
  732. SmallHeadImage = item.SmallHeadImage,
  733. IsNoSpeaking = item.IsNoSpeaking,
  734. IsAssistant = item.IsAssistant,
  735. });
  736. }
  737. }
  738. if (createAdmin != null)
  739. {
  740. courseInfo.CreateAdmin = new AdminView
  741. {
  742. Code = createAdmin._id,
  743. Name = createAdmin.Name,
  744. };
  745. }
  746. if (course.Owners != null && course.Owners.Any())
  747. {
  748. foreach (var item in course.Owners)
  749. {
  750. courseInfo.Owners.Add(new AdminView
  751. {
  752. Code = item._id,
  753. Name = item.Name,
  754. });
  755. }
  756. }
  757. if (course.AssistantIds != null && course.AssistantIds.Any())
  758. {
  759. foreach (var item in course.AssistantIds)
  760. {
  761. var user = MapToUserView(organizations, users, item);
  762. if (user != null)
  763. {
  764. courseInfo.AssistantInfos.Add(user);
  765. }
  766. }
  767. }
  768. if (course.GuestIds != null && course.GuestIds.Any())
  769. {
  770. foreach (var item in course.GuestIds)
  771. {
  772. var user = MapToUserView(organizations, users, item);
  773. if (user != null)
  774. {
  775. courseInfo.GuestInfos.Add(user);
  776. }
  777. }
  778. }
  779. if (course.MeetingMemberIds != null && course.MeetingMemberIds.Any())
  780. {
  781. foreach (var item in course.MeetingMemberIds)
  782. {
  783. var user = MapToUserView(organizations, users, item);
  784. if (user != null)
  785. {
  786. courseInfo.MeetingMemberInfos.Add(user);
  787. }
  788. }
  789. }
  790. onlineTrainingInfos.Add(courseInfo);
  791. }
  792. var request = new ReceiveOnlineTrainingRequest
  793. {
  794. OnlineTrainingInfos = onlineTrainingInfos,
  795. };
  796. var result = _jsonRpcProxy.DataCenter.ReceiveOnlineTrainingAsync(request).Result;
  797. }
  798. catch (Exception ex)
  799. {
  800. Logger.WriteLineWarn($"SendCourseInfos err, ex:{ex}");
  801. }
  802. }
  803. private void SendExaminationPaperInfos(IList<ExaminationPaper> examPapers, SyncDBEnum syncType)
  804. {
  805. try
  806. {
  807. var userIds = examPapers.Select(x => x.CreatorId)
  808. .Union(examPapers.SelectMany(x => x.ExaminerIds ?? new List<string>()))
  809. .Distinct().ToList();
  810. var users = _usersDBRepository.GetUserByCodes(userIds);
  811. var admins = _adminDBRepository.GetAdminByCodes(userIds);
  812. var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
  813. var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
  814. var userGroupIds = examPapers.SelectMany(x => x.ExaminerUserGroupIds ?? new List<string>()).Distinct().ToList();
  815. var userGroups = _userGroupDBRepository.GetUserGroupByCodes(userGroupIds);
  816. var classIds = examPapers.SelectMany(x => x.ClassIds ?? new List<string>()).Distinct().ToList();
  817. var classes = _ultrasonicClassDBRepository.GetUltrasonicClassByCodes(classIds);
  818. var examIds = examPapers.Select(x => x.Id).ToList();
  819. var examScores = _examScoreDBRepository.GetExamScoresByCodes(examIds);
  820. var examPaperInfos = new List<ExamPaperDTO>();
  821. foreach (var examPaper in examPapers)
  822. {
  823. var creatorName = MapToUserView(organizations, users, examPaper.CreatorId)?.Name;
  824. if (string.IsNullOrWhiteSpace(creatorName))
  825. {
  826. var admin = admins.FirstOrDefault(x => x.Id == examPaper.CreatorId);
  827. if (admin != null)
  828. {
  829. var adminName = !string.IsNullOrWhiteSpace(admin.FullName) ? admin.FullName
  830. : !string.IsNullOrWhiteSpace(admin.LastName) ? admin.LastName
  831. : !string.IsNullOrWhiteSpace(admin.FirstName) ? admin.FirstName
  832. : admin.Name;
  833. creatorName = adminName;
  834. }
  835. }
  836. var examPaperInfo = new ExamPaperDTO
  837. {
  838. Code = examPaper.Id,
  839. CreateTime = examPaper.CreateTime,
  840. UpdateTime = examPaper.UpdateTime,
  841. Name = examPaper.Title,
  842. Description = examPaper.Description,
  843. StarTime = examPaper.StarTime,
  844. EndTime = examPaper.EndTime,
  845. TotalScore = examPaper.TotalScore,
  846. LimitCount = examPaper.LimitCount,
  847. Result = examPaper.Result,
  848. Examiners = new List<UserView>(),
  849. ExaminerUserGroups = new List<GroupView>(),
  850. ExaminationAvailability = (ExaminationAvailabilityEnum)examPaper.ExaminationAvailability,
  851. Classes = new List<ClassView>(),
  852. CreatorId = examPaper.CreatorId,
  853. CreatorName = creatorName,
  854. ExamType = (ExamTypeEnum)examPaper.ExamType,
  855. HasPassScore = examPaper.HasPassScore,
  856. PassScore = examPaper.PassScore,
  857. IsDisplayAnswer = examPaper.IsDisplayAnswer,
  858. ExamVideoInfos = new List<ExamVideoView>(),
  859. ExamScoreInfos = new List<ExamScoreView>(),
  860. };
  861. if (examPaper.ExaminerIds != null && examPaper.ExaminerIds.Any())
  862. {
  863. foreach (var item in examPaper.ExaminerIds)
  864. {
  865. var user = MapToUserView(organizations, users, item);
  866. if (user != null)
  867. {
  868. examPaperInfo.Examiners.Add(user);
  869. }
  870. }
  871. }
  872. if (examPaper.ExaminerUserGroupIds != null && examPaper.ExaminerUserGroupIds.Any())
  873. {
  874. foreach (var item in examPaper.ExaminerUserGroupIds)
  875. {
  876. var userGroup = MapToUserGroupView(userGroups, item);
  877. if (userGroup != null)
  878. {
  879. examPaperInfo.ExaminerUserGroups.Add(userGroup);
  880. }
  881. }
  882. }
  883. if (examPaper.ClassIds != null && examPaper.ClassIds.Any())
  884. {
  885. foreach (var item in examPaper.ClassIds)
  886. {
  887. var classInfo = MapToClassView(classes, item);
  888. if (classInfo != null)
  889. {
  890. examPaperInfo.Classes.Add(classInfo);
  891. }
  892. }
  893. }
  894. if (examPaper.ExamVideoInfos != null && examPaper.ExamVideoInfos.Any())
  895. {
  896. foreach (var item in examPaper.ExamVideoInfos)
  897. {
  898. examPaperInfo.ExamVideoInfos.Add(new ExamVideoView
  899. {
  900. Id = item.Id,
  901. VideoName = item.VideoName,
  902. CreateTime = item.CreateTime,
  903. PosterToken = GetFileUrl(item.PosterToken),
  904. Duration = item.Duration,
  905. Size = item.Size,
  906. Description = item.Description,
  907. Url = GetFileUrl(item.Url),
  908. });
  909. }
  910. }
  911. if (examPaper.ExamTemplate != null)
  912. {
  913. var examTemplate = examPaper.ExamTemplate.MappingTo<ExamTemplateView>();
  914. if (examTemplate != null && examTemplate.Subjects != null && examTemplate.Subjects.Any())
  915. {
  916. foreach (var item in examTemplate.Subjects)
  917. {
  918. item.Images = item.Images?.Select(x => GetFileUrl(x))?.ToList() ?? new List<string>();
  919. if (item.Videos != null && item.Videos.Any())
  920. {
  921. item.Videos?.ForEach(x =>
  922. {
  923. x.VideoImageToken = GetFileUrl(x.VideoImageToken);
  924. x.VideoToken = GetFileUrl(x.VideoToken);
  925. });
  926. }
  927. }
  928. }
  929. examPaperInfo.ExamTemplate = examTemplate;
  930. }
  931. var examScoreInfos = examScores.Where(x => x.ExamId == examPaper.Id)?.ToList() ?? new List<ExamScores>();
  932. if (examScoreInfos.Any())
  933. {
  934. examPaperInfo.ExamScoreInfos = examScoreInfos.MappingTo<List<ExamScoreView>>();
  935. }
  936. examPaperInfos.Add(examPaperInfo);
  937. }
  938. var request = new ReceiveExamPaperInfosRequest
  939. {
  940. ExamPaperInfos = examPaperInfos,
  941. };
  942. var result = _jsonRpcProxy.DataCenter.ReceiveExamPaperAsync(request).Result;
  943. }
  944. catch (Exception ex)
  945. {
  946. Logger.WriteLineWarn($"SendCourseInfos err, ex:{ex}");
  947. }
  948. }
  949. private void SendReportInfos(IList<ReportInfoResults> reports, SyncDBEnum syncType)
  950. {
  951. try
  952. {
  953. var customLabelIds = reports.SelectMany(x => x.CustomLabels ?? new List<string>()).Distinct().ToList();
  954. var customerLabels = _customLabelDBRepository.GetCustomLabelByCodes(customLabelIds);
  955. var reportInfos = new List<ReportInfoResultDTO>();
  956. foreach (var report in reports)
  957. {
  958. var reportInfo = new ReportInfoResultDTO
  959. {
  960. Code = report.Id,
  961. CreateTime = report.CreateTime,
  962. UpdateTime = report.UpdateTime,
  963. ReportTemplateJson = report.Template,
  964. ElementCollectionJson = Newtonsoft.Json.JsonConvert.SerializeObject(report.ElementCollection),
  965. MeasureElementCollectionJson = Newtonsoft.Json.JsonConvert.SerializeObject(report.MeasureElementCollection),
  966. ReportUserCode = report.User?._id,
  967. ReportUserName = report.User?.Name,
  968. RecordCode = report.RecordId,
  969. PatientPerfPhysician = report.PatientPerfPhysician,
  970. PatientRefPhysician = report.PatientRefPhysician,
  971. PatientName = report.PatientName,
  972. PreviewImages = report.PreviewImages.MappingTo<List<WingInterfaceLibrary.DTO.DataCenter.ReportImageInfo>>(),
  973. CustomLabels = new List<CustomLabelView>(),
  974. ReportOrgan = (DiagnosisOrganEnum)report.Organ,
  975. QualifiedState = (WingInterfaceLibrary.Enum.QualifiedState)report.QualifiedState,
  976. QualityType = (WingInterfaceLibrary.Enum.QualityType)report.QualityType,
  977. ReportPreviewPdf = GetFileUrl(report.ReportPreviewPdf),
  978. QualityControlDatas = new List<QualityControlDataView>(),
  979. };
  980. if (report.CustomLabels != null && report.CustomLabels.Any())
  981. {
  982. foreach (var item in report.CustomLabels)
  983. {
  984. var customLabel = customerLabels.FirstOrDefault(x => x.Code == item);
  985. if (customLabel != null)
  986. {
  987. reportInfo.CustomLabels.Add(customLabel.MappingTo<CustomLabelView>());
  988. }
  989. }
  990. }
  991. if (report.QualityControlDatas != null && report.QualityControlDatas.Any())
  992. {
  993. reportInfo.QualityControlDatas = report.QualityControlDatas.MappingTo<List<QualityControlDataView>>();
  994. }
  995. reportInfos.Add(reportInfo);
  996. }
  997. var request = new ReceiveReportInfosRequest
  998. {
  999. ReportInfos = reportInfos,
  1000. };
  1001. var result = _jsonRpcProxy.DataCenter.ReceiveReportAsync(request).Result;
  1002. }
  1003. catch (Exception ex)
  1004. {
  1005. Logger.WriteLineWarn($"SendReportInfos err, ex:{ex}");
  1006. }
  1007. }
  1008. private void SendTerminalAIDataInfos(IList<TerminalAIDatas> terminalAIDatas, SyncDBEnum syncType)
  1009. {
  1010. try
  1011. {
  1012. var fileDiagnosisInfos = new List<FileDiagnosisResultDTO>();
  1013. foreach (var terminalAIData in terminalAIDatas)
  1014. {
  1015. var fileDiagnosisResult = new FileDiagnosisResultDTO
  1016. {
  1017. Code = terminalAIData.Id,
  1018. CreateTime = terminalAIData.CreateTime,
  1019. UpdateTime = terminalAIData.UpdateTime,
  1020. RemedicalCode = terminalAIData.TerminalDataId,
  1021. };
  1022. var diagnosisDatas = new List<AIDiagnosisPerImg>();
  1023. foreach (var item in terminalAIData.DiagResults)
  1024. {
  1025. diagnosisDatas.Add(new AIDiagnosisPerImg
  1026. {
  1027. Index = item.Index,
  1028. PriorityScore = item.ImageDiagResult.PriorityScore,
  1029. DiagResultsForEachOrgan = item.ImageDiagResult.DiagResultsForEachOrgan,
  1030. });
  1031. }
  1032. fileDiagnosisResult.DiagnosisOrgans = GetDiagnosisOrgans(diagnosisDatas);
  1033. fileDiagnosisResult.DiagnosisConclusion = GetDiagnosisConclusion(diagnosisDatas);
  1034. fileDiagnosisResult.DiagnosisResult = Newtonsoft.Json.JsonConvert.SerializeObject(diagnosisDatas);
  1035. fileDiagnosisInfos.Add(fileDiagnosisResult);
  1036. }
  1037. var request = new ReceiveFileDiagnosisResultInfosRequest
  1038. {
  1039. FileDiagnosisResultInfos = fileDiagnosisInfos,
  1040. };
  1041. var result = _jsonRpcProxy.DataCenter.ReceiveFileDiagnosisResultAsync(request).Result;
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. Logger.WriteLineWarn($"SendTerminalAIDataInfos err, ex:{ex}");
  1046. }
  1047. }
  1048. /// <summary>
  1049. /// 同步热数据到2.0
  1050. /// </summary>
  1051. /// <returns></returns>
  1052. public async Task MigrateRemedicalAndConsultationToWingServerAsync(int batchExcuteRemedicalDataCount)
  1053. {
  1054. Logger.WriteLineInfo($"Remote diagnosis infos migrate to wingServer starting");
  1055. //远程
  1056. await MigrateRemedicalRecords(SyncDBEnum.Synchronize);
  1057. //远程图像
  1058. MigrateRemedicalDatas(SyncDBEnum.Synchronize, batchExcuteRemedicalDataCount);
  1059. //AI
  1060. MigrateRemedicalAIDatas(SyncDBEnum.Synchronize);
  1061. //颈动脉
  1062. MigrateRemedicalCarotidDatas(SyncDBEnum.Synchronize);
  1063. //会诊
  1064. MigrateConsultationResults(SyncDBEnum.Synchronize);
  1065. //报告
  1066. MigrateReportInfoResults(SyncDBEnum.Synchronize);
  1067. Logger.WriteLineInfo($"Remote diagnosis infos migrate to wingServer successfully");
  1068. }
  1069. public async Task MigrateRemedicalRecords(SyncDBEnum syncType)
  1070. {
  1071. Logger.WriteLineInfo($"Remote diagnosis records migrate to wingServer starting");
  1072. //获取上次同步到的时间
  1073. var builder = Builders<TerminalRecords>.Filter;
  1074. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1075. var terminalRecords = new List<TerminalRecords>();
  1076. try
  1077. {
  1078. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1079. var tempTerminalRecords = _terminalRecordDBRepository.GetTerminalRecords(filter).OrderByDescending(x => x.CreateTime).ToList();
  1080. terminalRecords = await FilterData<TerminalRecords>(tempTerminalRecords, "TerminalRecordsData");
  1081. OnMigrate("Remote diagnosis records", terminalRecords, SendRemedicalRecordInfos, syncType, 100);
  1082. terminalRecords.Clear();
  1083. Logger.WriteLineInfo($"Remote diagnosis records migrate to wingServer successfully");
  1084. }
  1085. catch (Exception ex)
  1086. {
  1087. Logger.WriteLineInfo($"Remote diagnosis records migrate migrate to wingServer Error: {ex}");
  1088. }
  1089. finally
  1090. {
  1091. Logger.WriteLineInfo($"Remote diagnosis records migrate migrate to wingServer successfully, result:{terminalRecords?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1092. if (terminalRecords != null)
  1093. {
  1094. terminalRecords.Clear();
  1095. }
  1096. }
  1097. }
  1098. private void SendRemedicalRecordInfos(IList<TerminalRecords> terminalRecords, SyncDBEnum syncType)
  1099. {
  1100. try
  1101. {
  1102. var terminalRecordCodes = terminalRecords.Select(x => x.Id).ToList();
  1103. var terminalRecordStates = _terminalRecordReportStatesDBRepository.GetTerminalRecordReportStatesByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalRecordReportStates>();
  1104. var terminalIds = terminalRecords.Select(x => x.Terminal?.Id ?? string.Empty).Distinct().ToList();
  1105. var terminals = _terminalsDBRepository.GetTerminalByCodes(terminalIds);
  1106. var syncBatchRemedicalRecordRequest = new SyncBatchRemedicalRecordRequest();
  1107. syncBatchRemedicalRecordRequest.SyncType = syncType;
  1108. syncBatchRemedicalRecordRequest.RemedicalRecordList = new List<SyncRemedicalRecordRequest>();
  1109. foreach (var terminalRecord in terminalRecords)
  1110. {
  1111. try
  1112. {
  1113. var terminalRecordId = terminalRecord.Id;
  1114. var terminalRecordStateInfos = terminalRecordStates.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalRecordReportStates>();
  1115. var terminal = terminals.FirstOrDefault(x => x.Id == terminalRecord.Terminal?.Id);
  1116. var patientInfo = terminalRecord.PatientInfo;
  1117. var remoteDiagnosisInfo = new SyncRemedicalRecordRequest
  1118. {
  1119. Code = terminalRecordId,
  1120. OrganizationCode = terminalRecord.Organization?.Id,
  1121. DeviceCode = terminalRecord.Terminal?.Id,
  1122. CreateTime = terminalRecord.CreateTime,
  1123. Creator = terminalRecord.CreatorUserId,
  1124. UpdateTime = terminalRecord.UpdateTime < new DateTime(2000, 1, 1) ? terminalRecord.CreateTime : terminalRecord.UpdateTime,
  1125. IsUploadReport = terminalRecordStateInfos.Count > 0,
  1126. IsDelete = terminalRecord.IsDelete,
  1127. CustomDoctor = terminalRecord.CustomDoctor,
  1128. CustomOrganzation = terminalRecord.CustomOrganzation,
  1129. EquipmentSN = terminalRecord.EquipmentSN,
  1130. PatientInfo = new List<DataItemDTO>
  1131. {
  1132. new DataItemDTO{Key="Name",Value=$"{patientInfo.LastName} {patientInfo.FirstName}".Trim()},
  1133. new DataItemDTO{Key="Phone",Value=patientInfo.Mobile},
  1134. new DataItemDTO{Key="ID",Value=patientInfo.IdentityCardId},//设备病人ID
  1135. new DataItemDTO{Key="Sex",Value = patientInfo.GenderType.ToString()=="Unassigned"?"NotFilled":patientInfo.GenderType.ToString()},
  1136. }
  1137. };
  1138. if (CommonConfigManager.SpecialOrgCodes.Contains(remoteDiagnosisInfo.OrganizationCode))
  1139. {
  1140. remoteDiagnosisInfo.OrganizationCode = "VINNO_FIS";
  1141. }
  1142. if (patientInfo.Birthday != null && patientInfo.Birthday > new DateTime(1900, 1, 1))
  1143. {
  1144. remoteDiagnosisInfo.PatientInfo.Add(new DataItemDTO { Key = "Birthday", Value = ((DateTime)patientInfo.Birthday).ToString("yyyy-MM-dd") });
  1145. }
  1146. if (!string.IsNullOrWhiteSpace(patientInfo.Age))
  1147. {
  1148. remoteDiagnosisInfo.PatientInfo.Add(new DataItemDTO { Key = "AgeUnits", Value = "Year" });
  1149. remoteDiagnosisInfo.PatientInfo.Add(new DataItemDTO { Key = "AgeYear", Value = patientInfo.Age });
  1150. }
  1151. if (terminal != null && terminal.IsAIDiagnosis)
  1152. {
  1153. remoteDiagnosisInfo.DiagnosisStatus = DiagnosisStatusEnum.Under;
  1154. }
  1155. if (terminalRecord.AIDiagnosisInfos != null && terminalRecord.AIDiagnosisInfos.Any())
  1156. {
  1157. remoteDiagnosisInfo.AIDiagnosisInfos = terminalRecord.AIDiagnosisInfos.Select(x =>
  1158. {
  1159. var status = DiagnosisConclusionEnum.InProcess;
  1160. switch (x.Status)
  1161. {
  1162. case EnumAiDiagnosisStatus.NoObviousLesion:
  1163. status = DiagnosisConclusionEnum.NoObviousLesion;
  1164. break;
  1165. case EnumAiDiagnosisStatus.Benign:
  1166. status = DiagnosisConclusionEnum.Benign;
  1167. break;
  1168. case EnumAiDiagnosisStatus.Malignant:
  1169. status = DiagnosisConclusionEnum.Malignant;
  1170. break;
  1171. case EnumAiDiagnosisStatus.BenignAndMalignant:
  1172. status = DiagnosisConclusionEnum.BenignAndMalignant;
  1173. break;
  1174. }
  1175. return new DiagnosisInfoDTO
  1176. {
  1177. DiagnosisOrgan = (DiagnosisOrganEnum)x.Organ,
  1178. Conclusion = status,
  1179. };
  1180. }).ToList();
  1181. remoteDiagnosisInfo.DiagnosisStatus = DiagnosisStatusEnum.Completed;
  1182. }
  1183. syncBatchRemedicalRecordRequest.RemedicalRecordList.Add(remoteDiagnosisInfo);
  1184. }
  1185. catch (Exception ex)
  1186. {
  1187. Logger.WriteLineWarn($"SendRemedicalRecordInfos err, ex:{ex}");
  1188. }
  1189. }
  1190. var result = _jsonRpcProxy.RemedicalService.SyncBatchRemedicalRecordsAsync(syncBatchRemedicalRecordRequest).Result;
  1191. }
  1192. catch (Exception ex)
  1193. {
  1194. Logger.WriteLineWarn($"SendRemedicalRecordInfos err, ex:{ex}");
  1195. }
  1196. }
  1197. public async Task MigrateRemedicalDatas(SyncDBEnum syncType, int batchExcuteRemedicalDataCount)
  1198. {
  1199. Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer starting");
  1200. //获取上次同步到的时间
  1201. var builder = Builders<TerminalDatas>.Filter;
  1202. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1203. //startTime = Convert.ToDateTime("2023-06-26");
  1204. //_migrateRecord.EndTime = DateTime.Now;
  1205. var terminalDatas = new List<TerminalDatas>();
  1206. try
  1207. {
  1208. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1209. var tempTerminalDatas = _terminalDatasDBRepository.GetTerminalDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
  1210. terminalDatas = await FilterData<TerminalDatas>(tempTerminalDatas, "TerminalDatasData");
  1211. //只保留有预览图的数据,如果生成中会在生成后修改update时间,会再次同步
  1212. //terminalDatas = terminalDatas.Where(x => !string.IsNullOrWhiteSpace(x.PreviewImageFileToken)).ToList();
  1213. OnMigrate("Remote diagnosis datas", terminalDatas, SendRemedicalDatas, syncType, batchExcuteRemedicalDataCount);
  1214. terminalDatas.Clear();
  1215. Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer successfully");
  1216. }
  1217. catch (Exception ex)
  1218. {
  1219. Logger.WriteLineInfo($"Remote diagnosis datas migrate migrate to wingServer Error: {ex}");
  1220. }
  1221. finally
  1222. {
  1223. Logger.WriteLineInfo($"Remote diagnosis datas migrate migrate to wingServer successfully, result:{terminalDatas?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1224. if (terminalDatas != null)
  1225. {
  1226. terminalDatas.Clear();
  1227. }
  1228. }
  1229. }
  1230. private void SendRemedicalDatas(IList<TerminalDatas> terminalDatas, SyncDBEnum syncType)
  1231. {
  1232. try
  1233. {
  1234. var builder = Builders<TerminalRecords>.Filter;
  1235. var recordCodes = terminalDatas.Select(x => x.TerminalRecordId);
  1236. var filter = builder.Where(x => x.IsDelete == false && recordCodes.Contains(x.Id));
  1237. var records = _terminalRecordDBRepository.GetTerminalRecords(filter);
  1238. var syncBatchRemedicalRecordRequest = new SyncBatchUploadRemedicalDatasRequest();
  1239. syncBatchRemedicalRecordRequest.SyncType = syncType;
  1240. syncBatchRemedicalRecordRequest.SyncUploadRemedicalDataList = new List<SyncUploadRemedicalDataRequest>();
  1241. //根据结果查询recordId和对应检查所属超声机的短码code
  1242. Dictionary<string, string> dic = new Dictionary<string, string>();
  1243. if (terminalDatas?.Count > 0)
  1244. {
  1245. var recordIds = terminalDatas.Select(c => c.TerminalRecordId).Distinct().ToList();
  1246. var terRecords = _terminalRecordDBRepository.GetTerminalRecordByCodes(recordIds);
  1247. if (terRecords?.Count > 0)
  1248. {
  1249. foreach (var item in terRecords)
  1250. {
  1251. if (!string.IsNullOrEmpty(item?.Terminal?.Id))
  1252. {
  1253. var deviceInfo = _terminalsDBRepository.GetTerminalByCode(item.Terminal.Id);
  1254. if (!string.IsNullOrEmpty(deviceInfo.UniquedId))
  1255. {
  1256. dic.Add(item.Id, deviceInfo.UniquedId);
  1257. }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. foreach (var terminalData in terminalDatas)
  1263. {
  1264. try
  1265. {
  1266. var record = records.FirstOrDefault(x => x.Id == terminalData.TerminalRecordId);
  1267. var fileInfo = terminalData.Files.FirstOrDefault(f => f.ImageQuality == ImageQuality.High);
  1268. var fileUrl = GetFileUrl(fileInfo?.FileName);
  1269. var imageLocation = new ImageLocationDTO();
  1270. if (terminalData.ImageLocation != null)
  1271. {
  1272. if (terminalData.ImageLocation is BreastImageLocation bi)
  1273. {
  1274. imageLocation = new ImageLocationDTO
  1275. {
  1276. Group = "BreastImageLocation",
  1277. Position = bi.Position.ToString(),
  1278. Quadrant = bi.Quadrant.ToString(),
  1279. };
  1280. }
  1281. if (terminalData.ImageLocation is LiverImageLocation li)
  1282. {
  1283. imageLocation = new ImageLocationDTO
  1284. {
  1285. Group = "LiverImageLocation",
  1286. Position = li.Position.ToString(),
  1287. };
  1288. }
  1289. if (terminalData.ImageLocation is PositionImageLocation pi)
  1290. {
  1291. imageLocation = new ImageLocationDTO
  1292. {
  1293. Group = pi.Position,
  1294. Position = pi.Position.ToString(),
  1295. };
  1296. }
  1297. }
  1298. //验证超声机code是否在配置中,如果在,则需要优先处理
  1299. bool oldPlatformNeedAI = false;
  1300. if (dic?.Count > 0)
  1301. {
  1302. if (dic.Keys.Contains(terminalData.TerminalRecordId))
  1303. {
  1304. var shortCode = dic[terminalData.TerminalRecordId];
  1305. if (CommonConfigManager.DeviceShortCodes.Contains(shortCode))
  1306. {
  1307. oldPlatformNeedAI = true;
  1308. }
  1309. }
  1310. }
  1311. var applicationValue = _probeAppHepler.GetApplication(terminalData.Application, terminalData.Id);
  1312. var organDiagnosisResult = terminalData.OrganDiagnosisResult?.ToList() ?? new List<EnumOrgans>();
  1313. var syncUploadRemedicalDataRequest = new SyncUploadRemedicalDataRequest
  1314. {
  1315. Code = terminalData.Id,
  1316. CreateTime = terminalData.CreateTime,
  1317. UpdateTime = terminalData.UpdateTime < new DateTime(2000, 1, 1) ? terminalData.CreateTime : terminalData.UpdateTime,
  1318. ExamCode = terminalData.TerminalRecordId,
  1319. FileDataType = (WingInterfaceLibrary.Enum.RemedicalFileDataTypeEnum)terminalData.DataType,
  1320. ImageUrl = GetCDNUrl(fileUrl),
  1321. FileToken = GetSourceUrl(fileUrl),
  1322. PreviewFileToken = GetFileUrl(terminalData.PreviewImageFileToken),
  1323. ApplicationCategory = applicationValue.Item1,
  1324. Application = applicationValue.Item2,
  1325. ImageLocation = imageLocation,
  1326. DeviceCode = record?.Terminal?.Id,
  1327. OrganDiagnosisInfos = organDiagnosisResult.Select(x => x.ToString()).ToList(),
  1328. OldPlatformNeedAI = oldPlatformNeedAI
  1329. };
  1330. syncBatchRemedicalRecordRequest.SyncUploadRemedicalDataList.Add(syncUploadRemedicalDataRequest);
  1331. }
  1332. catch (Exception ex)
  1333. {
  1334. Logger.WriteLineWarn($"SendRemedicalDatas err, ex:{ex}");
  1335. }
  1336. }
  1337. var result = _jsonRpcProxy.RemedicalService.SyncBatchUploadRemedicalDatasAsync(syncBatchRemedicalRecordRequest).Result;
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. Logger.WriteLineWarn($"SendRemedicalDatas err, ex:{ex}");
  1342. }
  1343. }
  1344. ///// <summary>
  1345. ///// 数据转换
  1346. ///// </summary>
  1347. ///// <typeparam name="T"></typeparam>
  1348. ///// <param name="tempRecords"></param>
  1349. ///// <param name="key"></param>
  1350. ///// <returns></returns>
  1351. //private async Task<List<TerminalAIDatas>> AIFilterData(List<TerminalAIDatas> list)
  1352. //{
  1353. // var records = new List<TerminalAIDatas>();
  1354. // var key = "TerminalAIDatasData";
  1355. // if (list?.Count() > 0)
  1356. // {
  1357. // var tempReportTemplateData = new List<CacheBasicInfo>();
  1358. // foreach (var t in list)
  1359. // {
  1360. // if (t != null)
  1361. // {
  1362. // var createTime = t.CreateTime;
  1363. // var updateTime = t.UpdateTime;
  1364. // var item = new CacheBasicInfo()
  1365. // {
  1366. // Id = t.Id,
  1367. // CacheTime = createTime > updateTime ? createTime : updateTime,
  1368. // };
  1369. // tempReportTemplateData.Add(item);
  1370. // }
  1371. // }
  1372. // if (CommonConfigManager.CacheSynDataInfo.CacheDic.Keys.Contains(key) && CommonConfigManager.CacheSynDataInfo.CacheDic[key]?.Count > 0)
  1373. // {
  1374. // foreach (var templateInfo in tempReportTemplateData)
  1375. // {
  1376. // if (CommonConfigManager.CacheSynDataInfo.CacheDic[key].Exists(c => c.Id == templateInfo.Id && c.CacheTime == templateInfo.CacheTime))
  1377. // {
  1378. // //存在,表示已经处理过
  1379. // }
  1380. // else
  1381. // {
  1382. // //不存在,表示没处理过
  1383. // CommonConfigManager.CacheSynDataInfo.CacheDic[key].Add(templateInfo);
  1384. // var findEntity = list.FirstOrDefault(c => c.Id.ToString() == templateInfo.Id);
  1385. // if (!string.IsNullOrEmpty(findEntity?.Id))
  1386. // {
  1387. // records.Add(findEntity);
  1388. // }
  1389. // }
  1390. // }
  1391. // }
  1392. // else
  1393. // {
  1394. // CommonConfigManager.CacheSynDataInfo.CacheDic.Add(key, tempReportTemplateData);
  1395. // records = list;
  1396. // }
  1397. // }
  1398. // return records;
  1399. //}
  1400. public async Task MigrateRemedicalAIDatas(SyncDBEnum syncType)
  1401. {
  1402. Logger.WriteLineInfo($"Remote diagnosis ai datas migrate to wingServer starting");
  1403. //获取上次同步到的时间
  1404. //判断热数据
  1405. var builder = Builders<TerminalAIDatas>.Filter;
  1406. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1407. var terminalDatas = new List<TerminalAIDatas>();
  1408. try
  1409. {
  1410. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1411. var tempTerminalDatas = _terminalAIDatasDBRepository.GetTerminalAIDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
  1412. terminalDatas = await FilterData<TerminalAIDatas>(tempTerminalDatas, "TerminalAIDatasData");
  1413. OnMigrate("Remote diagnosis ai datas", terminalDatas, SendRemedicalAIDatas, syncType, 1);
  1414. terminalDatas.Clear();
  1415. Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer successfully");
  1416. }
  1417. catch (Exception ex)
  1418. {
  1419. Logger.WriteLineInfo($"Remote diagnosis datas migrate migrate to wingServer Error: {ex}");
  1420. }
  1421. finally
  1422. {
  1423. Logger.WriteLineInfo($"Remote diagnosis datas migrate migrate to wingServer successfully, result:{terminalDatas?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1424. if (terminalDatas != null)
  1425. {
  1426. terminalDatas.Clear();
  1427. }
  1428. }
  1429. }
  1430. private void SendRemedicalAIDatas(IList<TerminalAIDatas> terminalAIDatas, SyncDBEnum syncType)
  1431. {
  1432. try
  1433. {
  1434. var syncBatchAIResultRequest = new SyncBatchAIResultRequest();
  1435. syncBatchAIResultRequest.SyncType = syncType;
  1436. syncBatchAIResultRequest.SyncAIResultList = new List<SyncAIResultRequest>();
  1437. foreach (var terminalAIData in terminalAIDatas)
  1438. {
  1439. try
  1440. {
  1441. var syncAIResultRequest = new SyncAIResultRequest
  1442. {
  1443. RemedicalCode = terminalAIData.TerminalDataId,
  1444. CreateTime = terminalAIData.CreateTime,
  1445. UpdateTime = terminalAIData.UpdateTime < new DateTime(2000, 1, 1) ? terminalAIData.CreateTime : terminalAIData.UpdateTime,
  1446. DiagnosisResult = JsonConvert.SerializeObject(terminalAIData.DiagResults),
  1447. };
  1448. syncBatchAIResultRequest.SyncAIResultList.Add(syncAIResultRequest);
  1449. }
  1450. catch (Exception ex)
  1451. {
  1452. Logger.WriteLineWarn($"SendRemedicalAIDatas err, ex:{ex}");
  1453. }
  1454. }
  1455. var result = _jsonRpcProxy.RemedicalService.SyncBatchAIResultAsync(syncBatchAIResultRequest).Result;
  1456. }
  1457. catch (Exception ex)
  1458. {
  1459. Logger.WriteLineWarn($"SendRemedicalAIDatas err, ex:{ex}");
  1460. }
  1461. }
  1462. public async Task MigrateRemedicalCarotidDatas(SyncDBEnum syncType)
  1463. {
  1464. Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate to wingServer starting");
  1465. //获取上次同步到的时间
  1466. //判断热数据
  1467. var builder = Builders<Carotid3dModelData>.Filter;
  1468. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1469. var carotid3dModelDatas = new List<Carotid3dModelData>();
  1470. try
  1471. {
  1472. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1473. var tempCarotid3dModelDatas = _carotid3dModelDatasDBRepository.GetCarotid3dModelDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
  1474. carotid3dModelDatas = await FilterData<Carotid3dModelData>(tempCarotid3dModelDatas, "Carotid3dModelDataData");
  1475. OnMigrate("Remote diagnosis carotid datas", carotid3dModelDatas, SendRemedicalCarotidDatas, syncType, 1);
  1476. carotid3dModelDatas.Clear();
  1477. Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate to wingServer successfully");
  1478. }
  1479. catch (Exception ex)
  1480. {
  1481. Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate migrate to wingServer Error: {ex}");
  1482. }
  1483. finally
  1484. {
  1485. Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate migrate to wingServer successfully, result:{carotid3dModelDatas?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1486. if (carotid3dModelDatas != null)
  1487. {
  1488. carotid3dModelDatas.Clear();
  1489. }
  1490. }
  1491. }
  1492. private void SendRemedicalCarotidDatas(IList<Carotid3dModelData> carotid3dModelDatas, SyncDBEnum syncType)
  1493. {
  1494. try
  1495. {
  1496. var syncBatchCarotidResultRequest = new SyncBatchCarotidResultRequest();
  1497. syncBatchCarotidResultRequest.SyncType = syncType;
  1498. syncBatchCarotidResultRequest.SyncCarotidResultRequest = new List<GetCarotidResultRequest>();
  1499. foreach (var carotid3dModelData in carotid3dModelDatas)
  1500. {
  1501. try
  1502. {
  1503. var getCarotidResultRequest = new GetCarotidResultRequest
  1504. {
  1505. RemedicalCode = carotid3dModelData.ExamDataId,
  1506. SurfaceToken = GetFileUrl(carotid3dModelData.SurfaceToken),
  1507. MdlToken = GetFileUrl(carotid3dModelData.MdlToken),
  1508. CarotidScanDirection = (CarotidScanDirectionEnum)carotid3dModelData.CarotidScanDirection,
  1509. CarotidScanType = (CarotidScanTypeEnum)carotid3dModelData.CarotidScanType,
  1510. MeasureImageFiles = new List<MeasureImageFileDTO>()
  1511. };
  1512. if (!string.IsNullOrWhiteSpace(carotid3dModelData.CarotidAIMeasureImageToken))
  1513. {
  1514. string[] keyValuePairs = carotid3dModelData.CarotidAIMeasureImageToken.Split(';');
  1515. foreach (string keyValuePair in keyValuePairs)
  1516. {
  1517. string[] parts = keyValuePair.Split('=');
  1518. if (parts.Length != 2) continue;
  1519. if (Enum.TryParse(parts[0], out CarotidAIImageTypeEnum imageType))
  1520. {
  1521. string url = GetFileUrl(parts[1]);
  1522. getCarotidResultRequest.MeasureImageFiles.Add(new MeasureImageFileDTO { ImageType = imageType, ImageFile = url });
  1523. }
  1524. }
  1525. }
  1526. getCarotidResultRequest.MeasureResult = carotid3dModelData.CarotidAIMeasureResult;
  1527. syncBatchCarotidResultRequest.SyncCarotidResultRequest.Add(getCarotidResultRequest);
  1528. }
  1529. catch (Exception ex)
  1530. {
  1531. Logger.WriteLineWarn($"SendRemedicalCarotidDatas err, ex:{ex}");
  1532. }
  1533. }
  1534. var result = _jsonRpcProxy.RemedicalService.SyncBatchCarotidResultAsync(syncBatchCarotidResultRequest).Result;
  1535. }
  1536. catch (Exception ex)
  1537. {
  1538. Logger.WriteLineWarn($"SendRemedicalCarotidDatas err, ex:{ex}");
  1539. }
  1540. }
  1541. public async Task MigrateConsultationResults(SyncDBEnum syncType)
  1542. {
  1543. Logger.WriteLineInfo($"consultations migrate to wingServer starting");
  1544. //获取上次同步到的时间
  1545. var builder = Builders<ConsultationRecords>.Filter;
  1546. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1547. var consultations = new List<ConsultationRecords>();
  1548. try
  1549. {
  1550. var filter = builder.Where(x => x.IsDeleted == false && ((x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime)));
  1551. var tempConsultations = _consultationRecordDBRepository.GetTerminalRecords(filter).OrderByDescending(x => x.CreateTime).ToList();
  1552. consultations = await FilterData<ConsultationRecords>(tempConsultations, "ConsultationRecordsData");
  1553. OnMigrate("consultations", consultations, SendConsultations, syncType, 10);
  1554. consultations.Clear();
  1555. Logger.WriteLineInfo($"consultations migrate to wingServer successfully");
  1556. }
  1557. catch (Exception ex)
  1558. {
  1559. Logger.WriteLineInfo($"consultations migrate migrate to wingServer Error: {ex}");
  1560. }
  1561. finally
  1562. {
  1563. Logger.WriteLineInfo($"consultations migrate to wingServer successfully, result:{consultations?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1564. if (consultations != null)
  1565. {
  1566. consultations.Clear();
  1567. }
  1568. }
  1569. }
  1570. private void SendConsultations(IList<ConsultationRecords> consultations, SyncDBEnum syncType)
  1571. {
  1572. try
  1573. {
  1574. var builder = Builders<FollowUpVisitInfos>.Filter;
  1575. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1576. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1577. var followVistorList = _consultationRecordDBRepository.GetAllFollowUpVisitInfosRecords(filter).OrderByDescending(x => x.CreateTime).ToList();
  1578. var evaluatesBuilder = Builders<ConsultationEvaluates>.Filter;
  1579. var evaluatesFilter = evaluatesBuilder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1580. var valuatesList = _consultationRecordDBRepository.GetAllConsultationEvaluatesRecords(evaluatesFilter).OrderByDescending(x => x.CreateTime).ToList();
  1581. var syncBatchConsultationRequest = new SyncBatchConsultationRequest();
  1582. syncBatchConsultationRequest.SyncType = syncType;
  1583. syncBatchConsultationRequest.SyncConsultations = new List<SyncConsultationRequest>();
  1584. foreach (var consultation in consultations)
  1585. {
  1586. try
  1587. {
  1588. if (consultation.TerminalInfo == null)
  1589. {
  1590. continue;
  1591. }
  1592. var patientInfo = consultation.PatientInfo;
  1593. var syncReportInfoRequest = new SyncConsultationRequest
  1594. {
  1595. ConsultationCode = consultation.Id,
  1596. CreateTime = consultation.CreateTime,
  1597. UpdateTime = consultation.UpdateTime,
  1598. ApplyOrganizationCode = consultation.PrimaryHosptial.Id,
  1599. ApplyUserCode = consultation.DoctorInfo.ID,
  1600. ExpertOrganizationCode = consultation.CentralHospital.Id,
  1601. ExpertUserCode = consultation.ExpertInfo.ID,
  1602. DeviceCode = consultation.TerminalInfo.Id,
  1603. ScanUser = consultation.ScanDoctor,
  1604. PatientInfo = new List<DataItemDTO>
  1605. {
  1606. new DataItemDTO { Key = "Name", Value = patientInfo.Name },
  1607. new DataItemDTO { Key = "Phone", Value = patientInfo.ContactInfo },
  1608. new DataItemDTO { Key = "ID", Value = patientInfo.ID },//设备病人ID
  1609. new DataItemDTO { Key = "Sex", Value = patientInfo.GenderType.ToString() == "Unassigned" ? "NotFilled" : patientInfo.GenderType.ToString() },
  1610. new DataItemDTO { Key = "Anamnesis", Value = patientInfo.PastHistory },
  1611. new DataItemDTO { Key = "Anamnesis", Value = patientInfo.PastHistory },
  1612. new DataItemDTO { Key = "AgeUnits", Value = "Year" },
  1613. new DataItemDTO { Key = "AgeYear", Value = patientInfo.Age },
  1614. },
  1615. ScanPositions = new List<string>(),
  1616. ConsultationTime = consultation.AppointmentTime,
  1617. ConsultationTimeEnd = consultation.AppointmentTime.AddHours(2),
  1618. PrimaryDiagnosis = consultation.PatientInfo.Diagnosis,
  1619. ConsultationStatus = GetStatusEnum(consultation.State),
  1620. FollowUpVisitStatus = (FollowUpVisitStatusEnum)consultation.FollowUpVisitStatus,
  1621. //EvaluateGradeEnum = (EvaluateGradeEnum)consultation.EvaluateGrade,
  1622. Evaluates = null,
  1623. ConsultationFileList = new List<ConsultationFileDTO>()
  1624. };
  1625. if (CommonConfigManager.SpecialOrgCodes.Contains(syncReportInfoRequest.ApplyOrganizationCode))
  1626. {
  1627. syncReportInfoRequest.ApplyOrganizationCode = "VINNO_FIS";
  1628. }
  1629. if (CommonConfigManager.SpecialOrgCodes.Contains(syncReportInfoRequest.ExpertOrganizationCode))
  1630. {
  1631. syncReportInfoRequest.ExpertOrganizationCode = "VINNO_FIS";
  1632. }
  1633. syncReportInfoRequest.ScanPositions.Add(GetScanPosition(consultation.CheckPoint));
  1634. if (valuatesList?.Count > 0)
  1635. {
  1636. var findEntity = valuatesList.OrderByDescending(c => c.CreateTime).FirstOrDefault(c => c.ConsultationRecordId == consultation.Id) ?? new ConsultationEvaluates();
  1637. if (!string.IsNullOrEmpty(findEntity.Id))
  1638. {
  1639. syncReportInfoRequest.Evaluates = new SyncEvaluatesRequest()
  1640. {
  1641. ConsultationRecordCode = findEntity.ConsultationRecordId,
  1642. EvaluateGrade = (EvaluateGradeEnum)findEntity.EvaluateGrade,
  1643. Feedback = findEntity.Feedback,
  1644. IsDelete = findEntity.IsDeleted,
  1645. CreateTime = findEntity.CreateTime,
  1646. UpdateTime = findEntity.UpdateTime,
  1647. Code = findEntity.Id
  1648. };
  1649. if (findEntity.EvaluateGrade == EvaluateGrade.Satisfaction)
  1650. {
  1651. syncReportInfoRequest.Evaluates.EvaluateScore = 5;
  1652. }
  1653. else if (findEntity.EvaluateGrade == EvaluateGrade.General)
  1654. {
  1655. syncReportInfoRequest.Evaluates.EvaluateScore = 3;
  1656. }
  1657. else if (findEntity.EvaluateGrade == EvaluateGrade.Dissatisfaction)
  1658. {
  1659. syncReportInfoRequest.Evaluates.EvaluateScore = 1;
  1660. }
  1661. else
  1662. {
  1663. syncReportInfoRequest.Evaluates.EvaluateScore = 0;
  1664. }
  1665. }
  1666. }
  1667. //查询随访记录
  1668. if (followVistorList?.Count > 0)
  1669. {
  1670. var findList = followVistorList.Where(c => c.ConsultationRecordId == consultation.Id)?.ToList();
  1671. if (findList?.Count > 0)
  1672. {
  1673. var followUpVistorList = findList.Select(c => new SyncFollowUpVisitRequest()
  1674. {
  1675. IsDelete = c.IsDeleted,
  1676. CreateTime = c.CreateTime,
  1677. UpdateTime = c.UpdateTime,
  1678. FollowUpVisitCode = c.Id,
  1679. ConsultationRecordCode = c.ConsultationRecordId,
  1680. PatientName = c.PatientName,
  1681. PatientPhone = c.PatientPhone,
  1682. GeneralCase = c.GeneralCase,
  1683. ClinicalSituation = c.ClinicalSituation,
  1684. DoctorCode = c.Doctor,
  1685. OccurredTime = c.OccurredTime
  1686. }).ToList();
  1687. syncReportInfoRequest.SyncFollowUpVisitList = followUpVistorList;
  1688. }
  1689. }
  1690. if (consultation.ImageTokens != null && consultation.ImageTokens.Any())
  1691. {
  1692. foreach (var item in consultation.ImageTokens)
  1693. {
  1694. var consultationFileDTO = new ConsultationFileDTO();
  1695. consultationFileDTO.FileDataType = RemedicalFileDataTypeEnum.VinnoVidSingle;
  1696. consultationFileDTO.SourceUrl = ConvertToJpg(item);
  1697. consultationFileDTO.PreviewImageUrl = ConvertToJpg(item);
  1698. consultationFileDTO.CreatorCode = syncReportInfoRequest.ApplyUserCode;
  1699. syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
  1700. }
  1701. }
  1702. if (consultation.VideoTokens != null && consultation.VideoTokens.Any())
  1703. {
  1704. foreach (var item in consultation.VideoTokens)
  1705. {
  1706. var consultationFileDTO = new ConsultationFileDTO();
  1707. consultationFileDTO.FileDataType = RemedicalFileDataTypeEnum.VinnoVidMovie;
  1708. string previewImg = "";
  1709. string file = "";
  1710. var tuple = ConvertToVid(item.VideoToken, UploadFileTypeEnum.FVID);
  1711. if (tuple != null)
  1712. {
  1713. file = tuple.Item1;
  1714. if (string.IsNullOrEmpty(previewImg))
  1715. {
  1716. previewImg = tuple.Item2;
  1717. }
  1718. }
  1719. consultationFileDTO.SourceUrl = file;
  1720. consultationFileDTO.PreviewImageUrl = previewImg;
  1721. consultationFileDTO.CreatorCode = syncReportInfoRequest.ApplyUserCode;
  1722. syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
  1723. }
  1724. }
  1725. if (consultation.GraphicData != null && consultation.GraphicData.Any())
  1726. {
  1727. foreach (var item in consultation.GraphicData)
  1728. {
  1729. var consultationFileDTO = new ConsultationFileDTO();
  1730. string previewImg = "";
  1731. string file = "";
  1732. if (item.GraphicType == 0)
  1733. {
  1734. if (!string.IsNullOrEmpty(item.PreviewGraphicToken))
  1735. {
  1736. previewImg = ConvertToJpg(item.PreviewGraphicToken);
  1737. }
  1738. if (!string.IsNullOrEmpty(item.GraphicToken))
  1739. {
  1740. var tuple = ConvertToVid(item.GraphicToken, UploadFileTypeEnum.IMG);
  1741. if (tuple != null)
  1742. {
  1743. file = tuple.Item1;
  1744. }
  1745. }
  1746. }
  1747. else
  1748. {
  1749. if (!string.IsNullOrEmpty(item.PreviewGraphicToken))
  1750. {
  1751. previewImg = ConvertToJpg(item.PreviewGraphicToken);
  1752. }
  1753. if (!string.IsNullOrEmpty(item.GraphicToken))
  1754. {
  1755. var tuple = ConvertToVid(item.GraphicToken, UploadFileTypeEnum.FVID);
  1756. if (tuple != null)
  1757. {
  1758. file = tuple.Item1;
  1759. if (string.IsNullOrEmpty(previewImg))
  1760. {
  1761. previewImg = tuple.Item2;
  1762. }
  1763. }
  1764. }
  1765. }
  1766. consultationFileDTO.CoverImageUrl = previewImg;
  1767. consultationFileDTO.FileDataType = item.GraphicType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie;
  1768. consultationFileDTO.SourceUrl = file;
  1769. consultationFileDTO.PreviewImageUrl = previewImg;
  1770. consultationFileDTO.CreatorCode = item.UserId;
  1771. consultationFileDTO.CreateTime = (consultation.UpdateTime <= DateTime.MinValue ? consultation.CreateTime : consultation.UpdateTime);
  1772. syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
  1773. }
  1774. }
  1775. if (consultation.PreFileItems != null && consultation.PreFileItems.Any())
  1776. {
  1777. foreach (var item in consultation.PreFileItems)
  1778. {
  1779. string previewImg = "";
  1780. string file = "";
  1781. if (item.FileType == 0)
  1782. {
  1783. if (!string.IsNullOrEmpty(item.ThumbnailUrl))
  1784. {
  1785. previewImg = ConvertToJpg(item.ThumbnailUrl);
  1786. }
  1787. if (!string.IsNullOrEmpty(item.OriginalFileUrl))
  1788. {
  1789. var tuple = ConvertToVid(item.OriginalFileUrl, UploadFileTypeEnum.IMG);
  1790. if (tuple != null)
  1791. {
  1792. file = tuple.Item1;
  1793. }
  1794. }
  1795. }
  1796. else
  1797. {
  1798. if (!string.IsNullOrEmpty(item.ThumbnailUrl))
  1799. {
  1800. previewImg = ConvertToJpg(item.ThumbnailUrl);
  1801. }
  1802. if (!string.IsNullOrEmpty(item.OriginalFileUrl))
  1803. {
  1804. //file = ConvertToVid(item.GraphicToken, UploadFileTypeEnum.FVID);
  1805. //pdf文件
  1806. }
  1807. }
  1808. var consultationFileDTO = new ConsultationFileDTO();
  1809. consultationFileDTO.FileDataType = item.FileType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie;
  1810. consultationFileDTO.SourceUrl = file;
  1811. consultationFileDTO.PreviewImageUrl = previewImg;
  1812. consultationFileDTO.CreatorCode = item.Uploader;
  1813. syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
  1814. }
  1815. }
  1816. syncBatchConsultationRequest.SyncConsultations.Add(syncReportInfoRequest);
  1817. }
  1818. catch (Exception ex)
  1819. {
  1820. Logger.WriteLineWarn($"SendConsultations err, ex:{ex}");
  1821. }
  1822. }
  1823. var result = _jsonRpcProxy.LiveConsultationService.SyncBatchConsultationAsync(syncBatchConsultationRequest).Result;
  1824. }
  1825. catch (Exception ex)
  1826. {
  1827. Logger.WriteLineWarn($"SendConsultations err, ex:{ex}");
  1828. }
  1829. }
  1830. private string GetScanPosition(string checkPoint)
  1831. {
  1832. if (checkPoint == "Fetu")
  1833. {
  1834. return "Fetus";
  1835. }
  1836. else if (checkPoint == "Appendages")
  1837. {
  1838. return "Adnexa";
  1839. }
  1840. else if (checkPoint == "PelvicCavity")
  1841. {
  1842. return "Pelvic";
  1843. }
  1844. else if (checkPoint == "GB")
  1845. {
  1846. return "Cholecyst";
  1847. }
  1848. else if (checkPoint == "DoubleKidney")
  1849. {
  1850. return "Kidneys";
  1851. }
  1852. return checkPoint;
  1853. }
  1854. private TransactionStatusEnum GetStatusEnum(Entities.ConsultationState state)
  1855. {
  1856. TransactionStatusEnum transactionStatusEnum = TransactionStatusEnum.Applied;
  1857. switch (state)
  1858. {
  1859. case Entities.ConsultationState.Unhandled:
  1860. transactionStatusEnum = TransactionStatusEnum.Applied;
  1861. break;
  1862. case Entities.ConsultationState.Withdrawn:
  1863. transactionStatusEnum = TransactionStatusEnum.Withdrawn;
  1864. break;
  1865. case Entities.ConsultationState.Handled:
  1866. transactionStatusEnum = TransactionStatusEnum.ToStart;
  1867. break;
  1868. case Entities.ConsultationState.Started:
  1869. transactionStatusEnum = TransactionStatusEnum.InProgress;
  1870. break;
  1871. case Entities.ConsultationState.WaitForReportUpload:
  1872. transactionStatusEnum = TransactionStatusEnum.PendingReport;
  1873. break;
  1874. case Entities.ConsultationState.ReportUploading:
  1875. transactionStatusEnum = TransactionStatusEnum.PendingReport;
  1876. break;
  1877. case Entities.ConsultationState.ReportUploaded:
  1878. transactionStatusEnum = TransactionStatusEnum.End;
  1879. break;
  1880. case Entities.ConsultationState.ReportUploadFailed:
  1881. transactionStatusEnum = TransactionStatusEnum.PendingReport;
  1882. break;
  1883. case Entities.ConsultationState.Expired:
  1884. transactionStatusEnum = TransactionStatusEnum.Expired;
  1885. break;
  1886. case Entities.ConsultationState.Qualified:
  1887. transactionStatusEnum = TransactionStatusEnum.End;
  1888. break;
  1889. case Entities.ConsultationState.UnQualified:
  1890. transactionStatusEnum = TransactionStatusEnum.End;
  1891. break;
  1892. default:
  1893. break;
  1894. }
  1895. return transactionStatusEnum;
  1896. }
  1897. ///// <summary>
  1898. ///// 数据转换
  1899. ///// </summary>
  1900. ///// <typeparam name="T"></typeparam>
  1901. ///// <param name="tempRecords"></param>
  1902. ///// <param name="key"></param>
  1903. ///// <returns></returns>
  1904. //private async Task<List<ReportInfoResults>> ReportInfoFilterData(List<ReportInfoResults> list)
  1905. //{
  1906. // var records = new List<ReportInfoResults>();
  1907. // var key = "ReportInfoResultsData";
  1908. // if (list?.Count() > 0)
  1909. // {
  1910. // var tempReportTemplateData = new List<CacheBasicInfo>();
  1911. // foreach (var t in list)
  1912. // {
  1913. // if (t != null)
  1914. // {
  1915. // var createTime = t.CreateTime;
  1916. // var updateTime = t.UpdateTime;
  1917. // var item = new CacheBasicInfo()
  1918. // {
  1919. // Id = t.Id,
  1920. // CacheTime = createTime > updateTime ? createTime : updateTime,
  1921. // };
  1922. // tempReportTemplateData.Add(item);
  1923. // }
  1924. // }
  1925. // if (CommonConfigManager.CacheSynDataInfo.CacheDic.Keys.Contains(key) && CommonConfigManager.CacheSynDataInfo.CacheDic[key]?.Count > 0)
  1926. // {
  1927. // foreach (var templateInfo in tempReportTemplateData)
  1928. // {
  1929. // if (CommonConfigManager.CacheSynDataInfo.CacheDic[key].Exists(c => c.Id == templateInfo.Id && c.CacheTime == templateInfo.CacheTime))
  1930. // {
  1931. // //存在,表示已经处理过
  1932. // }
  1933. // else
  1934. // {
  1935. // //不存在,表示没处理过
  1936. // CommonConfigManager.CacheSynDataInfo.CacheDic[key].Add(templateInfo);
  1937. // var findEntity = list.FirstOrDefault(c => c.Id.ToString() == templateInfo.Id);
  1938. // if (!string.IsNullOrEmpty(findEntity?.Id))
  1939. // {
  1940. // records.Add(findEntity);
  1941. // }
  1942. // }
  1943. // }
  1944. // }
  1945. // else
  1946. // {
  1947. // CommonConfigManager.CacheSynDataInfo.CacheDic.Add(key, tempReportTemplateData);
  1948. // records = list;
  1949. // }
  1950. // }
  1951. // return records;
  1952. //}
  1953. public async Task MigrateReportInfoResults(SyncDBEnum syncType)
  1954. {
  1955. Logger.WriteLineInfo($"ReportInfoResults migrate to wingServer starting");
  1956. //获取上次同步到的时间
  1957. var builder = Builders<ReportInfoResults>.Filter;
  1958. var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
  1959. var reportInfoResults = new List<ReportInfoResults>();
  1960. try
  1961. {
  1962. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
  1963. //var filter = builder.Where(x => x.Id == "DE2642FAFCA64AEAAB285BD38E6DEEC0");
  1964. var tempReportInfoResults = _reportInfoResultDBRepository.GetReports(filter).OrderByDescending(x => x.CreateTime).ToList();
  1965. reportInfoResults = await FilterData(tempReportInfoResults, "ReportInfoResultsData");
  1966. OnMigrate("reportInfoResults", reportInfoResults, SendRemedicalreportInfoResults, syncType, 1);
  1967. }
  1968. catch (Exception ex)
  1969. {
  1970. Logger.WriteLineInfo($"ReportInfoResults migrate to wingServer Error: {ex}");
  1971. }
  1972. finally
  1973. {
  1974. Logger.WriteLineInfo($"reportInfoResults migrate to wingServer successfully, result:{reportInfoResults?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1975. if (reportInfoResults != null)
  1976. {
  1977. reportInfoResults.Clear();
  1978. }
  1979. }
  1980. }
  1981. public async Task MigrateSpeicalReportInfoResults(DateTime startTime, DateTime endTime)
  1982. {
  1983. Logger.WriteLineInfo($"MigrateSpeicalReportInfoResults migrate to wingServer starting");
  1984. //获取上次同步到的时间
  1985. var builder = Builders<ReportInfoResults>.Filter;
  1986. var reportInfoResults = new List<ReportInfoResults>();
  1987. try
  1988. {
  1989. var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= endTime) || (x.UpdateTime > startTime && x.UpdateTime <= endTime));
  1990. //var filter = builder.Where(x => x.Id == "DE2642FAFCA64AEAAB285BD38E6DEEC0");
  1991. reportInfoResults = _reportInfoResultDBRepository.GetReports(filter).OrderByDescending(x => x.CreateTime).ToList();
  1992. OnMigrate("reportInfoResults", reportInfoResults, SendRemedicalreportInfoResults, SyncDBEnum.Synchronize, 1);
  1993. }
  1994. catch (Exception ex)
  1995. {
  1996. Logger.WriteLineInfo($"MigrateSpeicalReportInfoResults migrate to wingServer Error: {ex}");
  1997. }
  1998. finally
  1999. {
  2000. Logger.WriteLineInfo($"MigrateSpeicalReportInfoResults migrate to wingServer successfully, result:{reportInfoResults?.Count}, startTime: {startTime.ToString("yyyy-MM-dd HH:mm:ss")}--endTime: {_migrateRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2001. if (reportInfoResults != null)
  2002. {
  2003. reportInfoResults.Clear();
  2004. }
  2005. }
  2006. }
  2007. private void SendRemedicalreportInfoResults(IList<ReportInfoResults> reportInfoResults, SyncDBEnum syncType)
  2008. {
  2009. try
  2010. {
  2011. var syncBatchReportInfoRequest = new SyncBatchReportInfoRequest();
  2012. syncBatchReportInfoRequest.SyncType = syncType;
  2013. syncBatchReportInfoRequest.SyncReportInfos = new List<SyncReportInfoRequest>();
  2014. foreach (var reportInfoResult in reportInfoResults)
  2015. {
  2016. try
  2017. {
  2018. var terminalRecord = _terminalRecordDBRepository.GetTerminalRecordByCodes(new List<string> { reportInfoResult.RecordId })?.FirstOrDefault();
  2019. var diagnosisLabels = new List<string>();
  2020. var reportUserCode = "";
  2021. var isAI = false;
  2022. if (reportInfoResult?.User?.Name == "AI")
  2023. {
  2024. diagnosisLabels = new List<string> { "VAid" };
  2025. isAI = true;
  2026. if (terminalRecord != null && terminalRecord.AIDiagnosisInfos != null && terminalRecord.AIDiagnosisInfos.Any())
  2027. {
  2028. foreach (var ai in terminalRecord.AIDiagnosisInfos)
  2029. {
  2030. if (ai.Organ == reportInfoResult.Organ && ai.Status != EnumAiDiagnosisStatus.Null)
  2031. {
  2032. diagnosisLabels.Add(ai.Status.ToString());
  2033. }
  2034. }
  2035. }
  2036. }
  2037. else
  2038. {
  2039. reportUserCode = reportInfoResult.User._id;
  2040. }
  2041. Logger.WriteLineInfo($"reportInfoResults migrate to wingServer successfully, reportInfoResult.Id: {reportInfoResult.Id}");
  2042. var syncReportInfoRequest = new SyncReportInfoRequest
  2043. {
  2044. ReportCode = reportInfoResult.Id,
  2045. CreateTime = reportInfoResult.CreateTime,
  2046. UpdateTime = reportInfoResult.UpdateTime,
  2047. RecordCode = reportInfoResult.RecordId,
  2048. ReportTemplateJson = reportInfoResult.Template,
  2049. ReportDatasJson = ReportElementsSerializer.ConvertReportElementsToJson(isAI, reportInfoResult.Template, reportInfoResult.ElementCollection),
  2050. ReportPreviewList = new List<ReportPreviewDTO>(),
  2051. ReportOrgan = (DiagnosisOrganEnum)reportInfoResult.Organ,
  2052. DiagnosisLabels = diagnosisLabels,
  2053. ReportUserCode = reportUserCode
  2054. };
  2055. if (reportInfoResult.PreviewImages != null && reportInfoResult.PreviewImages.Count > 0)
  2056. {
  2057. foreach (var item in reportInfoResult.PreviewImages)
  2058. {
  2059. var reportPreviewDTO = new ReportPreviewDTO();
  2060. reportPreviewDTO.FileToken = GetFileUrl(item.Name);
  2061. reportPreviewDTO.FileType = UploadFileTypeEnum.JPG;
  2062. syncReportInfoRequest.ReportPreviewList.Add(reportPreviewDTO);
  2063. }
  2064. }
  2065. syncBatchReportInfoRequest.SyncReportInfos.Add(syncReportInfoRequest);
  2066. }
  2067. catch (Exception ex)
  2068. {
  2069. Logger.WriteLineWarn($"SendRemedicalreportInfoResults err, ex:{ex}");
  2070. }
  2071. }
  2072. var result = _jsonRpcProxy.ReportService.SyncBatchReportInfoAsync(syncBatchReportInfoRequest).Result;
  2073. }
  2074. catch (Exception ex)
  2075. {
  2076. Logger.WriteLineWarn($"SendRemedicalreportInfoResults err, ex:{ex}");
  2077. }
  2078. }
  2079. private string GetFileUrl(string fileUrl)
  2080. {
  2081. var prefix = "1!U$";
  2082. if (!string.IsNullOrWhiteSpace(fileUrl) && fileUrl.StartsWith(prefix))
  2083. {
  2084. return fileUrl.Replace(prefix, "");
  2085. }
  2086. return fileUrl ?? string.Empty;
  2087. }
  2088. internal string GetSourceUrl(string cdnUrl)
  2089. {
  2090. cdnUrl = GetFileUrl(cdnUrl);
  2091. var sourceUrl = cdnUrl.Replace("http://cdn-bj.fis.plus", "https://flyinsono-bj-1300984704.cos.ap-beijing.myqcloud.com")
  2092. .Replace("http://cdn-hk.fis.plus", "https://flyinsono-hk-1300984704.cos.ap-hongkong.myqcloud.com")
  2093. .Replace("http://cdn-fra.fis.plus", "https://flyinsono-fra-1300984704.cos.eu-frankfurt.myqcloud.com")
  2094. .Replace("http://cdn-bom.fis.plus", "https://flyinsono-bom-1300984704.cos.ap-mumbai.myqcloud.com")
  2095. .Replace("http://static.fis.plus", "https://static-1300984704.cos.ap-shanghai.myqcloud.com");
  2096. return sourceUrl;
  2097. }
  2098. internal string GetCDNUrl(string sourceUrl)
  2099. {
  2100. if (sourceUrl.Contains("cdn-"))
  2101. {
  2102. return sourceUrl;
  2103. }
  2104. var cndUrl = sourceUrl.Replace("https://flyinsono-bj-1300984704.cos.ap-beijing.myqcloud.com", "http://cdn-bj.fis.plus")
  2105. .Replace("https://flyinsono-hk-1300984704.cos.ap-hongkong.myqcloud.com", "http://cdn-hk.fis.plus")
  2106. .Replace("https://flyinsono-fra-1300984704.cos.eu-frankfurt.myqcloud.com", "http://cdn-fra.fis.plus")
  2107. .Replace("https://flyinsono-bom-1300984704.cos.ap-mumbai.myqcloud.com", "http://cdn-bom.fis.plus")
  2108. .Replace("https://static-1300984704.cos.ap-shanghai.myqcloud.com", "http://static.fis.plus")
  2109. .Replace("http://flyinsono-bj-1300984704.cos.ap-beijing.myqcloud.com", "http://cdn-bj.fis.plus")
  2110. .Replace("http://flyinsono-hk-1300984704.cos.ap-hongkong.myqcloud.com", "http://cdn-hk.fis.plus")
  2111. .Replace("http://flyinsono-fra-1300984704.cos.eu-frankfurt.myqcloud.com", "http://cdn-fra.fis.plus")
  2112. .Replace("http://flyinsono-bom-1300984704.cos.ap-mumbai.myqcloud.com", "http://cdn-bom.fis.plus")
  2113. .Replace("http://static-1300984704.cos.ap-shanghai.myqcloud.com", "http://static.fis.plus");
  2114. return cndUrl;
  2115. }
  2116. private string ConvertToJpg(string oldFileToken)
  2117. {
  2118. try
  2119. {
  2120. var prefix = "1!U$";
  2121. if (!string.IsNullOrWhiteSpace(oldFileToken) && oldFileToken.StartsWith(prefix))
  2122. {
  2123. var fileUrl = oldFileToken.Replace(prefix, "");
  2124. var fileName = Path.GetFileNameWithoutExtension(fileUrl);
  2125. var jpgFileName = fileName + ".jpg";
  2126. //验证头
  2127. var storageUrl = "";
  2128. var validateResult = ValidateHeadFile(jpgFileName, ref storageUrl);
  2129. if (validateResult)
  2130. {
  2131. return storageUrl;
  2132. }
  2133. var localPath = DownloadAsync(fileUrl, jpgFileName).Result;
  2134. if (!string.IsNullOrWhiteSpace(localPath))
  2135. {
  2136. var newUrl = UploadAsync(localPath).Result;
  2137. if (!string.IsNullOrWhiteSpace(newUrl))
  2138. {
  2139. return newUrl;
  2140. }
  2141. }
  2142. }
  2143. return oldFileToken;
  2144. }
  2145. catch (Exception ex)
  2146. {
  2147. Logger.WriteLineWarn($"ConvertToJpg err, ex:{ex}");
  2148. return oldFileToken;
  2149. }
  2150. }
  2151. private bool ValidateHeadFile(string fileName, ref string storageUrl)
  2152. {
  2153. bool result = true;
  2154. var authorizationResult = _jsonRpcProxy.Storage.GetAuthorizationAsync(new FileServiceRequest
  2155. {
  2156. Token = DefaultToken,
  2157. FileName = fileName,
  2158. IsRechristen = false,
  2159. IsUpgradePackage = false,
  2160. RequestMethod = "head"
  2161. }).Result;
  2162. if (authorizationResult == null)
  2163. {
  2164. Logger.WriteLineInfo("Head Create Signature Fail");
  2165. return false;
  2166. }
  2167. var newRequestHeads = new Dictionary<string, string>();
  2168. newRequestHeads.Add("Authorization", authorizationResult.Authorization);
  2169. storageUrl = authorizationResult.StorageUrl;
  2170. using (var newRequest = new HttpRequestMessage())
  2171. {
  2172. newRequest.RequestUri = new Uri(storageUrl);
  2173. newRequest.Method = HttpMethod.Head;
  2174. foreach (var newHead in newRequestHeads)
  2175. {
  2176. newRequest.Headers.TryAddWithoutValidation(newHead.Key, newHead.Value);
  2177. }
  2178. var newResponse = _httpClient.SendAsync(newRequest).Result;
  2179. if (newResponse != null && newResponse.StatusCode == HttpStatusCode.OK)
  2180. {
  2181. //read response content
  2182. if (storageUrl.Contains("/SystemUpgradePackage/"))//表示vinno
  2183. {
  2184. var resultContent = newResponse.Content.Headers.ContentLength > 0;
  2185. if (resultContent)
  2186. {
  2187. result = result & true;
  2188. }
  2189. else
  2190. {
  2191. result = result & false;
  2192. }
  2193. }
  2194. else
  2195. {
  2196. var newETag = newResponse.Headers?.ETag?.Tag ?? string.Empty;
  2197. if (!string.IsNullOrEmpty(newETag))
  2198. {
  2199. result = result & true;
  2200. }
  2201. else
  2202. {
  2203. result = result & false;
  2204. }
  2205. }
  2206. }
  2207. else
  2208. {
  2209. result = result & false;
  2210. }
  2211. }
  2212. return result;
  2213. }
  2214. private Tuple<string, string> ConvertToVid(string oldFileToken, UploadFileTypeEnum fileType)
  2215. {
  2216. try
  2217. {
  2218. var prefix = "1!U$";
  2219. if (!string.IsNullOrWhiteSpace(oldFileToken) && oldFileToken.StartsWith(prefix))
  2220. {
  2221. var fileUrl = oldFileToken.Replace(prefix, "");
  2222. var fileName = Path.GetFileNameWithoutExtension(fileUrl);
  2223. var vidFileName = fileName + ".vid";
  2224. //验证头
  2225. var storageUrl = "";
  2226. var host = "";
  2227. var validateResult = ValidateHeadFile(vidFileName, ref storageUrl);
  2228. if (validateResult)
  2229. {
  2230. host = storageUrl.Replace(vidFileName, "");
  2231. var previewUrl = host + fileName + ".jpg";
  2232. return Tuple.Create<string, string>(storageUrl, previewUrl);
  2233. }
  2234. var vidResult = _jsonRpcProxy.RemedicalService.DoConvertToVid(new WingInterfaceLibrary.Request.Lab.LabFileInfoRequest
  2235. {
  2236. Token = DefaultToken,
  2237. FileName = fileName,
  2238. FilePath = fileUrl,
  2239. FileType = fileType
  2240. }).Result;
  2241. if (!string.IsNullOrWhiteSpace(vidResult))
  2242. {
  2243. host = vidResult.Replace(vidFileName, "");
  2244. var previewUrl = host + fileName + ".jpg";
  2245. return Tuple.Create<string, string>(vidResult, previewUrl);
  2246. }
  2247. }
  2248. return Tuple.Create<string, string>("", "");
  2249. }
  2250. catch (Exception ex)
  2251. {
  2252. Logger.WriteLineWarn($"ConvertToVid err, ex:{ex}");
  2253. return Tuple.Create<string, string>("", "");
  2254. }
  2255. }
  2256. private OrganizationView MapToOrganizationView(IList<Organizations> organizations, string? hospitalId)
  2257. {
  2258. var hospital = organizations.FirstOrDefault(x => x.Id == hospitalId);
  2259. if (hospital != null)
  2260. {
  2261. return new OrganizationView
  2262. {
  2263. Code = hospital.Id,
  2264. Name = hospital.Name,
  2265. Description = hospital.Description,
  2266. CountryCode = hospital.Country?.Id,
  2267. CountryName = hospital.Country?.Name,
  2268. ProvinceCode = hospital.Province?.Id,
  2269. ProvinceName = hospital.Province?.Name,
  2270. CityCode = hospital.City?.Id,
  2271. CityName = hospital.City?.Name,
  2272. };
  2273. }
  2274. return null;
  2275. }
  2276. private UserView MapToUserView(IList<Organizations> organizations, IList<Users> users, string? userId)
  2277. {
  2278. var user = users.FirstOrDefault(x => x.Id == userId);
  2279. if (user != null)
  2280. {
  2281. var hospital = organizations.FirstOrDefault(x => x.Id == user.HospitalId);
  2282. var name = !string.IsNullOrWhiteSpace(user.FullName) ? user.FullName
  2283. : !string.IsNullOrWhiteSpace(user.LastName) ? user.LastName
  2284. : !string.IsNullOrWhiteSpace(user.FirstName) ? user.FirstName
  2285. : !string.IsNullOrWhiteSpace(user.NickName) ? user.NickName
  2286. : user.Name;
  2287. return new UserView
  2288. {
  2289. Code = user.Id,
  2290. Name = name,
  2291. OrganizationCode = user.HospitalId,
  2292. OrganizationName = hospital?.Name,
  2293. };
  2294. }
  2295. return null;
  2296. }
  2297. private DeviceView MapToDeviceView(IList<Terminals> terminals, string? terminalId)
  2298. {
  2299. var terminal = terminals.FirstOrDefault(x => x.Id == terminalId);
  2300. if (terminal != null)
  2301. {
  2302. return new DeviceView
  2303. {
  2304. Code = terminal.Id,
  2305. Name = terminal.Name,
  2306. Description = terminal.Description,
  2307. UniqueCode = terminal.UniquedId,
  2308. DeviceType = terminal.IsSonopost ? "sonopost" : "US",
  2309. DeviceModel = terminal.Model,
  2310. OrganizationCode = terminal.Organization?.Id,
  2311. OrganizationName = terminal.Organization?.Name,
  2312. };
  2313. }
  2314. return null;
  2315. }
  2316. private GroupView MapToUserGroupView(IList<UserGroup> userGroups, string? userGroupId)
  2317. {
  2318. var userGroup = userGroups.FirstOrDefault(x => x.Id == userGroupId);
  2319. if (userGroup != null)
  2320. {
  2321. return new GroupView
  2322. {
  2323. Code = userGroup.Id,
  2324. Name = userGroup.Name,
  2325. };
  2326. }
  2327. return null;
  2328. }
  2329. private ClassView MapToClassView(IList<UltrasonicClass> classes, string? classId)
  2330. {
  2331. var classInfo = classes.FirstOrDefault(x => x.Id == classId);
  2332. if (classInfo != null)
  2333. {
  2334. return new ClassView
  2335. {
  2336. Code = classInfo.Id,
  2337. Name = classInfo.Name,
  2338. };
  2339. }
  2340. return null;
  2341. }
  2342. private List<DiagnosisOrganEnum> GetDiagnosisOrgans(List<AIDiagnosisPerImg> results)
  2343. {
  2344. var diagnosisOrgans = new List<DiagnosisOrganEnum>();
  2345. foreach (var imageResult in results)
  2346. {
  2347. foreach (var diagnosisResult in imageResult.DiagResultsForEachOrgan)
  2348. {
  2349. var organName = Enum.GetName(typeof(DiagnosisOrganEnum), (int)diagnosisResult.Organ);
  2350. if (!string.IsNullOrWhiteSpace(organName) && diagnosisResult.Organ != EnumOrgans.Null && diagnosisResult.DetectedObjects?.Any() == true)
  2351. {
  2352. diagnosisOrgans.Add((DiagnosisOrganEnum)diagnosisResult.Organ);
  2353. }
  2354. }
  2355. }
  2356. return diagnosisOrgans.Distinct().ToList();
  2357. }
  2358. private DiagnosisConclusionEnum GetDiagnosisConclusion(List<AIDiagnosisPerImg> results)
  2359. {
  2360. var diagnosisConclusions = new List<DiagnosisConclusionEnum>();
  2361. foreach (var imageResult in results)
  2362. {
  2363. foreach (var diagnosisResult in imageResult.DiagResultsForEachOrgan)
  2364. {
  2365. var benignLabels = new List<int>();
  2366. var malignantLabels = new List<int>();
  2367. if (diagnosisResult.Organ == EnumOrgans.Breast)
  2368. {
  2369. benignLabels = new List<int> { 1, 2, 3 };
  2370. malignantLabels = new List<int> { 4, 5, 6, 7 };
  2371. }
  2372. else if (diagnosisResult.Organ == EnumOrgans.Liver)
  2373. {
  2374. benignLabels = new List<int> { 1, 2, 3, 5, 6, 7, 8 };
  2375. malignantLabels = new List<int> { 4 };
  2376. }
  2377. else if (diagnosisResult.Organ == EnumOrgans.Thyroid)
  2378. {
  2379. benignLabels = new List<int> { 1, 2, 7 };
  2380. malignantLabels = new List<int> { 3, 4, 5, 6 };
  2381. }
  2382. var labels = diagnosisResult.DetectedObjects.Select(x => x.Label);
  2383. if (labels.Contains(0))
  2384. {
  2385. diagnosisConclusions.Add(DiagnosisConclusionEnum.NoObviousLesion);
  2386. }
  2387. if (labels.Intersect(benignLabels).Any())
  2388. {
  2389. diagnosisConclusions.Add(DiagnosisConclusionEnum.Benign);
  2390. }
  2391. if (labels.Intersect(malignantLabels).Any())
  2392. {
  2393. diagnosisConclusions.Add(DiagnosisConclusionEnum.Malignant);
  2394. }
  2395. }
  2396. }
  2397. var containsBenign = diagnosisConclusions.Contains(DiagnosisConclusionEnum.Benign);
  2398. var containsMalignant = diagnosisConclusions.Contains(DiagnosisConclusionEnum.Malignant);
  2399. var containsNoObviousLesion = diagnosisConclusions.Contains(DiagnosisConclusionEnum.NoObviousLesion);
  2400. if (containsBenign && containsMalignant)
  2401. {
  2402. return DiagnosisConclusionEnum.BenignAndMalignant;
  2403. }
  2404. else if (containsBenign)
  2405. {
  2406. return DiagnosisConclusionEnum.Benign;
  2407. }
  2408. else if (containsMalignant)
  2409. {
  2410. return DiagnosisConclusionEnum.Malignant;
  2411. }
  2412. else if (containsNoObviousLesion)
  2413. {
  2414. return DiagnosisConclusionEnum.NoObviousLesion;
  2415. }
  2416. else
  2417. {
  2418. return DiagnosisConclusionEnum.Unrecognized;
  2419. }
  2420. }
  2421. /// <summary>下载文件</summary>
  2422. /// <param name="fileUrl"></param>
  2423. /// <returns></returns>
  2424. private async Task<string> DownloadAsync(string fileUrl, string fileNameAndExtension = "")
  2425. {
  2426. try
  2427. {
  2428. if (string.IsNullOrEmpty(fileUrl))
  2429. {
  2430. return string.Empty;
  2431. }
  2432. if (!Directory.Exists(_tempFolder))
  2433. {
  2434. Directory.CreateDirectory(_tempFolder);
  2435. }
  2436. var fileName = Path.GetFileName(fileUrl);
  2437. if (!string.IsNullOrWhiteSpace(fileNameAndExtension))
  2438. {
  2439. fileName = fileNameAndExtension;
  2440. }
  2441. var tempFile = Path.Combine(_tempFolder, fileName);
  2442. if (File.Exists(tempFile))
  2443. {
  2444. return tempFile;
  2445. }
  2446. long fileSize = 0;
  2447. using (var request = new HttpRequestMessage())
  2448. {
  2449. request.RequestUri = new Uri(fileUrl);
  2450. request.Method = HttpMethod.Get;
  2451. var response = await _httpClient.SendAsync(request);
  2452. if (response != null && response.StatusCode == HttpStatusCode.OK)
  2453. {
  2454. var contentLength = response.Content.Headers.ContentLength;
  2455. fileSize = contentLength == null ? 0 : contentLength.Value;
  2456. }
  2457. }
  2458. if (fileSize <= 0)
  2459. {
  2460. throw new NotSupportedException($"fileSize is {fileSize}");
  2461. }
  2462. byte[] bytes = await _httpClient.GetByteArrayAsync(fileUrl);
  2463. File.WriteAllBytes(tempFile, bytes);
  2464. return tempFile;
  2465. }
  2466. catch (Exception ex)
  2467. {
  2468. Logger.WriteLineWarn($"MigrateService download file err, url: {fileUrl}, {ex}");
  2469. }
  2470. finally
  2471. {
  2472. //Logger.WriteLineInfo($"download file:{fileUrl}");
  2473. }
  2474. return string.Empty;
  2475. }
  2476. private async Task<string> UploadAsync(string localPath)
  2477. {
  2478. var authorizationResult = await _jsonRpcProxy.Storage.GetAuthorizationAsync(new FileServiceRequest
  2479. {
  2480. Token = DefaultToken,
  2481. FileName = Path.GetFileName(localPath),
  2482. IsRechristen = false,
  2483. });
  2484. var fileUrl = authorizationResult.StorageUrl;
  2485. using (var fileStream = new FileStream(localPath, FileMode.Open))
  2486. {
  2487. var size = fileStream.Length;
  2488. byte[] buffer = new byte[fileStream.Length];
  2489. fileStream.Read(buffer, 0, buffer.Length);
  2490. var requestHeads = new Dictionary<string, string>();
  2491. requestHeads.Add("Authorization", authorizationResult.Authorization);
  2492. using (var request = new HttpRequestMessage())
  2493. {
  2494. var fileExtension = Path.GetExtension(localPath);
  2495. var mimeType = FileHelper.GetMimeType(fileExtension);
  2496. var contentType = MediaTypeHeaderValue.Parse(mimeType);
  2497. using (UploadContent content = new UploadContent(buffer, contentType))
  2498. {
  2499. request.RequestUri = new Uri(fileUrl);
  2500. request.Method = HttpMethod.Put;
  2501. request.Content = content;
  2502. foreach (var head in requestHeads)
  2503. {
  2504. request.Headers.TryAddWithoutValidation(head.Key, head.Value);
  2505. }
  2506. var result = await ExecuteRequest(request);
  2507. if (result)
  2508. {
  2509. return fileUrl;
  2510. }
  2511. }
  2512. }
  2513. }
  2514. return null;
  2515. }
  2516. /// <summary>
  2517. /// 执行请求
  2518. /// </summary>
  2519. /// <param name="httpRequestMessage"></param>
  2520. /// <typeparam name="T"></typeparam>
  2521. /// <returns></returns>
  2522. private async Task<bool> ExecuteRequest(HttpRequestMessage httpRequestMessage)
  2523. {
  2524. try
  2525. {
  2526. var response = await _httpClient.SendAsync(httpRequestMessage);
  2527. if (response != null && response.StatusCode == HttpStatusCode.OK)
  2528. {
  2529. return true;
  2530. }
  2531. return false;
  2532. }
  2533. catch (Exception ex)
  2534. {
  2535. throw ex;
  2536. }
  2537. }
  2538. /// <summary>
  2539. /// 获取实际时间
  2540. /// </summary>
  2541. /// <param name="beginTime"></param>
  2542. /// <param name="endTime"></param>
  2543. /// <returns></returns>
  2544. private DateTime GetFactBeginTime(DateTime beginTime, DateTime endTime)
  2545. {
  2546. if (beginTime > endTime)
  2547. {
  2548. var dateDiff = endTime - beginTime;
  2549. if (dateDiff.TotalDays > 365)
  2550. {
  2551. beginTime = endTime.AddYears(-1);
  2552. }
  2553. }
  2554. else
  2555. {
  2556. var diffMintues = CommonConfigManager.MigrateRuleInfo.StartTimeDiffMintues;
  2557. if (diffMintues > 0)
  2558. {
  2559. beginTime = beginTime.AddMinutes(-diffMintues);
  2560. }
  2561. }
  2562. return beginTime;
  2563. }
  2564. }
  2565. public class AIDiagnosisPerImg
  2566. {
  2567. /// <summary>
  2568. /// Index
  2569. /// </summary>
  2570. public int Index { get; set; }
  2571. /// <summary>
  2572. /// Priority Score
  2573. /// </summary>
  2574. public float PriorityScore { get; set; }
  2575. /// <summary>
  2576. /// DiagResults of each Organ
  2577. /// </summary>
  2578. public IList<AIDiagResultPerOrganForDB> DiagResultsForEachOrgan { get; set; }
  2579. }
  2580. public class UploadContent : HttpContent
  2581. {
  2582. private const int ChunkSize = 2097152;//2M;
  2583. private readonly Stream _uploadStream;
  2584. private readonly long _fileSize;
  2585. public event EventHandler<double> ProgressChanged;
  2586. public UploadContent(string filePath)
  2587. {
  2588. if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
  2589. {
  2590. throw new Exception("UploadFile not find");
  2591. }
  2592. var fileName = Path.GetFileName(filePath);
  2593. _uploadStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  2594. var mimeType = FileHelper.GetMimeType(fileName.Substring(fileName.LastIndexOf(".")));
  2595. Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
  2596. Headers.ContentLength = _uploadStream.Length;
  2597. _fileSize = _uploadStream.Length;
  2598. }
  2599. public UploadContent(byte[] fileData, MediaTypeHeaderValue mediaTypeHeaderValue)
  2600. {
  2601. if (fileData == null || fileData.Length == 0)
  2602. {
  2603. throw new Exception("FileData is empty");
  2604. }
  2605. _uploadStream = new MemoryStream(fileData);
  2606. Headers.ContentType = mediaTypeHeaderValue;
  2607. Headers.ContentLength = _uploadStream.Length;
  2608. _fileSize = _uploadStream.Length;
  2609. }
  2610. /// <summary>
  2611. /// 将内容写入流
  2612. /// </summary>
  2613. /// <param name="stream"></param>
  2614. /// <param name="context"></param>
  2615. /// <returns></returns>
  2616. protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
  2617. {
  2618. for (long i = 0; i < _uploadStream.Length; i += ChunkSize)
  2619. {
  2620. var dataToWrite = new byte[Math.Min(ChunkSize, _uploadStream.Length - i)];
  2621. await _uploadStream.ReadAsync(dataToWrite, 0, dataToWrite.Length);
  2622. await stream.WriteAsync(dataToWrite, 0, dataToWrite.Length);
  2623. OnProgressChanged((double)(i * 100 / _uploadStream.Length));
  2624. }
  2625. OnProgressChanged(100);
  2626. }
  2627. /// <summary>
  2628. /// 比较文件大小
  2629. /// </summary>
  2630. /// <returns></returns>
  2631. public bool CompareFileSizes(long webFileSize)
  2632. {
  2633. return _fileSize == webFileSize;
  2634. }
  2635. protected override bool TryComputeLength(out long length)
  2636. {
  2637. length = _uploadStream.Length;
  2638. return true;
  2639. }
  2640. private void OnProgressChanged(double e)
  2641. {
  2642. ProgressChanged?.Invoke(this, e);
  2643. }
  2644. public new void Dispose()
  2645. {
  2646. base.Dispose();
  2647. _uploadStream.Close();
  2648. ProgressChanged = null;
  2649. }
  2650. }
  2651. }