1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128 |
- using Flyinsono.DBCopy.Tool.Entities;
- using Flyinsono.DBCopy.Tool.RpcService;
- using Flyinsono.DBCopy.Tool.Service.Repositories;
- using MongoDB.Driver;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Security;
- using System.Reflection;
- using System.Threading.Tasks;
- using System.Windows.Controls;
- using System.Xml.Linq;
- using WingInterfaceLibrary.DTO.Common;
- using WingInterfaceLibrary.DTO.DataCenter;
- using WingInterfaceLibrary.DTO.Management;
- using WingInterfaceLibrary.DTO.Record;
- using WingInterfaceLibrary.Enum;
- using WingInterfaceLibrary.Enum.CourseEnum;
- using WingInterfaceLibrary.Internal.Request;
- using WingInterfaceLibrary.Request;
- using WingInterfaceLibrary.Request.DBCopy;
- using WingServerCommon.Mapper;
- using MongoDB.Bson.IO;
- using JsonConvert = Newtonsoft.Json.JsonConvert;
- using WingInterfaceLibrary.Request.AIDiagnosis;
- using DnsClient.Protocol;
- using System.Text.RegularExpressions;
- using WingInterfaceLibrary.Result.AppletAPI;
- using WingInterfaceLibrary.DTO.Comment;
- using WingInterfaceLibrary.Request.Report;
- using WingInterfaceLibrary.DTO.Report;
- using WingInterfaceLibrary.LiveConsultation.Consultation;
- using WingInterfaceLibrary.DTO.Consultation;
- using System.Net.Http;
- using System.Net;
- using WingInterfaceLibrary.Request.Storage;
- using SharpCompress.Common;
- using System.Security.Policy;
- using System.Net.Http.Headers;
- using WingServerCommon.Interfaces.FileTransfer;
- using WingInterfaceLibrary.LiveConsultation;
- using WingInterfaceLibrary.Request.Report;
- using WingInterfaceLibrary.DTO.Report;
- using WingInterfaceLibrary.LiveConsultation.Consultation;
- using WingInterfaceLibrary.DTO.Consultation;
- using WingInterfaceLibrary.Request.User;
- using MongoDB.Driver.Core.Operations;
- namespace Flyinsono.DBCopy.Tool.Service
- {
- internal partial class MigrateService
- {
- private JsonRpcProxy _jsonRpcProxy;
- static HttpClient _httpClient = new HttpClient();
- private readonly string _tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DownloadTemp");
- private TerminalRecordDBRepository _terminalRecordDBRepository;
- private TerminalDatasDBRepository _terminalDatasDBRepository;
- private TerminalAIDatasDBRepository _terminalAIDatasDBRepository;
- private Carotid3dModelDatasDBRepository _carotid3dModelDatasDBRepository;
- private TerminalRecordReportStatesDBRepository _terminalRecordReportStatesDBRepository;
- private OrganizationsDBRepository _organizationsDBRepository;
- private TerminalsDBRepository _terminalsDBRepository;
- private PosterConfigsDBRepository _posterConfigsDBRepository;
- private MigrateRecordDTO _migrateRecord;
- private readonly string DefaultToken = "637f02a065ad47fbbe01b956919419c2";
- private ConsultationRecordDBRepository _consultationRecordDBRepository;
- private UsersDBRepository _usersDBRepository;
- private VideoDBRepository _videoDBRepository;
- private UserGroupDBRepository _userGroupDBRepository;
- private UltrasonicClassDBRepository _ultrasonicClassDBRepository;
- private CoursesDBRepository _coursesDBRepository;
- private AdminDBRepository _adminDBRepository;
- private ExaminationPaperDBPepository _examinationPaperDBPepository;
- private ExamScoreDBRepository _examScoreDBRepository;
- private ReportTemplateDBRepository _reportTemplateDBRepository;
- private ReportInfoResultDBRepository _reportInfoResultDBRepository;
- private CustomLabelDBRepository _customLabelDBRepository;
- protected readonly object locker = new object();
- public MigrateService(string dcServiceUrl)
- {
- _jsonRpcProxy = new JsonRpcProxy(dcServiceUrl);
- _httpClient.Timeout = TimeSpan.FromMinutes(15);
- _terminalRecordDBRepository = new TerminalRecordDBRepository();
- _terminalDatasDBRepository = new TerminalDatasDBRepository();
- _carotid3dModelDatasDBRepository = new Carotid3dModelDatasDBRepository();
- _terminalRecordReportStatesDBRepository = new TerminalRecordReportStatesDBRepository();
- _organizationsDBRepository = new OrganizationsDBRepository();
- _terminalsDBRepository = new TerminalsDBRepository();
- _posterConfigsDBRepository = new PosterConfigsDBRepository();
- _migrateRecord = GetQueryMigrateTimeRange();
- _terminalAIDatasDBRepository = new TerminalAIDatasDBRepository();
- _consultationRecordDBRepository = new ConsultationRecordDBRepository();
- _usersDBRepository = new UsersDBRepository();
- _videoDBRepository = new VideoDBRepository();
- _userGroupDBRepository = new UserGroupDBRepository();
- _ultrasonicClassDBRepository = new UltrasonicClassDBRepository();
- _coursesDBRepository = new CoursesDBRepository();
- _adminDBRepository = new AdminDBRepository();
- _examinationPaperDBPepository = new ExaminationPaperDBPepository();
- _examScoreDBRepository = new ExamScoreDBRepository();
- _reportTemplateDBRepository = new ReportTemplateDBRepository();
- _adminDBRepository = new AdminDBRepository();
- _reportInfoResultDBRepository = new ReportInfoResultDBRepository();
- _customLabelDBRepository = new CustomLabelDBRepository();
- }
- public async Task WriteMigrateStaticAsync()
- {
- Logger.WriteLineInfo($"Migrate Static Starting");
- Logger.WriteLineInfo($"terminal record totalCount:{_terminalRecordDBRepository.GetTerminalRecords(Builders<TerminalRecords>.Filter.Where(x => x.IsDelete == false)).Count()}");
- Logger.WriteLineInfo($"consultation record totalCount:{_consultationRecordDBRepository.GetTerminalRecords(Builders<ConsultationRecords>.Filter.Where(x => x.IsDeleted == false)).Count()}");
- Logger.WriteLineInfo($"video totalCount:{_videoDBRepository.GetVideos(Builders<Video>.Filter.Where(x => x.IsDeleted == false)).Count()}");
- Logger.WriteLineInfo($"course totalCount:{_coursesDBRepository.GetCourses(Builders<Courses>.Filter.Where(x => x.IsDeleted == false)).Count()}");
- Logger.WriteLineInfo($"exam paper totalCount:{_examinationPaperDBPepository.GetExaminationPapers(Builders<ExaminationPaper>.Filter.Where(x => x.IsDeleted == false)).Count()}");
- Logger.WriteLineInfo($"report totalCount:{_reportInfoResultDBRepository.GetReports(Builders<ReportInfoResults>.Filter.Where(x => true)).Count()}");
- Logger.WriteLineInfo($"terminal ai data totalCount:{_terminalAIDatasDBRepository.GetTerminalAIDatas(Builders<TerminalAIDatas>.Filter.Where(x => true)).Count()}");
- Logger.WriteLineInfo($"Migrate Static Successfully");
- }
- /// <summary>
- /// 查询同步数据的时间范围
- /// </summary>
- /// <returns></returns>
- private MigrateRecordDTO GetQueryMigrateTimeRange()
- {
- lock (locker)
- {
- if (_migrateRecord != null && _migrateRecord.EndTime > DateTime.MinValue)
- {
- return _migrateRecord;
- }
- var request = new QueryMigrateTimeRequest
- {
- Token = DefaultToken,
- IsInitMigreate = true
- };
- var result = _jsonRpcProxy.User.QueryMigrateTimeAsync(request).Result;
- return result;
- }
- }
- /// <summary>
- /// 备份库迁移分时诊断数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateRemoteDiagnosisInfosAsync()
- {
- Logger.WriteLineInfo($"Remote Diagnosis Infos Migrate Starting");
- var source = _terminalRecordDBRepository.GetTerminalRecords(Builders<TerminalRecords>.Filter.Where(x => x.IsDelete == false))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("terminal record", source, SendRemoteDiagnosisInfos);
- source.Clear();
- Logger.WriteLineInfo($"Remote Diagnosis Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移实时会诊数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateLiveConsultationInfosAsync()
- {
- Logger.WriteLineInfo($"Live Consultation Infos Migrate Starting");
- var source = _consultationRecordDBRepository.GetTerminalRecords(Builders<ConsultationRecords>.Filter.Where(x => x.IsDeleted == false))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("consultation record", source, SendLiveConsultationInfos);
- source.Clear();
- Logger.WriteLineInfo($"Live Consultation Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移在线视频数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateOnlineVideoInfosAsync()
- {
- Logger.WriteLineInfo($"Online Video Infos Migrate Starting");
- var videos = _videoDBRepository.GetVideos(Builders<Video>.Filter.Where(x => x.IsDeleted == false))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("video", videos, SendVideoInfos);
- videos.Clear();
- Logger.WriteLineInfo($"Online Video Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移在线培训数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateOnlineTrainingInfosAsync()
- {
- Logger.WriteLineInfo($"Online Training Infos Migrate Starting");
- var videos = _coursesDBRepository.GetCourses(Builders<Courses>.Filter.Where(x => x.IsDeleted == false))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("course", videos, SendCourseInfos);
- videos.Clear();
- Logger.WriteLineInfo($"Online Training Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移教培试卷数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateExamPaperInfosAsync()
- {
- Logger.WriteLineInfo($"Exam Paper Infos Migrate Starting");
- var examPapers = _examinationPaperDBPepository.GetExaminationPapers(Builders<ExaminationPaper>.Filter.Where(x => x.IsDeleted == false))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("exam paper", examPapers, SendExaminationPaperInfos);
- examPapers.Clear();
- Logger.WriteLineInfo($"Exam Paper Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移报告数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateReportInfosAsync()
- {
- Logger.WriteLineInfo($"Report Infos Migrate Starting");
- var reports = _reportInfoResultDBRepository.GetReports(Builders<ReportInfoResults>.Filter.Where(x => true))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("report", reports, SendReportInfos);
- reports.Clear();
- Logger.WriteLineInfo($"Report Infos Migrate Successfully");
- }
- /// <summary>
- /// 备份库迁移图像诊断结果数据
- /// </summary>
- /// <returns></returns>
- public async Task MigrateTerminalAIDataInfosAsync()
- {
- Logger.WriteLineInfo($"Terminal AI Data Infos Migrate Starting");
- var terminalAIDatas = _terminalAIDatasDBRepository.GetTerminalAIDatas(Builders<TerminalAIDatas>.Filter.Where(x => true))
- .OrderByDescending(x => x.CreateTime).ThenBy(x => x.Id).ToList();
- OnMigrate("terminal ai data", terminalAIDatas, SendTerminalAIDataInfos);
- terminalAIDatas.Clear();
- Logger.WriteLineInfo($"Terminal AI Data Infos Migrate Successfully");
- }
- private void OnMigrate<IEntity>(string name, IList<IEntity> source, Action<IList<IEntity>, SyncDBEnum> migrateAction, SyncDBEnum syncType = SyncDBEnum.Migrate,int processNumber=100)
- {
- Logger.WriteLineInfo($"{name} totalCount:{source.Count}");
- var totalCount = source.Count;
- var processedCount = 0;
- var minute = DateTime.Now.Minute;
- while (true)
- {
- var pendingRecords = source.Skip(processedCount).Take(processNumber)?.ToList() ?? new List<IEntity>();
- var pendingCount = pendingRecords.Count;
- if (pendingCount > 0)
- {
- migrateAction.Invoke(pendingRecords, syncType);
- processedCount += pendingCount;
- }
- if (DateTime.Now.Minute != minute)
- {
- minute = DateTime.Now.Minute;
- Logger.WriteLineInfo($"{name} processing: {processedCount * 100 / totalCount}%");
- }
- if (pendingCount < processNumber)
- {
- Logger.WriteLineInfo($"{name} processing: 100%");
- break;
- }
- }
- }
- private void SendRemoteDiagnosisInfos(IList<TerminalRecords> terminalRecords, SyncDBEnum syncType)
- {
- try
- {
- var terminalRecordCodes = terminalRecords.Select(x => x.Id).ToList();
- var terminalDatas = _terminalDatasDBRepository.GetTerminalDatasByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalDatas>();
- var terminalRecordStates = _terminalRecordReportStatesDBRepository.GetTerminalRecordReportStatesByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalRecordReportStates>();
- var deviceCodes = terminalRecords.Select(x => x.Terminal?.Id ?? string.Empty).ToList();
- var terminals = _terminalsDBRepository.GetTerminalByCodes(deviceCodes)?.ToList() ?? new List<Terminals>();
- var orgCodes = terminalRecords.Select(x => x.Organization?.Id ?? string.Empty).ToList();
- if (terminals.Any())
- {
- var terminalOrgs = terminals.Select(x => x.Organization?.Id ?? string.Empty);
- orgCodes = orgCodes.Union(terminalOrgs).ToList();
- }
- var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgCodes)?.ToList() ?? new List<Organizations>();
- var remoteDiagnosisInfos = new List<RemoteDiagnosisDTO>();
- foreach (var terminalRecord in terminalRecords)
- {
- var terminalRecordId = terminalRecord.Id;
- var patientInfo = terminalRecord.PatientInfo;
- var terminalDataInfos = terminalDatas.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalDatas>();
- var terminalRecordStateInfos = terminalRecordStates.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalRecordReportStates>();
- var remoteDiagnosisInfo = new RemoteDiagnosisDTO
- {
- Code = terminalRecordId,
- CreateTime = terminalRecord.CreateTime,
- UpdateTime = terminalRecord.UpdateTime,
- ExamId = terminalRecord.ExamId,
- OrganizationInfo = MapToOrganizationView(organizations, terminalRecord.Organization?.Id),
- DeviceInfo = MapToDeviceView(terminals, terminalRecord.Terminal?.Id),
- QualifiedInfo = new QualifiedView
- {
- QualifiedState = (WingInterfaceLibrary.Enum.QualifiedState)terminalRecord.QualifiedState,
- QualityType = (WingInterfaceLibrary.Enum.QualityType)terminalRecord.QualityType,
- },
- DiagnosisInfos = new List<DiagnosisView>(),
- ShareUserCodes = terminalRecord.SharerIds?.ToList() ?? new List<string>(),
- CustomDoctor = terminalRecord.CustomDoctor,
- CustomOrganzation = terminalRecord.CustomOrganzation,
- EquipmentSN = terminalRecord.EquipmentSN,
- FileInfos = terminalDataInfos.Select(x =>
- {
- var fileInfo = x.Files.FirstOrDefault(f => f.ImageQuality == ImageQuality.High);
- var fileUrl = GetFileUrl(fileInfo?.FileName);
- var terminalData = new RemoteDiagnosisFileView
- {
- DataType = (WingInterfaceLibrary.Enum.RemedicalFileDataTypeEnum)x.DataType,
- OriginalUrl = fileUrl,
- CdnUrl = fileUrl,
- PreviewUrl = GetFileUrl(x.PreviewImageFileToken),
- ConverUrl = "",
- Application = x.Application,
- };
- if (x.ImageLocation != null)
- {
- if (x.ImageLocation is BreastImageLocation bi)
- {
- terminalData.ImageLocationInfo = new ImageLocationView
- {
- Group = "BreastImageLocation",
- Position = bi.Position.ToString(),
- Quadrant = bi.Quadrant.ToString(),
- };
- }
- if (x.ImageLocation is LiverImageLocation li)
- {
- terminalData.ImageLocationInfo = new ImageLocationView
- {
- Group = "LiverImageLocation",
- Position = li.Position.ToString(),
- };
- }
- if (x.ImageLocation is PositionImageLocation pi)
- {
- terminalData.ImageLocationInfo = new ImageLocationView
- {
- Group = pi.Position,
- Position = pi.Position.ToString(),
- };
- }
- }
- return terminalData;
- }).ToList(),
- CompletedUsers = terminalRecordStateInfos.Select(x => x.UserId).ToList(),
- };
- if (patientInfo != null)
- {
- remoteDiagnosisInfo.PatientInfo = new PatientView
- {
- IdentityCardId = patientInfo.IdentityCardId,
- Name = patientInfo.LastName,
- Gender = patientInfo.GenderType.ToString(),
- Age = patientInfo.Age,
- };
- }
- if (terminalRecord.TerminalRecordSource == TerminalRecordSource.Screenshot)
- {
- remoteDiagnosisInfo.ScreenshotInfo = new ScreenshotView
- {
- CreateUserCode = terminalRecord.CreatorUserId,
- CreateUserName = "",
- PrelDiagnosis = terminalRecord.PrelDiagnosis,
- ExamDoctor = terminalRecord.ExamDoctor,
- };
- }
- if (terminalRecord.AIDiagnosisInfos != null && terminalRecord.AIDiagnosisInfos.Any())
- {
- remoteDiagnosisInfo.DiagnosisInfos = terminalRecord.AIDiagnosisInfos.Select(x => new DiagnosisView
- {
- Organ = (WingInterfaceLibrary.Enum.DiagnosisOrganEnum)x.Organ,
- DiagnosisStatus = (WingInterfaceLibrary.Enum.DiagnosisConclusionEnum)x.Status,
- }).ToList();
- }
- remoteDiagnosisInfos.Add(remoteDiagnosisInfo);
- }
- var request = new ReceiveRemoteDiagnosisRequest
- {
- RemoteDiagnosisInfos = remoteDiagnosisInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveRemoteDiagnosisAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemoteDiagnosisInfos err, ex:{ex}");
- }
- }
- private void SendLiveConsultationInfos(IList<ConsultationRecords> consultationRecords, SyncDBEnum syncType)
- {
- try
- {
- var userIds = consultationRecords.Select(x => x.DoctorInfo?.ID ?? string.Empty)
- .Union(consultationRecords.Select(x => x.ExpertInfo?.ID ?? string.Empty))
- .Distinct().ToList();
- var users = _usersDBRepository.GetUserByCodes(userIds);
- var orgIds = consultationRecords.Select(x => x.PrimaryHosptial?.Id ?? string.Empty)
- .Union(consultationRecords.Select(x => x.CentralHospital?.Id ?? string.Empty))
- .Union(users.Select(x => x.HospitalId))
- .Distinct().ToList();
- var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
- var terminalIds = consultationRecords.Select(x => x.TerminalInfo?.Id ?? string.Empty).Distinct().ToList();
- var terminals = _terminalsDBRepository.GetTerminalByCodes(terminalIds);
- var liveConsultationInfos = new List<LiveConsultationDTO>();
- foreach (var consultationRecord in consultationRecords)
- {
- var patient = consultationRecord.PatientInfo;
- var liveConsultationInfo = new LiveConsultationDTO
- {
- Code = consultationRecord.Id,
- CreateTime = consultationRecord.CreateTime,
- UpdateTime = consultationRecord.UpdateTime,
- ScanUserName = consultationRecord.ScanDoctor,
- ConsultationTime = consultationRecord.AppointmentTime,
- DoctorInfo = MapToUserView(organizations, users, consultationRecord.DoctorInfo?.ID),
- ExpertInfo = MapToUserView(organizations, users, consultationRecord.ExpertInfo?.ID),
- PrimaryHosptial = MapToOrganizationView(organizations, consultationRecord.PrimaryHosptial?.Id),
- CentralHospital = MapToOrganizationView(organizations, consultationRecord.CentralHospital?.Id),
- DeviceInfo = MapToDeviceView(terminals, consultationRecord.TerminalInfo?.Id),
- CheckPoint = consultationRecord.CheckPoint,
- ConsultationNumber = consultationRecord.ConsultationNumber,
- QueuingNumber = consultationRecord.QueuingNumber,
- IsNeedFollowUpVisit = consultationRecord.IsNeedFollowUpVisit,
- State = (WingInterfaceLibrary.Enum.ConsultationState)consultationRecord.State,
- QualityType = (WingInterfaceLibrary.Enum.QualityType)consultationRecord.QualityType,
- FollowUpVisitStatus = (FollowUpVisitStatusEnum)consultationRecord.FollowUpVisitStatus,
- EvaluateGrade = (EvaluateGradeEnum)consultationRecord.EvaluateGrade,
- FileInfos = new List<LiveConsultationFileView>(),
- ReportConclusionInfos = new List<ReportConclusionView>(),
- };
- if (patient != null)
- {
- liveConsultationInfo.PatientInfo = new PatientView
- {
- IdentityCardId = patient.ID,
- Name = patient.Name,
- Mobile = patient.ContactInfo,
- Gender = patient.GenderType.ToString(),
- Age = patient.Age,
- //PastHistory = patient.PastHistory,
- //Diagnosis = patient.Diagnosis,
- };
- }
- if (consultationRecord.ImageTokens != null && consultationRecord.ImageTokens.Any())
- {
- foreach (var item in consultationRecord.ImageTokens)
- {
- liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
- {
- Type = "FileTokens",
- DataType = RemedicalFileDataTypeEnum.VinnoVidSingle,
- OriginalUrl = GetFileUrl(item),
- CdnUrl = GetFileUrl(item),
- PreviewUrl = "",
- ConverUrl = "",
- });
- }
- }
- if (consultationRecord.VideoTokens != null && consultationRecord.VideoTokens.Any())
- {
- foreach (var item in consultationRecord.VideoTokens)
- {
- liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
- {
- Type = "FileTokens",
- DataType = RemedicalFileDataTypeEnum.VinnoVidMovie,
- OriginalUrl = GetFileUrl(item.VideoToken),
- CdnUrl = GetFileUrl(item.VideoToken),
- PreviewUrl = GetFileUrl(item.PreviewImageToken),
- ConverUrl = "",
- });
- }
- }
- if (consultationRecord.GraphicData != null && consultationRecord.GraphicData.Any())
- {
- foreach (var item in consultationRecord.GraphicData)
- {
- liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
- {
- Type = "GraphicData",
- DataType = item.GraphicType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie,
- OriginalUrl = GetFileUrl(item.GraphicToken),
- CdnUrl = GetFileUrl(item.GraphicToken),
- PreviewUrl = GetFileUrl(item.PreviewGraphicToken),
- ConverUrl = "",
- UserCode = item.UserId,
- });
- }
- }
- if (consultationRecord.PreFileItems != null && consultationRecord.PreFileItems.Any())
- {
- foreach (var item in consultationRecord.PreFileItems)
- {
- liveConsultationInfo.FileInfos.Add(new LiveConsultationFileView
- {
- Type = "PreFileItems",
- DataType = item.FileType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie,
- OriginalUrl = GetFileUrl(item.OriginalFileUrl),
- CdnUrl = GetFileUrl(item.OriginalFileUrl),
- PreviewUrl = GetFileUrl(item.ThumbnailUrl),
- ConverUrl = "",
- UserCode = item.Uploader,
- FileName = item.FileName,
- });
- }
- }
- if (consultationRecord.ReportConclusionInfos != null && consultationRecord.ReportConclusionInfos.Any())
- {
- foreach (var item in consultationRecord.ReportConclusionInfos)
- {
- liveConsultationInfo.ReportConclusionInfos.Add(new ReportConclusionView
- {
- ReportId = item.ReportId,
- DiseaseName = item.DiseaseName,
- DiseaseConclusion = (WingInterfaceLibrary.Enum.DiseaseConclusion)item.DiseaseConclusion,
- });
- }
- }
- liveConsultationInfos.Add(liveConsultationInfo);
- }
- var request = new ReceiveLiveConsultationRequest
- {
- LiveConsultationInfos = liveConsultationInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveLiveConsultationAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendLiveConsultationInfos err, ex:{ex}");
- }
- }
- private void SendVideoInfos(IList<Video> videos, SyncDBEnum syncType)
- {
- try
- {
- var userIds = videos.Select(x => x.CreatorId)
- .Union(videos.SelectMany(x => x.UserIds ?? new List<string>()))
- .Union(videos.SelectMany(x => x.FinishedUserIds ?? new List<string>()))
- .Distinct().ToList();
- var users = _usersDBRepository.GetUserByCodes(userIds);
- var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
- var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
- var userGroupIds = videos.SelectMany(x => x.UserGroupIds ?? new List<string>()).Distinct().ToList();
- var userGroups = _userGroupDBRepository.GetUserGroupByCodes(userGroupIds);
- var classIds = videos.SelectMany(x => x.ClassIds ?? new List<string>()).Distinct().ToList();
- var classes = _ultrasonicClassDBRepository.GetUltrasonicClassByCodes(classIds);
- //var courseIds = videos.SelectMany(x => x.Courses ?? new List<VideoLinkCourseInfo>()).Select(x => x.Id).Distinct().ToList();
- //var courses = _coursesDBRepository.GetCourseByCodes(courseIds);
- var onlineVideoInfos = new List<OnlineVideoDTO>();
- foreach (var video in videos)
- {
- var creator = MapToUserView(organizations, users, video.CreatorId);
- var videoInfo = new OnlineVideoDTO
- {
- Code = video.Id,
- CreateTime = video.CreateTime,
- UpdateTime = video.UpdateTime,
- Name = video.Title,
- Poster = GetFileUrl(video.PosterToken),
- Duration = video.Duration,
- VideoSize = video.Size,
- Description = video.Description,
- VideoToken = video.Url,
- Importance = (VideoImportanceEnum)video.Importance,
- CreatorCode = video.CreatorId,
- CreatorName = creator?.Name,
- Permissions = (VideoPermissionsEnum)video.Permissions,
- Users = new List<UserView>(),
- UserGroups = new List<GroupView>(),
- Courses = new List<OnlineTrainingDTO>(),
- ClassInfos = new List<ClassView>(),
- Labels = new List<VideoLabelEnum>(),
- TeachingDocumentName = video.TeachingDocumentName,
- TeachingDocument = GetFileUrl(video.TeachingDocument),
- RealBrowsedCount = video.RealBrowsedCount,
- BaseBrowsedCount = video.BaseBrowsedCount,
- FinishedUsers = new List<UserView>(),
- };
- if (video.UserIds != null && video.UserIds.Any())
- {
- foreach (var item in video.UserIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- videoInfo.Users.Add(user);
- }
- }
- }
- if (video.FinishedUserIds != null && video.FinishedUserIds.Any())
- {
- foreach (var item in video.FinishedUserIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- videoInfo.FinishedUsers.Add(user);
- }
- }
- }
- if (video.Labels != null && video.Labels.Any())
- {
- foreach (var item in video.Labels)
- {
- videoInfo.Labels.Add((VideoLabelEnum)item);
- }
- }
- if (video.Courses != null && video.Courses.Any())
- {
- foreach (var item in video.Courses)
- {
- videoInfo.Courses.Add(new OnlineTrainingDTO
- {
- Code = item.Id,
- Name = item.Name,
- });
- }
- }
- if (video.UserGroupIds != null && video.UserGroupIds.Any())
- {
- foreach (var item in video.UserGroupIds)
- {
- var userGroup = MapToUserGroupView(userGroups, item);
- if (userGroup != null)
- {
- videoInfo.UserGroups.Add(userGroup);
- }
- }
- }
- if (video.ClassIds != null && video.ClassIds.Any())
- {
- foreach (var item in video.ClassIds)
- {
- var classInfo = MapToClassView(classes, item);
- if (classInfo != null)
- {
- videoInfo.ClassInfos.Add(classInfo);
- }
- }
- }
- onlineVideoInfos.Add(videoInfo);
- }
- var request = new ReceiveOnlineVideoRequest
- {
- OnlineVideoInfos = onlineVideoInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveOnlineVideoAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendVideoInfos err, ex:{ex}");
- }
- }
- private void SendCourseInfos(IList<Courses> courses, SyncDBEnum syncType)
- {
- try
- {
- var userIds = courses.SelectMany(x => x.AssistantIds ?? new List<string>())
- .Union(courses.SelectMany(x => x.GuestIds ?? new List<string>()))
- .Union(courses.SelectMany(x => x.MeetingMemberIds ?? new List<string>()))
- .Distinct().ToList();
- var users = _usersDBRepository.GetUserByCodes(userIds);
- var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
- var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
- var onlineTrainingInfos = new List<OnlineTrainingDTO>();
- foreach (var course in courses)
- {
- var teacher = course.Teacher;
- var createAdmin = course.CreateAdmin;
- var courseInfo = new OnlineTrainingDTO
- {
- Code = course.Id,
- CreateTime = course.CreateTime,
- UpdateTime = course.UpdateTime,
- Name = course.Name,
- CourseIntro = course.Information,
- Price = (decimal)course.Price,
- Status = (CourseStatusEnum)course.State,//TODO
- StartTime = course.StarTime,
- Duration = course.Duration,
- Deadline = course.Deadline,
- ApplyState = (ApplyStateEnum)course.ApplyState,//TODO
- Poster = GetFileUrl(course.Poster),
- Students = new List<SignStudentView>(),
- ConversationId = course.ConversationId,//TODO
- ChannelDatas = new List<ChannelDataView>(),
- Owners = new List<AdminView>(),
- TeacherOnlineState = course.TeacherState == TeacherState.OnLine,
- StartCourseInAdvance = course.StartCourseInAdvance,
- ActualStartTime = course.ActualStartTime ?? DateTime.MinValue,
- ActualEndTime = course.ActualEndTime ?? DateTime.MinValue,
- AssistantInfos = new List<UserView>(),
- GuestInfos = new List<UserView>(),
- CredentialCode = course.CredentialCode,
- CourseNotice = course.CourseNotice,
- MeetingMemberInfos = new List<UserView>(),
- };
- if (teacher != null)
- {
- var name = !string.IsNullOrWhiteSpace(teacher.FullName) ? teacher.FullName
- : !string.IsNullOrWhiteSpace(teacher.LastName) ? teacher.LastName
- : !string.IsNullOrWhiteSpace(teacher.FirstName) ? teacher.FirstName
- : !string.IsNullOrWhiteSpace(teacher.NickName) ? teacher.NickName
- : teacher.Name;
- courseInfo.TeacherCode = teacher.Id;
- courseInfo.TeacherName = name;
- }
- if (course.ChannelDatas != null && course.ChannelDatas.Any())
- {
- foreach (var item in course.ChannelDatas)
- {
- courseInfo.ChannelDatas.Add(new ChannelDataView
- {
- ChannelId = item.ChannelId,
- DownLoadUrl = item.DownLoadUrl,
- UpLoadUrl = item.UpLoadUrl,
- Description = (ChannelDescriptionEnum)item.Description,
- HttpUrl = item.HttpUrl,
- HlsUrl = item.HlsUrl,
- });
- }
- }
- if (course.Students != null && course.Students.Any())
- {
- foreach (var item in course.Students)
- {
- courseInfo.Students.Add(new SignStudentView
- {
- StudentCode = item.Id,
- StudentName = item.Name,
- SmallHeadImage = item.SmallHeadImage,
- IsNoSpeaking = item.IsNoSpeaking,
- IsAssistant = item.IsAssistant,
- });
- }
- }
- if (createAdmin != null)
- {
- courseInfo.CreateAdmin = new AdminView
- {
- Code = createAdmin._id,
- Name = createAdmin.Name,
- };
- }
- if (course.Owners != null && course.Owners.Any())
- {
- foreach (var item in course.Owners)
- {
- courseInfo.Owners.Add(new AdminView
- {
- Code = item._id,
- Name = item.Name,
- });
- }
- }
- if (course.AssistantIds != null && course.AssistantIds.Any())
- {
- foreach (var item in course.AssistantIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- courseInfo.AssistantInfos.Add(user);
- }
- }
- }
- if (course.GuestIds != null && course.GuestIds.Any())
- {
- foreach (var item in course.GuestIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- courseInfo.GuestInfos.Add(user);
- }
- }
- }
- if (course.MeetingMemberIds != null && course.MeetingMemberIds.Any())
- {
- foreach (var item in course.MeetingMemberIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- courseInfo.MeetingMemberInfos.Add(user);
- }
- }
- }
- onlineTrainingInfos.Add(courseInfo);
- }
- var request = new ReceiveOnlineTrainingRequest
- {
- OnlineTrainingInfos = onlineTrainingInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveOnlineTrainingAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendCourseInfos err, ex:{ex}");
- }
- }
- private void SendExaminationPaperInfos(IList<ExaminationPaper> examPapers, SyncDBEnum syncType)
- {
- try
- {
- var userIds = examPapers.Select(x => x.CreatorId)
- .Union(examPapers.SelectMany(x => x.ExaminerIds ?? new List<string>()))
- .Distinct().ToList();
- var users = _usersDBRepository.GetUserByCodes(userIds);
- var admins = _adminDBRepository.GetAdminByCodes(userIds);
- var orgIds = users.Select(x => x.HospitalId).Distinct().ToList();
- var organizations = _organizationsDBRepository.GetOrganizationByCodes(orgIds);
- var userGroupIds = examPapers.SelectMany(x => x.ExaminerUserGroupIds ?? new List<string>()).Distinct().ToList();
- var userGroups = _userGroupDBRepository.GetUserGroupByCodes(userGroupIds);
- var classIds = examPapers.SelectMany(x => x.ClassIds ?? new List<string>()).Distinct().ToList();
- var classes = _ultrasonicClassDBRepository.GetUltrasonicClassByCodes(classIds);
- var examIds = examPapers.Select(x => x.Id).ToList();
- var examScores = _examScoreDBRepository.GetExamScoresByCodes(examIds);
- var examPaperInfos = new List<ExamPaperDTO>();
- foreach (var examPaper in examPapers)
- {
- var creatorName = MapToUserView(organizations, users, examPaper.CreatorId)?.Name;
- if (string.IsNullOrWhiteSpace(creatorName))
- {
- var admin = admins.FirstOrDefault(x => x._id == examPaper.CreatorId);
- if (admin != null)
- {
- var adminName = !string.IsNullOrWhiteSpace(admin.FullName) ? admin.FullName
- : !string.IsNullOrWhiteSpace(admin.LastName) ? admin.LastName
- : !string.IsNullOrWhiteSpace(admin.FirstName) ? admin.FirstName
- : admin.Name;
- creatorName = adminName;
- }
- }
- var examPaperInfo = new ExamPaperDTO
- {
- Code = examPaper.Id,
- CreateTime = examPaper.CreateTime,
- UpdateTime = examPaper.UpdateTime,
- Name = examPaper.Title,
- Description = examPaper.Description,
- StarTime = examPaper.StarTime,
- EndTime = examPaper.EndTime,
- TotalScore = examPaper.TotalScore,
- LimitCount = examPaper.LimitCount,
- Result = examPaper.Result,
- Examiners = new List<UserView>(),
- ExaminerUserGroups = new List<GroupView>(),
- ExaminationAvailability = (ExaminationAvailabilityEnum)examPaper.ExaminationAvailability,
- Classes = new List<ClassView>(),
- CreatorId = examPaper.CreatorId,
- CreatorName = creatorName,
- ExamType = (ExamTypeEnum)examPaper.ExamType,
- HasPassScore = examPaper.HasPassScore,
- PassScore = examPaper.PassScore,
- IsDisplayAnswer = examPaper.IsDisplayAnswer,
- ExamVideoInfos = new List<ExamVideoView>(),
- ExamScoreInfos = new List<ExamScoreView>(),
- };
- if (examPaper.ExaminerIds != null && examPaper.ExaminerIds.Any())
- {
- foreach (var item in examPaper.ExaminerIds)
- {
- var user = MapToUserView(organizations, users, item);
- if (user != null)
- {
- examPaperInfo.Examiners.Add(user);
- }
- }
- }
- if (examPaper.ExaminerUserGroupIds != null && examPaper.ExaminerUserGroupIds.Any())
- {
- foreach (var item in examPaper.ExaminerUserGroupIds)
- {
- var userGroup = MapToUserGroupView(userGroups, item);
- if (userGroup != null)
- {
- examPaperInfo.ExaminerUserGroups.Add(userGroup);
- }
- }
- }
- if (examPaper.ClassIds != null && examPaper.ClassIds.Any())
- {
- foreach (var item in examPaper.ClassIds)
- {
- var classInfo = MapToClassView(classes, item);
- if (classInfo != null)
- {
- examPaperInfo.Classes.Add(classInfo);
- }
- }
- }
- if (examPaper.ExamVideoInfos != null && examPaper.ExamVideoInfos.Any())
- {
- foreach (var item in examPaper.ExamVideoInfos)
- {
- examPaperInfo.ExamVideoInfos.Add(new ExamVideoView
- {
- Id = item.Id,
- VideoName = item.VideoName,
- CreateTime = item.CreateTime,
- PosterToken = GetFileUrl(item.PosterToken),
- Duration = item.Duration,
- Size = item.Size,
- Description = item.Description,
- Url = GetFileUrl(item.Url),
- });
- }
- }
- if (examPaper.ExamTemplate != null)
- {
- var examTemplate = examPaper.ExamTemplate.MappingTo<ExamTemplateView>();
- if (examTemplate != null && examTemplate.Subjects != null && examTemplate.Subjects.Any())
- {
- foreach (var item in examTemplate.Subjects)
- {
- item.Images = item.Images?.Select(x => GetFileUrl(x))?.ToList() ?? new List<string>();
- if (item.Videos != null && item.Videos.Any())
- {
- item.Videos?.ForEach(x =>
- {
- x.VideoImageToken = GetFileUrl(x.VideoImageToken);
- x.VideoToken = GetFileUrl(x.VideoToken);
- });
- }
- }
- }
- examPaperInfo.ExamTemplate = examTemplate;
- }
- var examScoreInfos = examScores.Where(x => x.ExamId == examPaper.Id)?.ToList() ?? new List<ExamScores>();
- if (examScoreInfos.Any())
- {
- examPaperInfo.ExamScoreInfos = examScoreInfos.MappingTo<List<ExamScoreView>>();
- }
- examPaperInfos.Add(examPaperInfo);
- }
- var request = new ReceiveExamPaperInfosRequest
- {
- ExamPaperInfos = examPaperInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveExamPaperAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendCourseInfos err, ex:{ex}");
- }
- }
- private void SendReportInfos(IList<ReportInfoResults> reports, SyncDBEnum syncType)
- {
- try
- {
- var customLabelIds = reports.SelectMany(x => x.CustomLabels ?? new List<string>()).Distinct().ToList();
- var customerLabels = _customLabelDBRepository.GetCustomLabelByCodes(customLabelIds);
- var reportInfos = new List<ReportInfoResultDTO>();
- foreach (var report in reports)
- {
- var reportInfo = new ReportInfoResultDTO
- {
- Code = report.Id,
- CreateTime = report.CreateTime,
- UpdateTime = report.UpdateTime,
- ReportTemplateJson = report.Template,
- ElementCollectionJson = Newtonsoft.Json.JsonConvert.SerializeObject(report.ElementCollection),
- MeasureElementCollectionJson = Newtonsoft.Json.JsonConvert.SerializeObject(report.MeasureElementCollection),
- ReportUserCode = report.User?._id,
- ReportUserName = report.User?.Name,
- RecordCode = report.RecordId,
- PatientPerfPhysician = report.PatientPerfPhysician,
- PatientRefPhysician = report.PatientRefPhysician,
- PatientName = report.PatientName,
- PreviewImages = report.PreviewImages.MappingTo<List<WingInterfaceLibrary.DTO.DataCenter.ReportImageInfo>>(),
- CustomLabels = new List<CustomLabelView>(),
- ReportOrgan = (DiagnosisOrganEnum)report.Organ,
- QualifiedState = (WingInterfaceLibrary.Enum.QualifiedState)report.QualifiedState,
- QualityType = (WingInterfaceLibrary.Enum.QualityType)report.QualityType,
- ReportPreviewPdf = GetFileUrl(report.ReportPreviewPdf),
- QualityControlDatas = new List<QualityControlDataView>(),
- };
- if (report.CustomLabels != null && report.CustomLabels.Any())
- {
- foreach (var item in report.CustomLabels)
- {
- var customLabel = customerLabels.FirstOrDefault(x => x.Code == item);
- if (customLabel != null)
- {
- reportInfo.CustomLabels.Add(customLabel.MappingTo<CustomLabelView>());
- }
- }
- }
- if (report.QualityControlDatas != null && report.QualityControlDatas.Any())
- {
- reportInfo.QualityControlDatas = report.QualityControlDatas.MappingTo<List<QualityControlDataView>>();
- }
- reportInfos.Add(reportInfo);
- }
- var request = new ReceiveReportInfosRequest
- {
- ReportInfos = reportInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveReportAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendReportInfos err, ex:{ex}");
- }
- }
- private void SendTerminalAIDataInfos(IList<TerminalAIDatas> terminalAIDatas, SyncDBEnum syncType)
- {
- try
- {
- var fileDiagnosisInfos = new List<FileDiagnosisResultDTO>();
- foreach (var terminalAIData in terminalAIDatas)
- {
- var fileDiagnosisResult = new FileDiagnosisResultDTO
- {
- Code = terminalAIData.Id,
- CreateTime = terminalAIData.CreateTime,
- UpdateTime = terminalAIData.UpdateTime,
- RemedicalCode = terminalAIData.TerminalDataId,
- };
- var diagnosisDatas = new List<AIDiagnosisPerImg>();
- foreach (var item in terminalAIData.DiagResults)
- {
- diagnosisDatas.Add(new AIDiagnosisPerImg
- {
- Index = item.Index,
- PriorityScore = item.ImageDiagResult.PriorityScore,
- DiagResultsForEachOrgan = item.ImageDiagResult.DiagResultsForEachOrgan,
- });
- }
- fileDiagnosisResult.DiagnosisOrgans = GetDiagnosisOrgans(diagnosisDatas);
- fileDiagnosisResult.DiagnosisConclusion = GetDiagnosisConclusion(diagnosisDatas);
- fileDiagnosisResult.DiagnosisResult = Newtonsoft.Json.JsonConvert.SerializeObject(diagnosisDatas);
- fileDiagnosisInfos.Add(fileDiagnosisResult);
- }
- var request = new ReceiveFileDiagnosisResultInfosRequest
- {
- FileDiagnosisResultInfos = fileDiagnosisInfos,
- };
- var result = _jsonRpcProxy.DataCenter.ReceiveFileDiagnosisResultAsync(request).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendTerminalAIDataInfos err, ex:{ex}");
- }
- }
- /// <summary>
- /// 同步热数据到2.0
- /// </summary>
- /// <returns></returns>
- public async Task MigrateRemedicalAndConsultationToWingServerAsync()
- {
- Logger.WriteLineInfo($"Remote diagnosis infos migrate to wingServer starting");
- //远程
- MigrateRemedicalRecords(SyncDBEnum.Synchronize);
- //远程图像
- MigrateRemedicalDatas(SyncDBEnum.Synchronize);
- //AI
- MigrateRemedicalAIDatas(SyncDBEnum.Synchronize);
- //颈动脉
- MigrateRemedicalCarotidDatas(SyncDBEnum.Synchronize);
- //会诊
- MigrateConsultationResults(SyncDBEnum.Synchronize);
- //报告
- MigrateReportInfoResults(SyncDBEnum.Synchronize);
- Logger.WriteLineInfo($"Remote diagnosis infos migrate to wingServer successfully");
- }
- public async Task MigrateRemedicalRecords(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"Remote diagnosis records migrate to wingServer starting");
- //获取上次同步到的时间
- var builder = Builders<TerminalRecords>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => x.IsDelete == false && ((x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime)));
- var terminalRecords = _terminalRecordDBRepository.GetTerminalRecords(filter).OrderByDescending(x=>x.CreateTime).ToList();
- OnMigrate("Remote diagnosis records", terminalRecords, SendRemedicalRecordInfos, syncType,1000);
- terminalRecords.Clear();
- Logger.WriteLineInfo($"Remote diagnosis records migrate to wingServer successfully");
- }
- private void SendRemedicalRecordInfos(IList<TerminalRecords> terminalRecords, SyncDBEnum syncType)
- {
- try
- {
- var terminalRecordCodes = terminalRecords.Select(x => x.Id).ToList();
- var terminalRecordStates = _terminalRecordReportStatesDBRepository.GetTerminalRecordReportStatesByCodes(terminalRecordCodes)?.ToList() ?? new List<TerminalRecordReportStates>();
- var syncBatchRemedicalRecordRequest = new SyncBatchRemedicalRecordRequest();
- syncBatchRemedicalRecordRequest.SyncType = syncType;
- syncBatchRemedicalRecordRequest.RemedicalRecordList = new List<SyncRemedicalRecordRequest>();
- foreach (var terminalRecord in terminalRecords)
- {
- try
- {
- var terminalRecordId = terminalRecord.Id;
- var terminalRecordStateInfos = terminalRecordStates.Where(x => x.TerminalRecordId == terminalRecordId)?.ToList() ?? new List<TerminalRecordReportStates>();
- var patientInfo = terminalRecord.PatientInfo;
- var remoteDiagnosisInfo = new SyncRemedicalRecordRequest
- {
- Code = terminalRecordId,
- OrganizationCode = terminalRecord.Organization?.Id,
- DeviceCode = terminalRecord.Terminal?.Id,
- CreateTime = terminalRecord.CreateTime,
- Creator = terminalRecord.CreatorUserId,
- UpdateTime = terminalRecord.UpdateTime < new DateTime(2000, 1, 1) ? terminalRecord.CreateTime : terminalRecord.UpdateTime,
- IsUploadReport = terminalRecordStateInfos.Count > 0,
- PatientInfo = new List<DataItemDTO>
- {
- new DataItemDTO{Key="Name",Value=$"{patientInfo.LastName} {patientInfo.FirstName}".Trim()},
- new DataItemDTO{Key="Phone",Value=patientInfo.Mobile},
- new DataItemDTO{Key="ID",Value=patientInfo.IdentityCardId},//设备病人ID
- new DataItemDTO{Key="Sex",Value = patientInfo.GenderType.ToString()=="Unassigned"?"NotFilled":patientInfo.GenderType.ToString()}
- }
- };
- if (patientInfo.Birthday != null && patientInfo.Birthday > new DateTime(1900, 1, 1))
- {
- remoteDiagnosisInfo.PatientInfo.Add(new DataItemDTO { Key = "Birthday", Value = ((DateTime)patientInfo.Birthday).ToString("yyyy-MM-dd") });
- }
- if (terminalRecord.AIDiagnosisInfos != null && terminalRecord.AIDiagnosisInfos.Any())
- {
- remoteDiagnosisInfo.AIDiagnosisInfos = terminalRecord.AIDiagnosisInfos.Select(x => new DiagnosisInfoDTO
- {
- DiagnosisOrgan = (WingInterfaceLibrary.Enum.DiagnosisOrganEnum)x.Organ,
- Conclusion = (WingInterfaceLibrary.Enum.DiagnosisConclusionEnum)x.Status,
- }).ToList();
- remoteDiagnosisInfo.DiagnosisStatus = DiagnosisStatusEnum.Completed;
- }
- syncBatchRemedicalRecordRequest.RemedicalRecordList.Add(remoteDiagnosisInfo);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalRecordInfos err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.RemedicalService.SyncBatchRemedicalRecordsAsync(syncBatchRemedicalRecordRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalRecordInfos err, ex:{ex}");
- }
- }
- public async Task MigrateRemedicalDatas(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer starting");
- //获取上次同步到的时间
- var builder = Builders<TerminalDatas>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var terminalDatas = _terminalDatasDBRepository.GetTerminalDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
- OnMigrate("Remote diagnosis datas", terminalDatas, SendRemedicalDatas, syncType,1000);
- terminalDatas.Clear();
- Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer successfully");
- }
- private void SendRemedicalDatas(IList<TerminalDatas> terminalDatas, SyncDBEnum syncType)
- {
- try
- {
- var builder = Builders<TerminalRecords>.Filter;
- var recordCodes = terminalDatas.Select(x => x.TerminalRecordId);
- var filter = builder.Where(x => x.IsDelete == false && recordCodes.Contains(x.Id));
- var records = _terminalRecordDBRepository.GetTerminalRecords(filter);
- var syncBatchRemedicalRecordRequest = new SyncBatchUploadRemedicalDatasRequest();
- syncBatchRemedicalRecordRequest.SyncType = syncType;
- syncBatchRemedicalRecordRequest.SyncUploadRemedicalDataList = new List<SyncUploadRemedicalDataRequest>();
- foreach (var terminalData in terminalDatas)
- {
- try
- {
- var record = records.FirstOrDefault(x => x.Id == terminalData.TerminalRecordId);
- var fileInfo = terminalData.Files.FirstOrDefault(f => f.ImageQuality == ImageQuality.High);
- var fileUrl = GetFileUrl(fileInfo?.FileName);
- var imageLocation = new ImageLocationDTO();
- if (terminalData.ImageLocation != null)
- {
- if (terminalData.ImageLocation is BreastImageLocation bi)
- {
- imageLocation = new ImageLocationDTO
- {
- Group = "BreastImageLocation",
- Position = bi.Position.ToString(),
- Quadrant = bi.Quadrant.ToString(),
- };
- }
- if (terminalData.ImageLocation is LiverImageLocation li)
- {
- imageLocation = new ImageLocationDTO
- {
- Group = "LiverImageLocation",
- Position = li.Position.ToString(),
- };
- }
- if (terminalData.ImageLocation is PositionImageLocation pi)
- {
- imageLocation = new ImageLocationDTO
- {
- Group = pi.Position,
- Position = pi.Position.ToString(),
- };
- }
- }
- var syncUploadRemedicalDataRequest = new SyncUploadRemedicalDataRequest
- {
- Code = terminalData.Id,
- CreateTime = terminalData.CreateTime,
- UpdateTime = terminalData.UpdateTime < new DateTime(2000, 1, 1) ? terminalData.CreateTime : terminalData.UpdateTime,
- ExamCode = terminalData.TerminalRecordId,
- FileDataType = (WingInterfaceLibrary.Enum.RemedicalFileDataTypeEnum)terminalData.DataType,
- FileToken = fileUrl,
- PreviewFileToken = GetFileUrl(terminalData.PreviewImageFileToken),
- Application = terminalData.Application,
- ImageLocation = imageLocation,
- DeviceCode = record?.Terminal?.Id
- };
- syncBatchRemedicalRecordRequest.SyncUploadRemedicalDataList.Add(syncUploadRemedicalDataRequest);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalDatas err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.RemedicalService.SyncBatchUploadRemedicalDatasAsync(syncBatchRemedicalRecordRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalDatas err, ex:{ex}");
- }
- }
- public async Task MigrateRemedicalAIDatas(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"Remote diagnosis ai datas migrate to wingServer starting");
- //获取上次同步到的时间
- //判断热数据
- var builder = Builders<TerminalAIDatas>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var terminalDatas = _terminalAIDatasDBRepository.GetTerminalAIDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
- OnMigrate("Remote diagnosis ai datas", terminalDatas, SendRemedicalAIDatas, syncType, 10);
- terminalDatas.Clear();
- Logger.WriteLineInfo($"Remote diagnosis datas migrate to wingServer successfully");
- }
- private void SendRemedicalAIDatas(IList<TerminalAIDatas> terminalAIDatas, SyncDBEnum syncType)
- {
- try
- {
- var syncBatchAIResultRequest = new SyncBatchAIResultRequest();
- syncBatchAIResultRequest.SyncType = syncType;
- syncBatchAIResultRequest.SyncAIResultList = new List<SyncAIResultRequest>();
- foreach (var terminalAIData in terminalAIDatas)
- {
- try
- {
- var syncAIResultRequest = new SyncAIResultRequest
- {
- RemedicalCode = terminalAIData.TerminalDataId,
- CreateTime = terminalAIData.CreateTime,
- UpdateTime = terminalAIData.UpdateTime < new DateTime(2000, 1, 1) ? terminalAIData.CreateTime : terminalAIData.UpdateTime,
- DiagnosisResult = JsonConvert.SerializeObject(terminalAIData.DiagResults),
- };
- syncBatchAIResultRequest.SyncAIResultList.Add(syncAIResultRequest);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalAIDatas err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.RemedicalService.SyncBatchAIResultAsync(syncBatchAIResultRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalAIDatas err, ex:{ex}");
- }
- }
- public async Task MigrateRemedicalCarotidDatas(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate to wingServer starting");
- //获取上次同步到的时间
- //判断热数据
- var builder = Builders<Carotid3dModelData>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x =>(x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var carotid3dModelDatas = _carotid3dModelDatasDBRepository.GetCarotid3dModelDatas(filter).OrderByDescending(x => x.CreateTime).ToList();
- OnMigrate("Remote diagnosis carotid datas", carotid3dModelDatas, SendRemedicalCarotidDatas, syncType, 100);
- carotid3dModelDatas.Clear();
- Logger.WriteLineInfo($"Remote diagnosis carotid datas migrate to wingServer successfully");
- }
- private void SendRemedicalCarotidDatas(IList<Carotid3dModelData> carotid3dModelDatas, SyncDBEnum syncType)
- {
- try
- {
- var syncBatchCarotidResultRequest = new SyncBatchCarotidResultRequest();
- syncBatchCarotidResultRequest.SyncType = syncType;
- syncBatchCarotidResultRequest.SyncCarotidResultRequest = new List<GetCarotidResultRequest>();
- foreach (var carotid3dModelData in carotid3dModelDatas)
- {
- try
- {
- var getCarotidResultRequest = new GetCarotidResultRequest
- {
- RemedicalCode = carotid3dModelData.ExamDataId,
- SurfaceToken = GetFileUrl(carotid3dModelData.SurfaceToken),
- MdlToken = GetFileUrl(carotid3dModelData.MdlToken),
- CarotidScanDirection = (CarotidScanDirectionEnum)carotid3dModelData.CarotidScanDirection,
- CarotidScanType = (CarotidScanTypeEnum)carotid3dModelData.CarotidScanType,
- MeasureImageFiles = new List<MeasureImageFileDTO>()
- };
- if (!string.IsNullOrWhiteSpace(carotid3dModelData.CarotidAIMeasureImageToken))
- {
- string[] keyValuePairs = carotid3dModelData.CarotidAIMeasureImageToken.Split(';');
- foreach (string keyValuePair in keyValuePairs)
- {
- string[] parts = keyValuePair.Split('=');
- if (parts.Length != 2) continue;
- if (Enum.TryParse(parts[0], out CarotidAIImageTypeEnum imageType))
- {
- string url = GetFileUrl(parts[1]);
- getCarotidResultRequest.MeasureImageFiles.Add(new MeasureImageFileDTO { ImageType = imageType, ImageFile = url });
- }
- }
- }
- getCarotidResultRequest.MeasureResult = carotid3dModelData.CarotidAIMeasureResult;
- syncBatchCarotidResultRequest.SyncCarotidResultRequest.Add(getCarotidResultRequest);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalCarotidDatas err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.RemedicalService.SyncBatchCarotidResultAsync(syncBatchCarotidResultRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalCarotidDatas err, ex:{ex}");
- }
- }
- public async Task MigrateConsultationResults(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"consultations migrate to wingServer starting");
- //获取上次同步到的时间
- var builder = Builders<ConsultationRecords>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => x.IsDeleted == false && ((x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime)));
- var consultations = _consultationRecordDBRepository.GetTerminalRecords(filter).OrderByDescending(x => x.CreateTime).ToList();
- OnMigrate("consultations", consultations, SendConsultations, syncType, 1000);
- consultations.Clear();
- Logger.WriteLineInfo($"consultations migrate to wingServer successfully");
- }
- private void SendConsultations(IList<ConsultationRecords> consultations, SyncDBEnum syncType)
- {
- try
- {
- var builder = Builders<FollowUpVisitInfos>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var followVistorList = _consultationRecordDBRepository.GetAllFollowUpVisitInfosRecords(filter).OrderByDescending(x => x.CreateTime).ToList();
- var evaluatesBuilder = Builders<ConsultationEvaluates>.Filter;
- var evaluatesFilter = evaluatesBuilder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var valuatesList = _consultationRecordDBRepository.GetAllConsultationEvaluatesRecords(evaluatesFilter).OrderByDescending(x => x.CreateTime).ToList();
-
- var syncBatchConsultationRequest = new SyncBatchConsultationRequest();
- syncBatchConsultationRequest.SyncType = syncType;
- syncBatchConsultationRequest.SyncConsultations = new List<SyncConsultationRequest>();
- foreach (var consultation in consultations)
- {
- try
- {
- if (consultation.TerminalInfo == null)
- {
- continue;
- }
- var patientInfo = consultation.PatientInfo;
- var syncReportInfoRequest = new SyncConsultationRequest
- {
- ConsultationCode = consultation.Id,
- CreateTime = consultation.CreateTime,
- UpdateTime = consultation.UpdateTime,
- ApplyOrganizationCode = consultation.PrimaryHosptial.Id,
- ApplyUserCode = consultation.DoctorInfo.ID,
- ExpertOrganizationCode = consultation.CentralHospital.Id,
- ExpertUserCode = consultation.ExpertInfo.ID,
- DeviceCode = consultation.TerminalInfo.Id,
- ScanUser = consultation.ScanDoctor,
- PatientInfo = new List<DataItemDTO>
- {
- new DataItemDTO{Key="Name",Value=patientInfo.Name},
- new DataItemDTO{Key="Phone",Value=patientInfo.ContactInfo},
- new DataItemDTO{Key="ID",Value=patientInfo.ID},//设备病人ID
- new DataItemDTO{Key="Sex",Value = patientInfo.GenderType.ToString()=="Unassigned"?"NotFilled":patientInfo.GenderType.ToString()},
- new DataItemDTO{Key="Anamnesis",Value=patientInfo.PastHistory},
- },
- ScanPosition = consultation.CheckPoint,
- ConsultationTime = consultation.AppointmentTime,
- ConsultationTimeEnd = consultation.AppointmentTime.AddHours(2),
- PrimaryDiagnosis = consultation.PatientInfo.Diagnosis,
- ConsultationStatus = GetStatusEnum(consultation.State),
- FollowUpVisitStatus = (FollowUpVisitStatusEnum)consultation.FollowUpVisitStatus,
- EvaluateGradeEnum = (EvaluateGradeEnum)consultation.EvaluateGrade,
- ConsultationFileList = new List<ConsultationFileDTO>()
- };
- if (valuatesList?.Count > 0)
- {
- var findEntity = valuatesList.OrderByDescending(c => c.CreateTime).FirstOrDefault(c => c.ConsultationRecordId == consultation.Id) ?? new ConsultationEvaluates();
- if (!string.IsNullOrEmpty(findEntity.Id))
- {
- syncReportInfoRequest.EvaluateGradeEnum = (EvaluateGradeEnum)findEntity.EvaluateGrade;
- }
- }
- //查询随访记录
- if (followVistorList?.Count > 0)
- {
- var findList = followVistorList.Where(c => c.ConsultationRecordId == consultation.Id)?.ToList();
- if (findList?.Count > 0)
- {
- var followUpVistorList = findList.Select(c => new SyncFollowUpVisitRequest()
- {
- IsDelete = c.IsDeleted,
- CreateTime = c.CreateTime,
- UpdateTime = c.UpdateTime,
- FollowUpVisitCode = c.Id,
- ConsultationRecordCode = c.ConsultationRecordId,
- PatientName = c.PatientName,
- PatientPhone = c.PatientPhone,
- GeneralCase = c.GeneralCase,
- ClinicalSituation = c.ClinicalSituation,
- DoctorCode = c.Doctor,
- OccurredTime = c.OccurredTime
- }).ToList();
- syncReportInfoRequest.SyncFollowUpVisitList = followUpVistorList;
- }
- }
- if (consultation.ImageTokens != null && consultation.ImageTokens.Any())
- {
- foreach (var item in consultation.ImageTokens)
- {
- var consultationFileDTO = new ConsultationFileDTO();
- consultationFileDTO.FileDataType = RemedicalFileDataTypeEnum.VinnoVidSingle;
- consultationFileDTO.SourceUrl = GetFileUrl(item);
- consultationFileDTO.PreviewImageUrl = ConvertToJpg(item);
- syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
- }
- }
- if (consultation.VideoTokens != null && consultation.VideoTokens.Any())
- {
- foreach (var item in consultation.VideoTokens)
- {
- var consultationFileDTO = new ConsultationFileDTO();
- consultationFileDTO.FileDataType = RemedicalFileDataTypeEnum.VinnoVidMovie;
- consultationFileDTO.SourceUrl = GetFileUrl(item.VideoToken);
- consultationFileDTO.PreviewImageUrl = ConvertToJpg(item.PreviewImageToken);
- syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
- }
- }
- if (consultation.GraphicData != null && consultation.GraphicData.Any())
- {
- foreach (var item in consultation.GraphicData)
- {
- var consultationFileDTO = new ConsultationFileDTO();
- consultationFileDTO.FileDataType = item.GraphicType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie;
- consultationFileDTO.SourceUrl = GetFileUrl(item.GraphicToken);
- consultationFileDTO.PreviewImageUrl = ConvertToJpg(item.PreviewGraphicToken);
- consultationFileDTO.CreateTime = (consultation.UpdateTime <= DateTime.MinValue ? consultation.CreateTime : consultation.UpdateTime);
- syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
- }
- }
- if (consultation.PreFileItems != null && consultation.PreFileItems.Any())
- {
- foreach (var item in consultation.PreFileItems)
- {
- var consultationFileDTO = new ConsultationFileDTO();
- consultationFileDTO.FileDataType = item.FileType == 0 ? RemedicalFileDataTypeEnum.ThirdVidSingle : RemedicalFileDataTypeEnum.ThirdVidMovie;
- consultationFileDTO.SourceUrl = GetFileUrl(item.OriginalFileUrl);
- consultationFileDTO.PreviewImageUrl = ConvertToJpg(item.ThumbnailUrl);
- syncReportInfoRequest.ConsultationFileList.Add(consultationFileDTO);
- }
- }
- syncBatchConsultationRequest.SyncConsultations.Add(syncReportInfoRequest);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendConsultations err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.LiveConsultationService.SyncBatchConsultationAsync(syncBatchConsultationRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendConsultations err, ex:{ex}");
- }
- }
- private TransactionStatusEnum GetStatusEnum(Entities.ConsultationState state)
- {
- TransactionStatusEnum transactionStatusEnum = TransactionStatusEnum.Applied;
- switch (state)
- {
- case Entities.ConsultationState.Unhandled:
- transactionStatusEnum = TransactionStatusEnum.Applied;
- break;
- case Entities.ConsultationState.Withdrawn:
- transactionStatusEnum = TransactionStatusEnum.Withdrawn;
- break;
- case Entities.ConsultationState.Handled:
- transactionStatusEnum = TransactionStatusEnum.ToStart;
- break;
- case Entities.ConsultationState.Started:
- transactionStatusEnum = TransactionStatusEnum.InProgress;
- break;
- case Entities.ConsultationState.WaitForReportUpload:
- transactionStatusEnum = TransactionStatusEnum.PendingReport;
- break;
- case Entities.ConsultationState.ReportUploading:
- transactionStatusEnum = TransactionStatusEnum.PendingReport;
- break;
- case Entities.ConsultationState.ReportUploaded:
- transactionStatusEnum = TransactionStatusEnum.End;
- break;
- case Entities.ConsultationState.ReportUploadFailed:
- transactionStatusEnum = TransactionStatusEnum.PendingReport;
- break;
- case Entities.ConsultationState.Expired:
- transactionStatusEnum = TransactionStatusEnum.End;
- break;
- case Entities.ConsultationState.Qualified:
- transactionStatusEnum = TransactionStatusEnum.End;
- break;
- case Entities.ConsultationState.UnQualified:
- transactionStatusEnum = TransactionStatusEnum.End;
- break;
- default:
- break;
- }
- return transactionStatusEnum;
- }
- public async Task MigrateReportInfoResults(SyncDBEnum syncType)
- {
- Logger.WriteLineInfo($"ReportInfoResults migrate to wingServer starting");
- //获取上次同步到的时间
- var builder = Builders<ReportInfoResults>.Filter;
- var startTime = GetFactBeginTime(_migrateRecord.StartTime, _migrateRecord.EndTime);
- var filter = builder.Where(x => (x.CreateTime > startTime && x.CreateTime <= _migrateRecord.EndTime) || (x.UpdateTime > startTime && x.UpdateTime <= _migrateRecord.EndTime));
- var reportInfoResults = _reportInfoResultDBRepository.GetReports(filter).OrderByDescending(x => x.CreateTime).ToList();
- OnMigrate("reportInfoResults", reportInfoResults, SendRemedicalreportInfoResults, syncType, 1000);
- reportInfoResults.Clear();
- Logger.WriteLineInfo($"reportInfoResults migrate to wingServer successfully");
- }
- private void SendRemedicalreportInfoResults(IList<ReportInfoResults> reportInfoResults, SyncDBEnum syncType)
- {
- try
- {
- var syncBatchReportInfoRequest = new SyncBatchReportInfoRequest();
- syncBatchReportInfoRequest.SyncType = syncType;
- syncBatchReportInfoRequest.SyncReportInfos = new List<SyncReportInfoRequest>();
- foreach (var reportInfoResult in reportInfoResults)
- {
- try
- {
- var diagnosisLabels = new List<string>();
- var reportUserCode = "";
- var isAI = false;
- if (reportInfoResult?.User?.Name == "AI")
- {
- diagnosisLabels = new List<string> { "VAid" };
- isAI = true;
- }
- else
- {
- reportUserCode = reportInfoResult.User._id;
- }
- var syncReportInfoRequest = new SyncReportInfoRequest
- {
- ReportCode = reportInfoResult.Id,
- CreateTime = reportInfoResult.CreateTime,
- UpdateTime = reportInfoResult.UpdateTime,
- RecordCode = reportInfoResult.RecordId,
- ReportTemplateJson = reportInfoResult.Template,
- ReportDatasJson = ReportElementsSerializer.ConvertReportElementsToJson(isAI, reportInfoResult.Template, reportInfoResult.ElementCollection),
- ReportPreviewList = new List<ReportPreviewDTO>(),
- ReportOrgan = (DiagnosisOrganEnum)reportInfoResult.Organ,
- DiagnosisLabels = diagnosisLabels,
- ReportUserCode = reportUserCode
- };
- if (reportInfoResult.PreviewImages != null && reportInfoResult.PreviewImages.Count > 0)
- {
- foreach (var item in reportInfoResult.PreviewImages)
- {
- var reportPreviewDTO = new ReportPreviewDTO();
- reportPreviewDTO.FileToken = GetFileUrl(item.Name);
- reportPreviewDTO.FileType = UploadFileTypeEnum.JPG;
- syncReportInfoRequest.ReportPreviewList.Add(reportPreviewDTO);
- }
- }
- syncBatchReportInfoRequest.SyncReportInfos.Add(syncReportInfoRequest);
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalreportInfoResults err, ex:{ex}");
- }
- }
- var result = _jsonRpcProxy.ReportService.SyncBatchReportInfoAsync(syncBatchReportInfoRequest).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"SendRemedicalreportInfoResults err, ex:{ex}");
- }
- }
- private string GetFileUrl(string fileUrl)
- {
- var prefix = "1!U$";
- if (!string.IsNullOrWhiteSpace(fileUrl) && fileUrl.StartsWith(prefix))
- {
- return fileUrl.Replace(prefix, "");
- }
- return fileUrl ?? string.Empty;
- }
- private string ConvertToJpg(string oldFileToken)
- {
- try
- {
- var prefix = "1!U$";
- if (!string.IsNullOrWhiteSpace(oldFileToken) && oldFileToken.StartsWith(prefix))
- {
- var fileUrl = oldFileToken.Replace(prefix, "");
- var localPath = DownloadAsync(fileUrl, $"{Guid.NewGuid():N}.jpg").Result;
- if (!string.IsNullOrWhiteSpace(localPath))
- {
- var newUrl = UploadAsync(localPath).Result;
- if (!string.IsNullOrWhiteSpace(newUrl))
- {
- return newUrl;
- }
- }
- }
- return oldFileToken;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"ConvertToJpg err, ex:{ex}");
- return oldFileToken;
- }
- }
- private OrganizationView MapToOrganizationView(IList<Organizations> organizations, string? hospitalId)
- {
- var hospital = organizations.FirstOrDefault(x => x.Id == hospitalId);
- if (hospital != null)
- {
- return new OrganizationView
- {
- Code = hospital.Id,
- Name = hospital.Name,
- Description = hospital.Description,
- CountryCode = hospital.Country?.Id,
- CountryName = hospital.Country?.Name,
- ProvinceCode = hospital.Province?.Id,
- ProvinceName = hospital.Province?.Name,
- CityCode = hospital.City?.Id,
- CityName = hospital.City?.Name,
- };
- }
- return null;
- }
- private UserView MapToUserView(IList<Organizations> organizations, IList<Users> users, string? userId)
- {
- var user = users.FirstOrDefault(x => x._id == userId);
- if (user != null)
- {
- var hospital = organizations.FirstOrDefault(x => x.Id == user.HospitalId);
- var name = !string.IsNullOrWhiteSpace(user.FullName) ? user.FullName
- : !string.IsNullOrWhiteSpace(user.LastName) ? user.LastName
- : !string.IsNullOrWhiteSpace(user.FirstName) ? user.FirstName
- : !string.IsNullOrWhiteSpace(user.NickName) ? user.NickName
- : user.Name;
- return new UserView
- {
- Code = user._id,
- Name = name,
- OrganizationCode = user.HospitalId,
- OrganizationName = hospital?.Name,
- };
- }
- return null;
- }
- private DeviceView MapToDeviceView(IList<Terminals> terminals, string? terminalId)
- {
- var terminal = terminals.FirstOrDefault(x => x.Id == terminalId);
- if (terminal != null)
- {
- return new DeviceView
- {
- Code = terminal.Id,
- Name = terminal.Name,
- Description = terminal.Description,
- UniqueCode = terminal.UniquedId,
- DeviceType = terminal.IsSonopost ? "sonopost" : "US",
- DeviceModel = terminal.Model,
- OrganizationCode = terminal.Organization?.Id,
- OrganizationName = terminal.Organization?.Name,
- };
- }
- return null;
- }
- private GroupView MapToUserGroupView(IList<UserGroup> userGroups, string? userGroupId)
- {
- var userGroup = userGroups.FirstOrDefault(x => x.Id == userGroupId);
- if (userGroup != null)
- {
- return new GroupView
- {
- Code = userGroup.Id,
- Name = userGroup.Name,
- };
- }
- return null;
- }
- private ClassView MapToClassView(IList<UltrasonicClass> classes, string? classId)
- {
- var classInfo = classes.FirstOrDefault(x => x.Id == classId);
- if (classInfo != null)
- {
- return new ClassView
- {
- Code = classInfo.Id,
- Name = classInfo.Name,
- };
- }
- return null;
- }
- private List<DiagnosisOrganEnum> GetDiagnosisOrgans(List<AIDiagnosisPerImg> results)
- {
- var diagnosisOrgans = new List<DiagnosisOrganEnum>();
- foreach (var imageResult in results)
- {
- foreach (var diagnosisResult in imageResult.DiagResultsForEachOrgan)
- {
- var organName = Enum.GetName(typeof(DiagnosisOrganEnum), (int)diagnosisResult.Organ);
- if (!string.IsNullOrWhiteSpace(organName) && diagnosisResult.Organ != EnumOrgans.Null && diagnosisResult.DetectedObjects?.Any() == true)
- {
- diagnosisOrgans.Add((DiagnosisOrganEnum)diagnosisResult.Organ);
- }
- }
- }
- return diagnosisOrgans.Distinct().ToList();
- }
- private DiagnosisConclusionEnum GetDiagnosisConclusion(List<AIDiagnosisPerImg> results)
- {
- var diagnosisConclusions = new List<DiagnosisConclusionEnum>();
- foreach (var imageResult in results)
- {
- foreach (var diagnosisResult in imageResult.DiagResultsForEachOrgan)
- {
- var benignLabels = new List<int>();
- var malignantLabels = new List<int>();
- if (diagnosisResult.Organ == EnumOrgans.Breast)
- {
- benignLabels = new List<int> { 1, 2, 3 };
- malignantLabels = new List<int> { 4, 5, 6, 7 };
- }
- else if (diagnosisResult.Organ == EnumOrgans.Liver)
- {
- benignLabels = new List<int> { 1, 2, 3, 5, 6, 7, 8 };
- malignantLabels = new List<int> { 4 };
- }
- else if (diagnosisResult.Organ == EnumOrgans.Thyroid)
- {
- benignLabels = new List<int> { 1, 2, 7 };
- malignantLabels = new List<int> { 3, 4, 5, 6 };
- }
- var labels = diagnosisResult.DetectedObjects.Select(x => x.Label);
- if (labels.Contains(0))
- {
- diagnosisConclusions.Add(DiagnosisConclusionEnum.NoObviousLesion);
- }
- if (labels.Intersect(benignLabels).Any())
- {
- diagnosisConclusions.Add(DiagnosisConclusionEnum.Benign);
- }
- if (labels.Intersect(malignantLabels).Any())
- {
- diagnosisConclusions.Add(DiagnosisConclusionEnum.Malignant);
- }
- }
- }
- var containsBenign = diagnosisConclusions.Contains(DiagnosisConclusionEnum.Benign);
- var containsMalignant = diagnosisConclusions.Contains(DiagnosisConclusionEnum.Malignant);
- var containsNoObviousLesion = diagnosisConclusions.Contains(DiagnosisConclusionEnum.NoObviousLesion);
- if (containsBenign && containsMalignant)
- {
- return DiagnosisConclusionEnum.BenignAndMalignant;
- }
- else if (containsBenign)
- {
- return DiagnosisConclusionEnum.Benign;
- }
- else if (containsMalignant)
- {
- return DiagnosisConclusionEnum.Malignant;
- }
- else if (containsNoObviousLesion)
- {
- return DiagnosisConclusionEnum.NoObviousLesion;
- }
- else
- {
- return DiagnosisConclusionEnum.Unrecognized;
- }
- }
- /// <summary>下载文件</summary>
- /// <param name="fileUrl"></param>
- /// <returns></returns>
- private async Task<string> DownloadAsync(string fileUrl, string fileNameAndExtension = "")
- {
- try
- {
- if (string.IsNullOrEmpty(fileUrl))
- {
- return string.Empty;
- }
- if (!Directory.Exists(_tempFolder))
- {
- Directory.CreateDirectory(_tempFolder);
- }
- var fileName = Path.GetFileName(fileUrl);
- if (!string.IsNullOrWhiteSpace(fileNameAndExtension))
- {
- fileName = fileNameAndExtension;
- }
- var tempFile = Path.Combine(_tempFolder, fileName);
- if (File.Exists(tempFile))
- {
- return tempFile;
- }
- long fileSize = 0;
- using (var request = new HttpRequestMessage())
- {
- request.RequestUri = new Uri(fileUrl);
- request.Method = HttpMethod.Get;
- var response = await _httpClient.SendAsync(request);
- if (response != null && response.StatusCode == HttpStatusCode.OK)
- {
- var contentLength = response.Content.Headers.ContentLength;
- fileSize = contentLength == null ? 0 : contentLength.Value;
- }
- }
- if (fileSize <= 0)
- {
- throw new NotSupportedException($"fileSize is {fileSize}");
- }
- byte[] bytes = await _httpClient.GetByteArrayAsync(fileUrl);
- File.WriteAllBytes(tempFile, bytes);
- return tempFile;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"MigrateService download file err, url: {fileUrl}, {ex}");
- }
- finally
- {
- //Logger.WriteLineInfo($"download file:{fileUrl}");
- }
- return string.Empty;
- }
- private async Task<string> UploadAsync(string localPath)
- {
- var authorizationResult = await _jsonRpcProxy.Storage.GetAuthorizationAsync(new FileServiceRequest
- {
- Token = DefaultToken,
- FileName = Path.GetFileName(localPath),
- IsRechristen = true,
- });
- var fileUrl = authorizationResult.StorageUrl;
- using (var fileStream = new FileStream(localPath, FileMode.Open))
- {
- var size = fileStream.Length;
- byte[] buffer = new byte[fileStream.Length];
- fileStream.Read(buffer, 0, buffer.Length);
- var requestHeads = new Dictionary<string, string>();
- requestHeads.Add("Authorization", authorizationResult.Authorization);
- using (var request = new HttpRequestMessage())
- {
- var fileExtension = Path.GetExtension(localPath);
- var mimeType = FileHelper.GetMimeType(fileExtension);
- var contentType = MediaTypeHeaderValue.Parse(mimeType);
- using (UploadContent content = new UploadContent(buffer, contentType))
- {
- request.RequestUri = new Uri(fileUrl);
- request.Method = HttpMethod.Put;
- request.Content = content;
- foreach (var head in requestHeads)
- {
- request.Headers.TryAddWithoutValidation(head.Key, head.Value);
- }
- var result = await ExecuteRequest(request);
- if (result)
- {
- return fileUrl;
- }
- }
- }
- }
- return null;
- }
- /// <summary>
- /// 执行请求
- /// </summary>
- /// <param name="httpRequestMessage"></param>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- private async Task<bool> ExecuteRequest(HttpRequestMessage httpRequestMessage)
- {
- try
- {
- var response = await _httpClient.SendAsync(httpRequestMessage);
- if (response != null && response.StatusCode == HttpStatusCode.OK)
- {
- return true;
- }
- return false;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 获取实际时间
- /// </summary>
- /// <param name="beginTime"></param>
- /// <param name="endTime"></param>
- /// <returns></returns>
- private DateTime GetFactBeginTime(DateTime beginTime, DateTime endTime)
- {
- var dateDiff = endTime - beginTime;
- if (dateDiff.TotalDays > 365)
- {
- beginTime = endTime.AddYears(-1);
- }
- return beginTime;
- }
- }
- public class AIDiagnosisPerImg
- {
- /// <summary>
- /// Index
- /// </summary>
- public int Index { get; set; }
- /// <summary>
- /// Priority Score
- /// </summary>
- public float PriorityScore { get; set; }
- /// <summary>
- /// DiagResults of each Organ
- /// </summary>
- public IList<AIDiagResultPerOrganForDB> DiagResultsForEachOrgan { get; set; }
- }
- public class UploadContent : HttpContent
- {
- private const int ChunkSize = 2097152;//2M;
- private readonly Stream _uploadStream;
- private readonly long _fileSize;
- public event EventHandler<double> ProgressChanged;
- public UploadContent(string filePath)
- {
- if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
- {
- throw new Exception("UploadFile not find");
- }
- var fileName = Path.GetFileName(filePath);
- _uploadStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
- var mimeType = FileHelper.GetMimeType(fileName.Substring(fileName.LastIndexOf(".")));
- Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
- Headers.ContentLength = _uploadStream.Length;
- _fileSize = _uploadStream.Length;
- }
- public UploadContent(byte[] fileData, MediaTypeHeaderValue mediaTypeHeaderValue)
- {
- if (fileData == null || fileData.Length == 0)
- {
- throw new Exception("FileData is empty");
- }
- _uploadStream = new MemoryStream(fileData);
- Headers.ContentType = mediaTypeHeaderValue;
- Headers.ContentLength = _uploadStream.Length;
- _fileSize = _uploadStream.Length;
- }
- /// <summary>
- /// 将内容写入流
- /// </summary>
- /// <param name="stream"></param>
- /// <param name="context"></param>
- /// <returns></returns>
- protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
- {
- for (long i = 0; i < _uploadStream.Length; i += ChunkSize)
- {
- var dataToWrite = new byte[Math.Min(ChunkSize, _uploadStream.Length - i)];
- await _uploadStream.ReadAsync(dataToWrite, 0, dataToWrite.Length);
- await stream.WriteAsync(dataToWrite, 0, dataToWrite.Length);
- OnProgressChanged((double)(i * 100 / _uploadStream.Length));
- }
- OnProgressChanged(100);
- }
- /// <summary>
- /// 比较文件大小
- /// </summary>
- /// <returns></returns>
- public bool CompareFileSizes(long webFileSize)
- {
- return _fileSize == webFileSize;
- }
- protected override bool TryComputeLength(out long length)
- {
- length = _uploadStream.Length;
- return true;
- }
- private void OnProgressChanged(double e)
- {
- ProgressChanged?.Invoke(this, e);
- }
- public new void Dispose()
- {
- base.Dispose();
- _uploadStream.Close();
- ProgressChanged = null;
- }
- }
- }
|