123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429 |
- using Newtonsoft.Json;
- using Newtonsoft.Json.Converters;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using Vinno.IUS.Common.Log;
- using Vinno.vCloud.Common.FIS.Helper;
- using Vinno.vCloud.FIS.CrossPlatform.Common.Helper;
- using Vinno.vCloud.Report.Interfaces;
- using Vinno.vCloud.Report.JsonConverters;
- using Vinno.vCloud.Report.Models;
- using WingInterfaceLibrary.Interface;
- using WingInterfaceLibrary.Request.Examine;
- using WingInterfaceLibrary.Request.Report;
- using WingInterfaceLibrary.Request.Storage;
- using WingInterfaceLibrary.ResearchEdition;
- using WingInterfaceLibrary.Result.Examine;
- namespace Vinno.vCloud.Common.FIS.Remedicals
- {
- public class ReportData : IDisposable
- {
- private readonly IStorageService _storageService;
- private readonly IReportService _reportService;
- private readonly IRemedicalService _remedicalService;
- private string _token;
- private UploadStatus _status;
- private Action<ExamPairInfo> _updateExamPairCache;
- private Action<ExamPairInfo, string> _updateExamPairCacheForResearch;
- private Func<string, ResearchProjectDTO> _getResearchProjectDTO;
- /// <summary>
- /// Id
- /// </summary>
- public string Id { get; }
- /// <summary>
- /// 云端病人Id
- /// </summary>
- public string PatientIdInServer { get; set; }
- /// <summary>
- /// 云端检查Id
- /// </summary>
- public string ExamIdInServer { get; set; }
- /// <summary>
- /// 报告信息
- /// </summary>
- public ReportInfoDTO ReportInfo { get; set; }
- /// <summary>
- /// 报告Pdf文件路径
- /// </summary>
- public string PdfFilePath { get; set; }
- /// <summary>
- /// 报告Json文件路径
- /// </summary>
- public string JsonFilePath { get; set; }
- public UploadStatus Status
- {
- get
- {
- return _status;
- }
- private set
- {
- if (_status != value)
- {
- _status = value;
- StatusChanged?.Invoke(this, Status);
- }
- }
- }
- public event EventHandler<UploadStatus> StatusChanged;
- public override string ToString()
- {
- return $"ReportInfoDTO Id:{Id},PatientId:{ReportInfo?.PatientId},ExamId:{ReportInfo?.ExamId},ReportId:{ReportInfo?.ReportId},PdfPath:{PdfFilePath},JsonPath:{JsonFilePath},Organ:{ReportInfo?.Organ},LanguageCode:{ReportInfo?.LanguageCode}";
- }
- public ReportData(string patientIdInServer, string examIdInServer, ReportInfoDTO reportInfo, IRemedicalService remedicalService, IStorageService storageService, IReportService reportService, string token, Action<ExamPairInfo> updateExamRecordCache, Action<ExamPairInfo, string> updateExamPairCacheForResearch, Func<string, ResearchProjectDTO> getResearchProjectDTO)
- {
- try
- {
- _remedicalService = remedicalService;
- _storageService = storageService;
- _reportService = reportService;
- _token = token;
- Id = "Report-" + Guid.NewGuid().ToString("N").ToUpper();
- PatientIdInServer = patientIdInServer;
- ExamIdInServer = examIdInServer;
- ReportInfo = reportInfo;
- _updateExamPairCache = updateExamRecordCache;
- _updateExamPairCacheForResearch = updateExamPairCacheForResearch;
- _getResearchProjectDTO = getResearchProjectDTO;
- if (ReportInfo == null)
- {
- throw new ArgumentNullException();
- }
- if (File.Exists(ReportInfo?.PdfFilePath))
- {
- var extension = Path.GetExtension(ReportInfo?.PdfFilePath);
- var filePath = Path.Combine(GetWorkingFolder(), $"{Id}{extension}");
- FileHelper.CopyFile(ReportInfo?.PdfFilePath, filePath, true);
- PdfFilePath = filePath;
- }
- else
- {
- PdfFilePath = null;
- }
- if (File.Exists(ReportInfo?.JsonFilePath))
- {
- var extension = Path.GetExtension(ReportInfo?.JsonFilePath);
- var filePath = Path.Combine(GetWorkingFolder(), $"{Id}{extension}");
- FileHelper.CopyFile(ReportInfo?.JsonFilePath, filePath, true);
- JsonFilePath = filePath;
- }
- else
- {
- JsonFilePath = null;
- }
- Status = UploadStatus.Idle;
- Logger.WriteLineInfo(ToString());
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"ReportData {ToString()} Cstor Error:{ex}");
- }
- }
- private string GetWorkingFolder()
- {
- var folder = Path.Combine(vCloudTerminalV2.WorkingFolder, "ReportUploadCache");
- DirectoryHelper.CreateDirectory(folder);
- return folder;
- }
- internal void UpdateStatus(UploadStatus status)
- {
- Status = status;
- }
- public void Dispose()
- {
- try
- {
- FileHelper.DeleteFile(JsonFilePath);
- FileHelper.DeleteFile(PdfFilePath);
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"ReportData {ToString()} Dispose Error:{ex}");
- }
- }
- internal void Upload(CancellationTokenSource cancellationTokenSource)
- {
- var document = RepportDeserializeHelper.DeserializeReport(JsonFilePath);
- if (document == null)
- {
- throw new InvalidDataException($"Report Deserialize Fail!");
- }
- if (string.IsNullOrWhiteSpace(ReportInfo.ReportId))
- {
- ReportInfo.ReportId = document.Id;
- }
- var settings = new JsonSerializerSettings
- {
- ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
- Converters =
- new List<JsonConverter>
- {
- new StringEnumConverter(),
- new ReadOnlyCellDictionaryJsonConverter(),
- #pragma warning disable 612
- new ElementValueDictionaryJsonConverter(),
- #pragma warning restore 612
- new ElementValueJsonConverter(),
- new DictionaryJsonConverter<MeasureTag, TextElementValue>(),
- new DictionaryJsonConverter<ElementTag, Dictionary<MeasureTag, TextElementValue>>(),
- }
- };
- var templatestring = JsonConvert.SerializeObject(document.Template, Formatting.None, settings);
- string elementValueString = SerializeElementValue(document, settings);
- string measureElementValueString = SerializeMeasureElementValue(document, settings);
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- string pdfUrl = null;
- if (File.Exists(PdfFilePath))
- {
- pdfUrl = UploadPdf(cancellationTokenSource);
- if (string.IsNullOrWhiteSpace(pdfUrl))
- {
- throw new InvalidOperationException("Get url failed when Uploading pdf file");
- }
- }
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var saveUltrasonicReportRequest = new SaveUltrasonicReportRequest
- {
- Token = _token,
- DeviceExamId = ReportInfo.ExamId,
- DeviceReportId = ReportInfo.ReportId,
- ReportType = ReportInfo.ReportType,
- ReportTemplateJson = templatestring,
- ReportDatasJson = elementValueString,
- ReportMeasureDatasJson = measureElementValueString,
- ReportPDFUrl = pdfUrl,
- LanguageCode = ReportInfo.LanguageCode,
- ReportOrgan = ReportInfo.Organ,
- };
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var result = JsonRpcHelper.SaveUltrasonicReport(_reportService, saveUltrasonicReportRequest);
- if (result == null)
- {
- throw new InvalidDataException($"JsonRPCHelper SaveUltrasonicReport Result is null");
- }
- else if (result.IsSuccess)
- {
- Status = UploadStatus.Uploaded;
- return;
- }
- else if (!result.IsSuccess)
- {
- if (result.ErrorCode == 4016)//云端没有找到对应的检查
- {
- if (CreateExamRecord(out var examRecordId, out var patientIdInServer))
- {
- PatientIdInServer = patientIdInServer;
- var examPairInfo = new ExamPairInfo(ReportInfo.ExamId, ReportInfo.PatientId, examRecordId, patientIdInServer);
- if (string.IsNullOrEmpty(ReportInfo.ProjectCode))
- {
- _updateExamPairCache(examPairInfo);
- }
- else
- {
- _updateExamPairCacheForResearch(examPairInfo, ReportInfo.ProjectCode);
- }
- result = JsonRpcHelper.SaveUltrasonicReport(_reportService, saveUltrasonicReportRequest);
- if (result == null)
- {
- throw new InvalidDataException($"JsonRPCHelper SaveUltrasonicReport Result is null");
- }
- else if (result.IsSuccess)
- {
- Status = UploadStatus.Uploaded;
- return;
- }
- else
- {
- throw new InvalidDataException($"JsonRPCHelper SaveUltrasonicReport Fail,Error Code is {result.ErrorCode}");
- }
- }
- else
- {
- throw new InvalidDataException($"JsonRPCHelper SaveUltrasonicReport Fail:CreateExamRecord Result is false");
- }
- }
- }
- Status = UploadStatus.Fail;
- }
- private static string SerializeElementValue(ReportInfo document, JsonSerializerSettings settings)
- {
- var elementValuesList = new List<ReportDataItemDTO>();
- foreach (var elementValue in document.ElementValues)
- {
- var tagId = elementValue.Key.Id;
- var name = elementValue.Key.Name;
- var value = JsonConvert.SerializeObject(elementValue.Value, Formatting.None, settings);
- var key = "";
- foreach (var block in document.Template.Blocks)
- {
- var elment = block.Elements.FirstOrDefault(x => x.Tag?.Id == elementValue.Key.Id);
- if (elment != null)
- {
- key = elment.Id;
- break;
- }
- }
- elementValuesList.Add(new ReportDataItemDTO()
- {
- TagId = tagId,
- Value = value,
- Name = name,
- Key = key,
- });
- }
- var elementValueString = JsonConvert.SerializeObject(elementValuesList, Formatting.None, settings);
- return elementValueString;
- }
- private static string SerializeMeasureElementValue(ReportInfo document, JsonSerializerSettings settings)
- {
- var measureElementValuesList = new List<ReportDataItemDTO>();
- foreach (var measureElementValue in document.MeasureElementValues)
- {
- var tagId = measureElementValue.Key.Id;
- var name = measureElementValue.Key.Name;
- var key = "";
- var value = JsonConvert.SerializeObject(measureElementValue.Value, Formatting.None, settings);
- foreach (var block in document.Template.Blocks)
- {
- var elment = block.Elements.FirstOrDefault(x => x.Tag?.Id == measureElementValue.Key.Id);
- if (elment != null)
- {
- key = elment.Id;
- break;
- }
- }
- measureElementValuesList.Add(new ReportDataItemDTO()
- {
- TagId = tagId,
- Value = value,
- Name = name,
- Key = key,
- });
- }
- var measureElementValueString = JsonConvert.SerializeObject(measureElementValuesList, Formatting.None, settings);
- return measureElementValueString;
- }
- /// <inheritdoc />
- /// <summary>
- /// Create an exam record from vCloud.
- /// </summary>
- /// <param name="examId">The local excam id.</param>
- /// <param name="workOrderId">The workerId</param>
- /// <param name="patientInfo">The patient basic info for creating the exam record.</param>
- /// <returns><see cref="T:Vinno.vCloud.Terminal.Remedicals.IvCloudExamRecord" /></returns>
- private bool CreateExamRecord(out string examRecordId, out string patientIdInServer)
- {
- var patientType = vCloudServerConfig.Instance.PatientType;
- if (!string.IsNullOrEmpty(ReportInfo.ProjectCode))
- {
- var researchProjectDTO = _getResearchProjectDTO.Invoke(ReportInfo.ProjectCode);
- if (researchProjectDTO != null)
- {
- patientType = researchProjectDTO.PatientType;
- }
- else
- {
- examRecordId = string.Empty;
- patientIdInServer = string.Empty;
- Logger.WriteLineError($"GetResearchProjectDTO Fail,ProjectCode:{ReportInfo.ProjectCode}");
- return false;
- }
- }
- var createExaminfoRequest = new CreateExaminfoRequest
- {
- Token = _token,
- PatientType = patientType.ToString(),
- ExamRecordCode = null,
- PatientInfo = DTOConverter.RenderPatientInfo(ReportInfo.PatientInfo, ReportInfo.ExamId, patientType),
- PatientScanInfoList = DTOConverter.RenderPatientScanInfo(ReportInfo.PatientInfo),
- IsScreenshotVersion = false,
- PatientCode = PatientIdInServer,
- ExamTime = ReportInfo.PatientInfo.ExamTime,
- ProjectCode = ReportInfo.ProjectCode,
- };
- CreateExaminfoResult result = JsonRpcHelper.CreateExamInfo(_remedicalService, createExaminfoRequest);
- if (result == null || string.IsNullOrEmpty(result.ExamCode))
- {
- examRecordId = string.Empty;
- patientIdInServer = string.Empty;
- return false;
- }
- else
- {
- examRecordId = result.ExamCode;
- patientIdInServer = result.PatientCode;
- return true;
- }
- }
- private string UploadPdf(CancellationTokenSource cancellationTokenSource)
- {
- try
- {
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- var fileName = Path.GetFileName(PdfFilePath);
- var fileServiceRequest = new FileServiceRequest
- {
- FileName = fileName,
- IsRechristen = true,
- Token = _token,
- };
- var authorizationInfo = JsonRpcHelper.GetAuthorization(_storageService, fileServiceRequest);
- if (authorizationInfo == null)
- {
- throw new Exception("GetAuthorization Error,AuthorizationInfo is null ");
- }
- var uploadResult = UploadFileHelper.UploadFile(authorizationInfo.StorageUrl, PdfFilePath, authorizationInfo.ContentType, authorizationInfo.Authorization, null, cancellationTokenSource);
- if (cancellationTokenSource.IsCancellationRequested)
- {
- throw new OperationCanceledException("Cancelled");
- }
- if (uploadResult?.Item1 == true)
- {
- return authorizationInfo.StorageUrl;
- }
- else
- {
- return string.Empty;
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Upload Report Pdf File Error:{ex}");
- return string.Empty;
- }
- }
- }
- }
|