DeviceService.cs 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using WingInterfaceLibrary.DTO.Device;
  6. using WingInterfaceLibrary.Interface;
  7. using WingInterfaceLibrary.Request.Device;
  8. using WingInterfaceLibrary.DTO.Dictionary;
  9. using WingServerCommon.Log;
  10. using WingServerCommon.Service;
  11. using WingInterfaceLibrary.Interface.DBInterface;
  12. using WingInterfaceLibrary.DB.Request;
  13. using WingServerCommon.Mapper;
  14. using WingInterfaceLibrary.Request;
  15. using WingInterfaceLibrary.Request.Authentication;
  16. using WingInterfaceLibrary.DTO.User;
  17. using WingInterfaceLibrary.DTO.Management;
  18. using WingServerCommon.Config;
  19. using WingDeviceService.Common;
  20. using WingInterfaceLibrary.Request.User;
  21. using WingInterfaceLibrary.Enum;
  22. using WingInterfaceLibrary.DTO.Organization;
  23. using WingInterfaceLibrary.DTO.DiagnosisModule;
  24. using WingServerCommon.Config.Parameters;
  25. using WingServerCommon.Interfaces.Cache;
  26. using WingInterfaceLibrary.LiveConsultation;
  27. using WingInterfaceLibrary.Result.Languge;
  28. using WingInterfaceLibrary.Internal.Interface;
  29. using WingInterfaceLibrary.Notifications;
  30. using WingInterfaceLibrary.Internal.Request;
  31. using WingInterfaceLibrary.Rtc;
  32. using WingInterfaceLibrary.Notifications.Live;
  33. using WingInterfaceLibrary.Enum.NotificationEnum;
  34. using WingInterfaceLibrary.Request.DBRequest;
  35. using WingInterfaceLibrary.DTO.Record;
  36. using WingInterfaceLibrary.DTO.Consultation;
  37. using System.Collections.Concurrent;
  38. using WingInterfaceLibrary.DTO.LiveRoom;
  39. using WingInterfaceLibrary.Result;
  40. using System.Threading.Tasks.Dataflow;
  41. using WingServerCommon.Utilities.Executors;
  42. using WingInterfaceLibrary.Request.Comment;
  43. using WingInterfaceLibrary.DTO.Common;
  44. namespace WingDeviceService.Service
  45. {
  46. /// <summary>
  47. /// 设备管理服务
  48. /// </summary>
  49. public partial class DeviceService : JsonRpcService, IDeviceService, ISyncDeviceRemoteConnectService
  50. {
  51. //远程调参
  52. private ConcurrentDictionary<string, CacheControllingParameter> _controllingParameterDevices = new ConcurrentDictionary<string, CacheControllingParameter>();
  53. private IUserDBService _userServiceProxy;
  54. private IDeviceInfoDBService _deviceInfoDBServiceProxy;
  55. private IAuthenticationService _authenticationService;
  56. private IOrganizationDBService _organizationDBService;
  57. private IUserDBService _userDBService;
  58. private INotificationService _notificationService;
  59. private IRecordsInfoDBService _recordsInfoDBService;
  60. private IPatientInfoDBService _patientInfoDBService;
  61. private IDiagnosisModuleDBService _diagnosisModuleService;
  62. private IRemedicalService _remedicalService;
  63. private IWingRtcService _wingRtcService;
  64. private IRtcService _rtcService;
  65. private IRtmpService _rtmpService;
  66. private int _heartRateSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
  67. private DeviceHeartRateManager _deviceHeartRateManager;
  68. private RemoteConnectManager _remoteConnectManager;
  69. private string _webSocketUrl => EnvironmentConfigManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
  70. private int _liveConsultationRateSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("LiveConsultation", "HeartRateSeconds").Value;
  71. // private int _remoteControlAskTimeoutSec => EnvironmentConfigManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
  72. private int _remoteControlHeartRateSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("Device", "RemoteControlHeartRateSeconds").Value;
  73. private int _reportStateIntervalSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("LiveConsultation", "ReportStateIntervalSeconds").Value;
  74. private int _reportStateTimeout = 0;
  75. private string _deviceShareUrl => EnvironmentConfigManager.GetParammeter<StringParameter>("Share", "DeviceLiveUrl").Value;
  76. private int _shareEffectiveSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("Share", "DeviceLiveEffectiveSeconds").Value;
  77. private ILiveConsultationService _liveConsultationService;
  78. private IConsultationRecordDBService _consultationRecordDBService;
  79. private IRemedicalDBService _remedicalDBService;
  80. private IShareDBService _shareDBService;
  81. private IMasterInteractionCenterService _masterInteractionCenterService;
  82. private string _serverID;
  83. private IDeviceForwardService _deviceForwardService;
  84. private readonly SequenceExecutor<ModifyDeviceRequest> _modifyDeviceExecutor = new SequenceExecutor<ModifyDeviceRequest>("UpdateDeviceInvented");
  85. /// <summary>
  86. /// Init service
  87. /// </summary>
  88. public override void Load(JsonRpcClientPool jsonRpcClientPool)
  89. {
  90. base.Load(jsonRpcClientPool);
  91. _userServiceProxy = GetProxy<IUserDBService>();
  92. _authenticationService = GetProxy<IAuthenticationService>();
  93. _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
  94. _userDBService = GetProxy<IUserDBService>();
  95. _organizationDBService = GetProxy<IOrganizationDBService>();
  96. _notificationService = GetProxy<INotificationService>();
  97. _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
  98. _patientInfoDBService = GetProxy<IPatientInfoDBService>();
  99. _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
  100. _remedicalService = GetProxy<IRemedicalService>();
  101. _wingRtcService = GetProxy<IWingRtcService>();
  102. _rtcService = GetProxy<IRtcService>();
  103. _rtmpService = GetProxy<IRtmpService>();
  104. _liveConsultationService = GetProxy<ILiveConsultationService>();
  105. _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
  106. _remedicalDBService = GetProxy<IRemedicalDBService>();
  107. _shareDBService = GetProxy<IShareDBService>();
  108. _masterInteractionCenterService = GetProxy<IMasterInteractionCenterService>();
  109. _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState, CheckDeviceLiveStatus);
  110. _remoteConnectManager = new RemoteConnectManager(RemoteConnectOnlineState, DeviceRemoteConnectOnlineState, _authenticationService);
  111. _reportStateTimeout = _reportStateIntervalSeconds + 60;
  112. _serverID = ConfigurationManager.GetParammeter<StringParameter>("General", "ServerID").Value;
  113. }
  114. /// <summary>
  115. /// default server restart run
  116. /// </summary>
  117. public override void LoadAfterRegister()
  118. {
  119. try
  120. {
  121. _deviceForwardService = GetProxy<IDeviceForwardService>();
  122. }
  123. catch (Exception ex)
  124. {
  125. Logger.WriteLineWarn($"DeviceService LoadAfterRegister err, {ex}");
  126. }
  127. }
  128. /// <summary>
  129. /// 设备心跳
  130. /// </summary>
  131. /// <param name="request"></param>
  132. /// <returns></returns>
  133. public async Task<bool> HeartRateAsync(TokenRequest request)
  134. {
  135. _deviceHeartRateManager.AddOrUpdate(request.Token);
  136. var result = SetOnlineState(request.Token, true);
  137. return result;
  138. }
  139. private bool SetOnlineState(string token, bool isOnline)
  140. {
  141. return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
  142. }
  143. private bool CheckDeviceLiveStatus()
  144. {
  145. try
  146. {
  147. _rtcService.CheckDeviceLiveRoomAsync(new TokenRequest { });
  148. }
  149. catch (Exception ex)
  150. {
  151. Logger.WriteLineWarn($"DeviceService CheckDeviceLiveStatus err, ex:{ex}");
  152. }
  153. return true;
  154. }
  155. /// <summary>
  156. /// 添加分享设备关联用户请求
  157. /// </summary>
  158. /// <param name="request"></param>
  159. /// <returns></returns>
  160. public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
  161. {
  162. var userCodes = request.UserCodes;
  163. var deviceCode = request.DeviceCode;
  164. //检查设备编码不为空
  165. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  166. {
  167. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  168. }
  169. if (userCodes == null || userCodes.Count <= 0)
  170. {
  171. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  172. }
  173. //查询设备对象
  174. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  175. if (deviceDb == null)
  176. {
  177. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  178. }
  179. foreach (var userCode in userCodes)
  180. {
  181. var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
  182. if (existUser == null)
  183. {
  184. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  185. }
  186. }
  187. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  188. {
  189. DeviceCodes = new List<string>() { deviceCode },
  190. OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
  191. UserCodes = userCodes.ToList()
  192. });
  193. return true;
  194. }
  195. /// <summary>
  196. /// 根据设备code获取设备信息
  197. /// </summary>
  198. /// <param name="request">设备code请求实体</param>
  199. /// <returns>返回查询到的设备对象信息</returns>
  200. public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
  201. {
  202. //验证
  203. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  204. {
  205. ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
  206. }
  207. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  208. if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
  209. {
  210. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  211. }
  212. //根据机构编号查询机构名称
  213. var organizationName = "";
  214. var patientType = OrganizationPatientTypeEnum.Person;
  215. if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
  216. {
  217. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
  218. organizationName = organization?.OrganizationName ?? string.Empty;
  219. patientType = organization?.PatientType ?? OrganizationPatientTypeEnum.Person;
  220. }
  221. //根据机构编号查询科室名称
  222. var departmentName = "";
  223. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  224. {
  225. var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
  226. departmentName = department?.OrganizationName ?? string.Empty;
  227. }
  228. //是否在线 todo
  229. var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
  230. var result = deviceDb.MappingTo<DeviceExtendInfoDTO>();
  231. result.DepartmentName = departmentName;
  232. result.OrganizationName = organizationName;
  233. result.IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode);
  234. result.IsCanRemoteMaintenance = true;
  235. result.LanguageConfigs = deviceTypeModel?.LanguageConfigs ?? new List<DictionaryLanguageConfigDTO>();
  236. result.PatientType = patientType;
  237. return result;
  238. }
  239. /// <summary>
  240. /// 根据设备动态唯一码获取设备信��
  241. /// </summary>
  242. /// <param name="request"></param>
  243. /// <returns></returns>
  244. public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
  245. {
  246. //验证
  247. if (string.IsNullOrWhiteSpace(request.ShortCode))
  248. {
  249. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
  250. }
  251. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  252. if (deviceDb == null || deviceDb.ShortCode.ToLower() != request.ShortCode.ToLower())
  253. {
  254. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  255. }
  256. return await MapToExtendDTO(deviceDb);
  257. }
  258. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
  259. {
  260. throw new System.NotImplementedException();
  261. }
  262. public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
  263. {
  264. var userCodes = request.UserCodes;
  265. var deviceCode = request.DeviceCode;
  266. //检查设备编码不为空
  267. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  268. {
  269. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  270. }
  271. //用户编码集合检��
  272. if (userCodes == null || userCodes.Count <= 0)
  273. {
  274. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  275. }
  276. //查询设备对象
  277. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  278. if (deviceDb == null)
  279. {
  280. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  281. }
  282. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  283. foreach (var userCode in userCodes)
  284. {
  285. var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
  286. if (user != null)
  287. {
  288. if (user.BindDevices.Contains(deviceCode))
  289. {
  290. user.BindDevices.Remove(deviceCode);
  291. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  292. {
  293. Data = user.MappingTo<UserPasswordDTO>(),
  294. });
  295. }
  296. }
  297. }
  298. if (updateUsers.Count > 0)
  299. {
  300. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  301. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  302. }
  303. return true;
  304. }
  305. /// <summary>
  306. /// 机构设备移除-根据机构code和设备code解除其绑定关系
  307. /// </summary>
  308. /// <param name="request">移除设备请求实体</param>
  309. /// <returns>移除是否成功:true-成功;false-失败</returns>
  310. public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
  311. {
  312. //验证
  313. if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
  314. {
  315. ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
  316. }
  317. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  318. if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
  319. {
  320. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
  321. }
  322. //根据设备code和机构code查询相关数据,查到则删除关联
  323. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  324. {
  325. deviceDb.DepartmentCode = "";
  326. deviceDb.OrganizationCode = "";
  327. }
  328. else
  329. {
  330. deviceDb.OrganizationCode = "";
  331. }
  332. bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  333. // 删除已知绑定的用户
  334. var users = await _userServiceProxy.GetUsersByDeviceAsync(deviceDb.DeviceCode);
  335. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  336. foreach (var user in users)
  337. {
  338. user.BindDevices.Remove(deviceDb.DeviceCode);
  339. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  340. {
  341. Data = user.MappingTo<UserPasswordDTO>(),
  342. });
  343. }
  344. if (updateUsers.Count > 0)
  345. {
  346. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  347. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  348. }
  349. return removeDeviceResult;
  350. }
  351. private async Task<string> GetClientIdByTokenAsync(string token)
  352. {
  353. var request = new TokenRequest() { Token = token };
  354. var result = await _authenticationService.GetTokenAsync(request);
  355. return result.ClientId; //return User code
  356. }
  357. /// <summary>
  358. /// 查询机构管理员机构名下所有设备列表接口
  359. /// </summary>
  360. /// <param name="request">请求实体</param>
  361. /// <returns>返回设备信息列表</returns>
  362. public async Task<PageCollection<DeviceExtendInfoDTO>> GetOrganizationDeviceListAsync(GetPersonDeviceRequest request)
  363. {
  364. //验证
  365. var userCode = await GetClientIdByTokenAsync(request.Token);
  366. //查询用户是否存在
  367. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  368. if (userInfoDO == null)
  369. {
  370. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  371. }
  372. //查询用户的医院是否存在
  373. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  374. {
  375. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  376. }
  377. //判断是否机构管理员
  378. if (!userInfoDO.IsDirector)
  379. {
  380. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "Not organization administrator");
  381. }
  382. var deviceInfoDTOList = new List<DeviceInfoDTO>();
  383. var dbPage = new PageResult<DeviceInfoDTO>();
  384. var dbRequest = new FindDeviceInfoPageRequest()
  385. {
  386. PageIndex = request.PageIndex,
  387. PageSize = request.PageSize,
  388. DeviceType = request.DeviceType,
  389. DeviceModel = request.DeviceModel,
  390. KeyWord = request.KeyWord,
  391. IsOnline = request.IsOnline,
  392. OrganizationCodes = request.OrganizationCodes
  393. };
  394. var tokenList = CacheMaintenance.Instance.Get<ITokensManager>().Where(c => (c.AccountType == 2 || c.AccountType == 3) && c.IsOnline == true)?.ToList();
  395. if (tokenList?.Count > 0)
  396. {
  397. dbRequest.IsOnlineCodes = tokenList.Select(c => c.ClientId).Distinct().ToList();
  398. }
  399. //机构负责人
  400. var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  401. var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  402. if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  403. {
  404. orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  405. }
  406. dbRequest.OrgCodes = orgCodes;
  407. dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
  408. if (dbPage?.PageData?.Count > 0)
  409. {
  410. deviceInfoDTOList = dbPage.PageData;
  411. }
  412. if (!deviceInfoDTOList.Any())
  413. {
  414. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  415. }
  416. var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
  417. foreach (var device in deviceList)
  418. {
  419. device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
  420. }
  421. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  422. {
  423. CurrentPage = request.PageIndex,
  424. PageSize = request.PageSize,
  425. DataCount = dbPage.TotalCount,
  426. PageData = deviceList
  427. };
  428. return pagedResult;
  429. }
  430. /// <summary>
  431. /// 查询个人名下本机构所有设备列表接口
  432. /// </summary>
  433. /// <param name="request"></param>
  434. /// <returns>返回设备信息列表</returns>
  435. /// <errorCodes>UserNotExistError,OrganizationNotExist</errorCodes>
  436. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonOrgDeviceListAsync(GetPersonDeviceRequest request)
  437. {
  438. //验证
  439. var userCode = await GetClientIdByTokenAsync(request.Token);
  440. //查询用户是否存在
  441. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  442. if (userInfoDO == null)
  443. {
  444. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  445. }
  446. // //查询用户的医院是否存在
  447. // if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  448. // {
  449. // ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  450. // }
  451. var deviceInfoDTOList = new List<DeviceInfoDTO>();
  452. var dbPage = new PageResult<DeviceInfoDTO>();
  453. var dbRequest = new FindDeviceInfoPageRequest()
  454. {
  455. UserCode = userCode,
  456. PageIndex = request.PageIndex,
  457. PageSize = request.PageSize,
  458. DeviceType = request.DeviceType,
  459. DeviceModel = request.DeviceModel,
  460. KeyWord = request.KeyWord,
  461. IsOnline = request.IsOnline,
  462. OrganizationCodes = request.OrganizationCodes
  463. };
  464. dbPage = await _deviceInfoDBServiceProxy.FindMyOrgDeviceInfoListPageDBAsync(dbRequest);
  465. if (dbPage?.PageData?.Count > 0)
  466. {
  467. deviceInfoDTOList = dbPage.PageData;
  468. }
  469. if (!deviceInfoDTOList.Any())
  470. {
  471. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  472. }
  473. var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
  474. foreach (var device in deviceList)
  475. {
  476. device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
  477. }
  478. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  479. {
  480. CurrentPage = request.PageIndex,
  481. PageSize = request.PageSize,
  482. DataCount = dbPage.TotalCount,
  483. PageData = deviceList
  484. };
  485. return pagedResult;
  486. }
  487. /// <summary>
  488. /// 查询个人名下所有设备列表接口
  489. /// </summary>
  490. /// <param name="request">查询个人名下所有设备列表请求实体</param>
  491. /// <returns>返回设备信息列表</returns>
  492. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
  493. {
  494. //验证
  495. var userCode = await GetClientIdByTokenAsync(request.Token);
  496. //查询用户是否存在
  497. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  498. if (userInfoDO == null)
  499. {
  500. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  501. }
  502. // //查询用户的医院是否存在
  503. // if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  504. // {
  505. // ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  506. // }
  507. var deviceInfoDTOList = new List<DeviceInfoDTO>();
  508. //普通用户,查询用户绑定的设备
  509. var dbPage = new PageResult<DeviceInfoDTO>();
  510. var dbRequest = new FindDeviceInfoPageRequest()
  511. {
  512. PageIndex = request.PageIndex,
  513. PageSize = request.PageSize,
  514. DeviceType = request.DeviceType,
  515. DeviceModel = request.DeviceModel,
  516. KeyWord = request.KeyWord,
  517. IsOnline = request.IsOnline,
  518. OrganizationCodes = request.OrganizationCodes
  519. };
  520. var tokenList = CacheMaintenance.Instance.Get<ITokensManager>().Where(c => (c.AccountType == 2 || c.AccountType == 3) && c.IsOnline == true)?.ToList();
  521. if (tokenList?.Count > 0)
  522. {
  523. dbRequest.IsOnlineCodes = tokenList.Select(c => c.ClientId).Distinct().ToList();
  524. }
  525. if (userInfoDO.IsDirector)
  526. {
  527. //机构负责人
  528. var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  529. var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  530. if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  531. {
  532. orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  533. }
  534. dbRequest.OrgCodes = orgCodes;
  535. }
  536. dbRequest.DeviceCodes = userInfoDO.BindDevices;
  537. dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
  538. if (dbPage?.PageData?.Count > 0)
  539. {
  540. deviceInfoDTOList = dbPage.PageData;
  541. }
  542. if (!deviceInfoDTOList.Any())
  543. {
  544. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  545. }
  546. var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
  547. foreach (var device in deviceList)
  548. {
  549. device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
  550. }
  551. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  552. {
  553. CurrentPage = request.PageIndex,
  554. PageSize = request.PageSize,
  555. DataCount = dbPage.TotalCount,
  556. PageData = deviceList
  557. //PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
  558. };
  559. return pagedResult;
  560. }
  561. /// <summary>
  562. /// 查询设备列表(助理查专家的如果没有专家则查机构的)
  563. /// </summary>
  564. /// <param name="request">查询设备列表请求实体</param>
  565. /// <returns>返回设备信息列表</returns>
  566. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceListByPersonRoleAsync(GetPersonRoleDeviceRequest request)
  567. {
  568. //验证
  569. var userCode = await GetClientIdByTokenAsync(request.Token);
  570. //查询用户是否存在
  571. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  572. if (userInfoDO == null)
  573. {
  574. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  575. }
  576. //查询用户的医院是否存在
  577. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  578. {
  579. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  580. }
  581. var deviceInfoDTOList = new List<DeviceInfoDTO>();
  582. //普通用户,查询用户绑定的设备
  583. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
  584. {
  585. deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  586. }
  587. if (userInfoDO.IsDirector)
  588. {
  589. //机构负责人
  590. var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  591. var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  592. if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  593. {
  594. orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  595. }
  596. var orgDeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodesAsync(orgCodes);
  597. if (orgDeviceInfoDTOList != null && orgDeviceInfoDTOList.Count > 0)
  598. {
  599. var devinceInfoCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
  600. foreach (var item in orgDeviceInfoDTOList)
  601. {
  602. if (!devinceInfoCodes.Contains(item.DeviceCode))
  603. {
  604. deviceInfoDTOList.Add(item);
  605. }
  606. }
  607. }
  608. }
  609. //助理
  610. if (userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  611. {
  612. var basedeviceInfoDTOList = new List<DeviceInfoDTO>();
  613. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  614. if (experts.Any())
  615. {
  616. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  617. if (bindDeviceCodes.Any())
  618. {
  619. basedeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  620. }
  621. }
  622. else
  623. {
  624. basedeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  625. }
  626. if (deviceInfoDTOList.Count > 0)
  627. {
  628. var deviceCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
  629. foreach (var item in basedeviceInfoDTOList)
  630. {
  631. if (!deviceCodes.Contains(item.DeviceCode))
  632. {
  633. deviceInfoDTOList.Add(item);
  634. }
  635. }
  636. }
  637. else
  638. {
  639. deviceInfoDTOList.AddRange(basedeviceInfoDTOList);
  640. }
  641. }
  642. if (!deviceInfoDTOList.Any())
  643. {
  644. return new PageCollection<DeviceInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceInfoDTO>() };
  645. }
  646. //条件筛选
  647. if (!string.IsNullOrWhiteSpace(request.DeviceType))
  648. {
  649. deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceInfoDTO>();
  650. }
  651. if (!string.IsNullOrWhiteSpace(request.DeviceModel))
  652. {
  653. deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceInfoDTO>();
  654. }
  655. if (!string.IsNullOrWhiteSpace(request.KeyWord))
  656. {
  657. string keyword = request.KeyWord.Trim().ToLower();
  658. deviceInfoDTOList = deviceInfoDTOList.Where(d => (!string.IsNullOrWhiteSpace(d.Description) && d.Description.ToLower().Contains(keyword)) || (!string.IsNullOrWhiteSpace(d.Name) && d.Name.ToLower().Contains(keyword)) || ((!string.IsNullOrWhiteSpace(d.ShortCode) && d.ShortCode.ToLower().Contains(keyword))))?.ToList() ?? new List<DeviceInfoDTO>();
  659. }
  660. var pagedResult = new PageCollection<DeviceInfoDTO>
  661. {
  662. CurrentPage = request.PageIndex,
  663. PageSize = request.PageSize,
  664. DataCount = deviceInfoDTOList.Count,
  665. PageData = deviceInfoDTOList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceInfoDTO>()
  666. };
  667. return pagedResult;
  668. }
  669. /// <summary>
  670. /// 更新虚拟设备检查和病人信息
  671. /// </summary>
  672. /// <param name="request">请求实体</param>
  673. /// <returns></returns>
  674. private bool OnUpdateInventedDeviceInfoAsync(ModifyDeviceRequest request)
  675. {
  676. try
  677. {
  678. //迁移数据超声机上传检查记录
  679. var orgResult = _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { request.DeviceCode }, request.DepartmentCode).Result;
  680. //迁移数据超声机上传病人
  681. var patientResult = _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { request.DeviceCode }, request.DepartmentCode).Result;
  682. }
  683. catch (Exception ex)
  684. {
  685. Logger.WriteLineWarn($"save admin statistic info failed, ex:{ex}");
  686. }
  687. return true;
  688. }
  689. /// <summary>
  690. /// 机构负责人,机构绑定设备
  691. /// </summary>
  692. /// <param name="request"></param>
  693. /// <returns></returns>
  694. public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
  695. {
  696. //验证
  697. var userCode = await GetClientIdByTokenAsync(request.Token);
  698. //查询用户是否存在
  699. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  700. if (userInfoDO == null)
  701. {
  702. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  703. }
  704. if (string.IsNullOrEmpty(request.ShortCode))
  705. {
  706. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCodeEmpty");
  707. }
  708. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  709. if (deviceDb == null)
  710. {
  711. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  712. }
  713. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  714. {
  715. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  716. }
  717. // //判断设备绑定机构是否跟用户的机构一致
  718. // //判断父子级,父级可以绑定子集机构的设备 杏聆荟平台可以绑定任何设备
  719. // var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  720. // var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  721. // if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  722. // {
  723. // orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  724. // }
  725. // if (userInfoDO.RootOrganizationCode != "VINNO_FIS" && !string.IsNullOrEmpty(deviceDb.OrganizationCode) && !orgCodes.Contains(deviceDb.OrganizationCode))
  726. // {
  727. // ThrowCustomerException(CustomerRpcCode.OrganizationCodeInconformity, "Organization code inconformity");
  728. // }
  729. if (string.IsNullOrEmpty(request.Description))
  730. {
  731. ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "DeviceNameEmpty");
  732. }
  733. if (request.Name.Length > 50)
  734. {
  735. ThrowCustomerException(CustomerRpcCode.TooLongCharacter, "TooLongCharacter");
  736. }
  737. try
  738. {
  739. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == "VINNO_FIS") ? true : false;
  740. if (!string.IsNullOrEmpty(request.Description))
  741. {
  742. deviceDb.Description = request.Description;
  743. }
  744. if (!string.IsNullOrEmpty(request.HeadPicUrl))
  745. {
  746. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  747. }
  748. deviceDb.DepartmentCode = request.DepartmentCode;
  749. deviceDb.IsAutoShared = request.IsAutoShared;
  750. deviceDb.OrganizationCode = request.OrganizationCode;
  751. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  752. if (isInvented) //虚拟机构改为正常机构
  753. {
  754. if (string.IsNullOrWhiteSpace(request.OrganizationCode) && string.IsNullOrWhiteSpace(request.DepartmentCode))
  755. {
  756. ThrowCustomerException(CustomerRpcCode.OrganizationCodeEmpty, "OrganizationCodeEmpty");
  757. }
  758. var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
  759. var orgInfo = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = newOrgCode });
  760. if (orgInfo == null)
  761. {
  762. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "OrganizationNotExist");
  763. }
  764. // //迁移数据超声机上传检查记录
  765. // await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  766. // //迁移数据超声机上传病人
  767. // await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  768. _modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
  769. }
  770. var userCodes = new List<string>();
  771. if (deviceDb.IsAutoShared)
  772. {
  773. var users = new List<UserDTO>();
  774. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  775. {
  776. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  777. }
  778. else
  779. {
  780. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  781. }
  782. userCodes = users.Select(f => f.UserCode).ToList();
  783. }
  784. else
  785. {
  786. userCodes.Add(userCode);
  787. }
  788. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  789. {
  790. DeviceCodes = new List<string>() { deviceDb.DeviceCode },
  791. OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
  792. UserCodes = userCodes
  793. });
  794. return true;
  795. }
  796. catch (Exception ex)
  797. {
  798. Logger.WriteLineError($"BindDeviceAsync error {ex}");
  799. }
  800. return false;
  801. }
  802. /// <summary>
  803. /// 修改设备全部信息
  804. /// </summary>
  805. /// <param name="request"></param>
  806. /// <returns></returns>
  807. public async Task<bool> UpdateDeviceAsync(UpdateDeviceRequest request)
  808. {
  809. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  810. if (deviceDb == null)
  811. {
  812. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  813. }
  814. //全部覆盖
  815. deviceDb = request.MappingTo<DeviceInfoDTO>();
  816. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  817. }
  818. /// <summary>
  819. /// 修改设备
  820. /// </summary>
  821. /// <param name="request"></param>
  822. /// <returns></returns>
  823. public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
  824. {
  825. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  826. if (deviceDb == null)
  827. {
  828. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  829. }
  830. if (string.IsNullOrWhiteSpace(request.Description))
  831. {
  832. ThrowCustomerException(CustomerRpcCode.DeviceDescriptionEmpty, "Device description cannot be empty");
  833. }
  834. //当设备描述为空或者设备描述与设备名称一致的情况下,所有用户都有编辑描述和封面的功能
  835. if (string.IsNullOrEmpty(deviceDb.Description) || deviceDb.Description == deviceDb.Name)
  836. {
  837. if (!string.IsNullOrWhiteSpace(request.Description))
  838. {
  839. deviceDb.Description = request.Description;
  840. }
  841. }
  842. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  843. if (!string.IsNullOrEmpty(deviceDb.Description) && !string.IsNullOrEmpty(request.Description) && deviceDb.Description != request.Description)
  844. {
  845. ThrowCustomerException(CustomerRpcCode.DeviceDescriptionNotModify, "Device description not modify");
  846. }
  847. deviceDb.DepartmentCode = request.DepartmentCode;
  848. //修改自动分享
  849. deviceDb.IsAutoShared = request.IsAutoShared;
  850. if (deviceDb.IsAutoShared)
  851. {
  852. var users = new List<UserDTO>();
  853. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  854. {
  855. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  856. }
  857. else
  858. {
  859. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  860. }
  861. var userCodes = users.Select(f => f.UserCode).ToList();
  862. //先解绑,再绑定,避免绑定重复设备code
  863. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  864. foreach (var user in users)
  865. {
  866. var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
  867. user.BindDevices?.Remove(deviceDb.DeviceCode);
  868. await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
  869. }
  870. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  871. {
  872. DeviceCodes = new List<string>() { deviceDb.DeviceCode },
  873. OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
  874. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  875. });
  876. }
  877. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  878. }
  879. /// <summary>
  880. /// 创建字典
  881. /// </summary>
  882. /// <param name="request"></param>
  883. /// <returns></returns>
  884. public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
  885. {
  886. return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
  887. {
  888. Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
  889. ExtensionData = string.Empty
  890. });
  891. }
  892. /// <summary>
  893. /// 查找设备型号所有字典项
  894. /// </summary>
  895. /// <param name="request"></param>
  896. /// <returns></returns>
  897. public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
  898. {
  899. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  900. {
  901. DictionaryType = (int)request.DictionaryType,
  902. ParentCode = request.DeviceTypeCode
  903. });
  904. return dictionaryDOList;
  905. }
  906. /// <summary>
  907. /// 查找设备类型所有字典项
  908. /// </summary>
  909. /// <param name="request"></param>
  910. /// <returns></returns>
  911. public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
  912. {
  913. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  914. {
  915. DictionaryType = (int)request.DictionaryType
  916. });
  917. return dictionaryDOList;
  918. }
  919. /// <summary>
  920. /// 根据组织编码查询所属全部设备信息
  921. /// </summary>
  922. /// <param name="request"></param>
  923. /// <returns></returns>
  924. public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
  925. {
  926. var result = new List<DeviceExtendInfoDTO>();
  927. var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
  928. if (deviceInfoDOList?.Count > 0)
  929. {
  930. //根据机构编号查询机构名称
  931. var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
  932. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
  933. var organizationName = organization?.OrganizationName ?? string.Empty;
  934. //根据机构编号查询科室名称
  935. var organizationFilter = new Dictionary<string, string>();
  936. organizationFilter.Add("RootCode", organizationCode);
  937. var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
  938. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  939. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  940. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  941. foreach (var c in deviceInfoDOList)
  942. {
  943. var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
  944. result.Add(new DeviceExtendInfoDTO
  945. {
  946. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  947. OrganizationName = organizationName,
  948. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  949. DeviceCode = c.DeviceCode,
  950. SerialNumber = c.SerialNumber,
  951. Name = c.Name,
  952. Description = c.Description,
  953. DeviceModel = c.DeviceModel,
  954. DeviceType = c.DeviceType,
  955. HeadPicUrl = c.HeadPicUrl,
  956. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  957. SDKSoftwareVersion = c.SDKSoftwareVersion,
  958. OrganizationCode = c.OrganizationCode,
  959. DepartmentCode = c.DepartmentCode,
  960. ShortCode = c.ShortCode,
  961. LanguageConfigs = deviceTypeModel?.LanguageConfigs
  962. });
  963. }
  964. }
  965. return result;
  966. }
  967. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  968. {
  969. throw new NotImplementedException();
  970. }
  971. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  972. {
  973. //验证
  974. var userCode = await GetClientIdByTokenAsync(request.Token);
  975. //查询用户是否存在
  976. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  977. if (userInfoDO == null)
  978. {
  979. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  980. }
  981. var result = new List<SelectItemDTO>();
  982. //查询用户的医院是否存在
  983. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  984. {
  985. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  986. }
  987. var deviceInfoDTOList = new List<DeviceInfoDTO>();
  988. if (userInfoDO.IsDirector)
  989. {
  990. //查询个人的设备数据
  991. deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  992. //查询机构的设备数据
  993. var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  994. var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  995. if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  996. {
  997. orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  998. }
  999. var orgDeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodesAsync(orgCodes);
  1000. if (orgDeviceInfoDTOList != null && orgDeviceInfoDTOList.Count > 0)
  1001. {
  1002. var devinceInfoCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
  1003. foreach (var item in orgDeviceInfoDTOList)
  1004. {
  1005. if (!devinceInfoCodes.Contains(item.DeviceCode))
  1006. {
  1007. deviceInfoDTOList.Add(item);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  1013. {
  1014. //查询用户绑定的设备
  1015. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  1016. {
  1017. return result;
  1018. }
  1019. //根据用户名下的设备id查询所有的设备信息
  1020. deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  1021. }
  1022. else
  1023. {
  1024. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  1025. if (experts.Any())
  1026. {
  1027. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  1028. if (bindDeviceCodes.Any())
  1029. {
  1030. deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  1031. }
  1032. }
  1033. else
  1034. {
  1035. deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  1036. }
  1037. }
  1038. if (deviceInfoDTOList?.Count > 0)
  1039. {
  1040. result = deviceInfoDTOList.Select(c => new SelectItemDTO()
  1041. {
  1042. Key = c.DeviceCode,
  1043. Value = c.Description ?? c.Name
  1044. }).ToList();
  1045. }
  1046. return result;
  1047. }
  1048. /// <summary>
  1049. /// 设备端调用,查询获取服务器配置信息接口
  1050. /// </summary>
  1051. /// <param name="request">Token验证</param>
  1052. /// <returns>服务器配置信息结果key:字段,value:数据值,复杂类型可为json</returns>
  1053. public async Task<DeviceServerSettingResult> QueryServerConfigAsync(TokenRequest request)
  1054. {
  1055. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1056. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  1057. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  1058. {
  1059. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  1060. }
  1061. var org = new OrganizationDTO();
  1062. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  1063. {
  1064. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  1065. if (org == null)
  1066. {
  1067. org = new OrganizationDTO();
  1068. }
  1069. }
  1070. var dictionary = new Dictionary<string, string>();
  1071. //定义配置字段 并扩充字段,返回数据可持续更新接口文�如果数据是复杂类型可以转成json
  1072. //TODO 配置信息: 直播配置、存储配置�
  1073. //存储上传图像或者视频是 是否本地上传缩略��
  1074. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  1075. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  1076. dictionary.Add("PatientType", org.PatientType.ToString());
  1077. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  1078. dictionary.Add("NotificationUrl", _webSocketUrl);
  1079. dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
  1080. dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
  1081. var liveProtocol = string.Empty;
  1082. var _isRTCSelf = false;
  1083. var liveProtocolType = TransactionStatusEnum.Common;
  1084. try
  1085. {
  1086. var rtcType = EnvironmentConfigManager.GetParammeter<StringParameter>("Rtc", "RTCType").Value;
  1087. _isRTCSelf = rtcType == "VRTC";
  1088. if (EnvironmentConfigs.General.LiveProtocol.ToLower() == "rtmp")
  1089. {
  1090. liveProtocol = EnvironmentConfigs.Rtmp.RTMPType;
  1091. }
  1092. else
  1093. {
  1094. liveProtocol = EnvironmentConfigs.Rtc.RTCType;
  1095. }
  1096. liveProtocolType = EnvironmentConfigs.General.LiveProtocolDetail<TransactionStatusEnum>();
  1097. }
  1098. catch (Exception ex)
  1099. {
  1100. Logger.WriteLineWarn($"DeviceService liveProtocol not config");
  1101. }
  1102. var result = new DeviceServerSettingResult()
  1103. {
  1104. ServerConfigList = dictionary,
  1105. IsUploadThumbnail = isUploadThumbnail,
  1106. PatientType = org.PatientType,
  1107. HeartRateSeconds = _heartRateSeconds,
  1108. NotificationUrl = _webSocketUrl,
  1109. LiveConsultationRateSeconds = _liveConsultationRateSeconds,
  1110. MergedChannel = deviceInfo.MergedChannel,
  1111. MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
  1112. MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
  1113. IsSelfRtcService = _isRTCSelf,
  1114. // RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec,
  1115. RemoteControlHeartRateSeconds = _remoteControlHeartRateSeconds,
  1116. LiveProtocol = liveProtocol,
  1117. LiveProtocolType = liveProtocolType,
  1118. FISWebUrl = EnvironmentConfigManager.GetParammeter<StringParameter>("Gateway", "FISWebUrl").Value,
  1119. IsResearchEditionService = GetIsResearchEditionService(),
  1120. };
  1121. return result;
  1122. }
  1123. private bool GetIsResearchEditionService()
  1124. {
  1125. var result = false;
  1126. try
  1127. {
  1128. result = EnvironmentConfigManager.GetParammeter<BoolParameter>("General", "IsResearchEditionService").Value;
  1129. }
  1130. catch
  1131. {
  1132. }
  1133. return result;
  1134. }
  1135. /// <summary>
  1136. /// 添加或迁移设备到医院请求(废弃)
  1137. /// </summary>
  1138. /// <param name="request"></param>
  1139. /// <returns></returns>
  1140. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  1141. {
  1142. var shortCode = request.UniqueCode;
  1143. #region Params Check
  1144. var userCode = await GetClientIdByTokenAsync(request.Token);
  1145. if (string.IsNullOrEmpty(shortCode))
  1146. {
  1147. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  1148. }
  1149. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  1150. if (device == null)
  1151. {
  1152. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  1153. }
  1154. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  1155. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  1156. {
  1157. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  1158. }
  1159. //用户
  1160. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1161. if (userDTO == null)
  1162. {
  1163. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1164. }
  1165. if (!userDTO.IsDirector)
  1166. {
  1167. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  1168. }
  1169. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  1170. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  1171. {
  1172. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  1173. }
  1174. #endregion
  1175. try
  1176. {
  1177. var newOrgode = org.OrganizationCode;
  1178. //设备更新医院
  1179. if (!string.IsNullOrEmpty(device.DepartmentCode))
  1180. {
  1181. device.DepartmentCode = "";
  1182. }
  1183. if (!string.IsNullOrEmpty(device.Name))
  1184. {
  1185. device.Name = "";
  1186. }
  1187. device.HeadPicUrl = "";
  1188. device.Description = "";
  1189. device.IsAutoShared = false;
  1190. device.OrganizationCode = newOrgode;
  1191. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  1192. if (success)
  1193. {
  1194. // 删除已知绑定的用��
  1195. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  1196. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  1197. foreach (var user in users)
  1198. {
  1199. user.BindDevices.Remove(device.DeviceCode);
  1200. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  1201. {
  1202. Data = user.MappingTo<UserPasswordDTO>(),
  1203. });
  1204. }
  1205. if (updateUsers.Count > 0)
  1206. {
  1207. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  1208. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  1209. }
  1210. if (oldOrg.Isinvented) // 虚拟医院
  1211. {
  1212. //迁移数据超声机上传检查记��
  1213. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  1214. //迁移数据超声机上传病��
  1215. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  1216. }
  1217. }
  1218. return success;
  1219. }
  1220. catch (System.Exception ex)
  1221. {
  1222. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  1223. }
  1224. return false;
  1225. }
  1226. /// <summary>
  1227. /// 补齐设备扩展信息
  1228. /// </summary>
  1229. /// <param name="deviceInfoDOList"></param>
  1230. /// <returns></returns>
  1231. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList, UserDTO userInfo = null)
  1232. {
  1233. var deviceList = new List<DeviceExtendInfoDTO>();
  1234. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  1235. {
  1236. //查询机构
  1237. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  1238. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  1239. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  1240. //查询机构负责人
  1241. var organizationDirectorCodes = new List<string>();
  1242. foreach (var org in organizations)
  1243. {
  1244. if (org.Directors != null && org.Directors.Any())
  1245. {
  1246. organizationDirectorCodes.AddRange(org.Directors);
  1247. }
  1248. }
  1249. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  1250. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  1251. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  1252. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  1253. foreach (var dto in deviceInfoDOList)
  1254. {
  1255. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  1256. var deviceTokenInfo = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode);
  1257. device.IsOnline = deviceTokenInfo?.IsOnline ?? false;
  1258. var curOrgInfo = organizations.FirstOrDefault(c => c.OrganizationCode == dto.OrganizationCode) ?? new OrganizationDTO();
  1259. device.PatientType = curOrgInfo?.PatientType ?? OrganizationPatientTypeEnum.Person;
  1260. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  1261. device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
  1262. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  1263. if (organization != null)
  1264. {
  1265. device.OrganizationName = organization.OrganizationName;
  1266. if (organization.Directors != null && organization.Directors.Any())
  1267. {
  1268. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  1269. device.OrganizationDirectorCode = director?.UserCode;
  1270. device.OrganizationDirectorUserName = director?.UserName;
  1271. device.OrganizationDirectorFullName = director?.FullName;
  1272. }
  1273. }
  1274. if (device.DeviceType.ToLower() == "sonopost")
  1275. {
  1276. device.IsCanRestart = true;
  1277. if (deviceTokenInfo != null && deviceTokenInfo.IsOldPlatform)
  1278. {
  1279. device.IsCanRestart = false;
  1280. }
  1281. }
  1282. if (userInfo != null)
  1283. {
  1284. //调整逻辑,只有远程维护权限的,才能开启远程维护功能,机构管理员如果没有远程维护菜单,则不能开启远程控制,自己机构的设备也不行;
  1285. if (userInfo.UserFeatureCodes != null && userInfo.UserFeatureCodes.Exists(c => c == "RemoteMaintain" || c == "RemoteManager"))
  1286. {
  1287. //远程维护管理员,那么权限全开
  1288. device.IsCanRemoteMaintenance = true;
  1289. }
  1290. // else if (userInfo.IsDirector)
  1291. // {
  1292. // //如果是机构管理员,本机构的设备才可以有权限,非本机构的无远程维护权限
  1293. // if (!string.IsNullOrEmpty(userInfo.OrganizationCode) && !string.IsNullOrEmpty(device.OrganizationCode) && userInfo.OrganizationCode == device.OrganizationCode)
  1294. // {
  1295. // device.IsCanRemoteMaintenance = true;
  1296. // }
  1297. // else
  1298. // {
  1299. // device.IsCanRemoteMaintenance = false;
  1300. // }
  1301. // }
  1302. else
  1303. {
  1304. device.IsCanRemoteMaintenance = false;
  1305. }
  1306. }
  1307. deviceList.Add(device);
  1308. }
  1309. }
  1310. return deviceList;
  1311. }
  1312. /// <summary>
  1313. /// 补齐设备扩展信息
  1314. /// </summary>
  1315. /// <param name="deviceInfoDOList"></param>
  1316. /// <returns></returns>
  1317. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  1318. {
  1319. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  1320. return deviceList.FirstOrDefault();
  1321. }
  1322. /// <summary>
  1323. /// 获取设备绑定用户codes
  1324. /// </summary>
  1325. /// <param name="request">获取设备绑定用户codes请求实体</param>
  1326. /// <returns>test01,test02</returns>
  1327. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  1328. {
  1329. //检查设备编码不为空
  1330. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  1331. {
  1332. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1333. }
  1334. //查询设备对象
  1335. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  1336. if (deviceDb == null)
  1337. {
  1338. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  1339. }
  1340. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  1341. if (userListResult != null && userListResult.Count > 0)
  1342. {
  1343. return userListResult.Select(u => u.UserCode).ToList();
  1344. }
  1345. return new List<string>();
  1346. }
  1347. /// <summary>
  1348. /// 查询设备AI应用的状��
  1349. /// </summary>
  1350. /// <param name="request">请求参数</param>
  1351. /// <returns>AI应用集合</returns>
  1352. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  1353. {
  1354. //检查设备编码不为空
  1355. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  1356. {
  1357. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1358. }
  1359. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  1360. }
  1361. /// <summary>
  1362. /// 修改设备AI应用启用状��
  1363. /// </summary>
  1364. /// <param name="request">修改设备AI应用启用状态请求实��/param>
  1365. /// <returns>是否成功</returns>
  1366. /// <para>DeviceErrorCodeEnum</para>
  1367. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  1368. {
  1369. //检查设备编码不为空
  1370. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  1371. {
  1372. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1373. }
  1374. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  1375. {
  1376. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  1377. }
  1378. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  1379. {
  1380. DeviceCode = request.DeviceCode,
  1381. DiagnosisModule = request.DiagnosisModule,
  1382. Enabled = request.Enabled
  1383. });
  1384. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  1385. return result;
  1386. }
  1387. /// <summary>
  1388. /// 设备离开会诊房间
  1389. /// </summary>
  1390. /// <param name="request">设备离开会诊房间请求实体</param>
  1391. /// <returns></returns>
  1392. public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
  1393. {
  1394. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1395. var result = new DeviceLeaveLiveConsultationResult
  1396. {
  1397. Success = false,
  1398. };
  1399. return result;
  1400. }
  1401. /// <summary>
  1402. /// 通用异常处理方法
  1403. /// </summary>
  1404. /// <param name="customerRpcCodeEnum">异常标识码</param>
  1405. /// <param name="msg">异常信息</param>
  1406. /// <param name="internalMessage">内部异常信息,非必填</param>
  1407. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  1408. {
  1409. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  1410. }
  1411. /// <summary>
  1412. /// 上报设备画面尺寸相关信息
  1413. /// </summary>
  1414. /// <param name="request"></param>
  1415. /// <docFirstDirectory>设备端API</docFirstDirectory>
  1416. /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
  1417. /// <docThirdDirectory>会诊</docThirdDirectory>
  1418. /// <returns></returns>
  1419. public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
  1420. {
  1421. var tokenInfo = await _authenticationService.GetTokenAsync(request);
  1422. var result = new ReportVideoDeviceInfoResult();
  1423. request.VideoDeviceInfos = request.VideoDeviceInfos?.ToList() ?? new List<VideoDeviceInfo>();
  1424. if (request.VideoDeviceInfos.Any())
  1425. {
  1426. if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
  1427. {
  1428. //视屏设备ID为空
  1429. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
  1430. }
  1431. var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
  1432. if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
  1433. {
  1434. //视屏设备ID重复
  1435. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
  1436. }
  1437. }
  1438. var deviceCode = tokenInfo.ClientId;
  1439. var isOldPlatform = tokenInfo != null && tokenInfo.IsOnline && tokenInfo.IsOldPlatform;
  1440. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  1441. var screenAndCamera = request.VideoDeviceInfos.Any(x => x.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Camera);
  1442. var outputWidth = deviceDTO.MergedVideoOutputWidth;
  1443. var outputHeight = deviceDTO.MergedVideoOutputHeight;
  1444. if (outputWidth <= 0 || outputHeight <= 0)
  1445. {
  1446. outputWidth = 1280;
  1447. outputHeight = 720;
  1448. }
  1449. if (!deviceDTO.MergedChannel)
  1450. {
  1451. var highCpu = _highCpuLevels?.Split(',');
  1452. if (deviceDTO.DeviceModel.ToUpper().StartsWith("SP002"))
  1453. {
  1454. outputWidth = _highMergedVideoOutputWidth;
  1455. outputHeight = _highMergedVideoOutputHeight;
  1456. }
  1457. else if (highCpu != null && highCpu.Contains(deviceDTO.CPUModel))
  1458. {
  1459. outputWidth = _highMergedVideoOutputWidth;
  1460. outputHeight = _highMergedVideoOutputHeight;
  1461. }
  1462. else if (deviceDTO.CPUModel.StartsWith("I"))
  1463. {
  1464. int.TryParse(deviceDTO.CPUModel.Substring(1, deviceDTO.CPUModel.IndexOf('-') - 1), out int cpuLevel);
  1465. if (cpuLevel >= 5)
  1466. {
  1467. outputWidth = _highMergedVideoOutputWidth;
  1468. outputHeight = _highMergedVideoOutputHeight;
  1469. }
  1470. else
  1471. {
  1472. outputWidth = _lowMergedVideoOutputWidth;
  1473. outputHeight = _lowMergedVideoOutputHeight;
  1474. }
  1475. }
  1476. else
  1477. {
  1478. outputWidth = _lowMergedVideoOutputWidth;
  1479. outputHeight = _lowMergedVideoOutputHeight;
  1480. }
  1481. }
  1482. var videoDeviceInfos = new List<VideoDeviceDTO>();
  1483. foreach (var video in request.VideoDeviceInfos)
  1484. {
  1485. var videoDeviceInfo = InitOutputInfo(video, deviceDTO.MergedChannel, screenAndCamera, outputWidth, outputHeight);
  1486. if (isOldPlatform)
  1487. {
  1488. videoDeviceInfo.OutputWidth = videoDeviceInfo.Width;
  1489. videoDeviceInfo.OutputHeight = videoDeviceInfo.Height;
  1490. }
  1491. videoDeviceInfos.Add(videoDeviceInfo);
  1492. }
  1493. var deviceVideoChanged = DeviceVideoInfoHasChange(request.LiveOpened, videoDeviceInfos, deviceDTO);
  1494. deviceDTO.VideoDeviceInfos = videoDeviceInfos;
  1495. var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
  1496. {
  1497. DeviceCode = deviceDTO.DeviceCode,
  1498. LiveOpened = request.LiveOpened,
  1499. VideoDeviceInfos = videoDeviceInfos,
  1500. IsSync = request.IsSync
  1501. };
  1502. await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
  1503. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(deviceDTO.DeviceCode);
  1504. if (deviceVideoChanged && !string.IsNullOrWhiteSpace(deviceDTO.ShortCode))
  1505. {
  1506. _rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
  1507. {
  1508. DeviceShortCode = deviceDTO.ShortCode,
  1509. CloseDevicePush = true,
  1510. });
  1511. }
  1512. result.Success = true;
  1513. result.VideoDeviceOutputInfos = videoDeviceInfos;
  1514. return result;
  1515. }
  1516. private bool DeviceVideoInfoHasChange(bool liveOpened, List<VideoDeviceDTO> videoDeviceInfos, DeviceInfoDTO oldDeviceInfo)
  1517. {
  1518. if (liveOpened != oldDeviceInfo.LiveOpened)
  1519. {
  1520. return true;
  1521. }
  1522. if (oldDeviceInfo.VideoDeviceInfos == null || !oldDeviceInfo.VideoDeviceInfos.Any())
  1523. {
  1524. if (videoDeviceInfos.Any())
  1525. {
  1526. return true;
  1527. }
  1528. }
  1529. else if (oldDeviceInfo.VideoDeviceInfos.Count != videoDeviceInfos.Count)
  1530. {
  1531. return true;
  1532. }
  1533. else
  1534. {
  1535. foreach (var videoInfo in videoDeviceInfos)
  1536. {
  1537. var oldVideoInfo = oldDeviceInfo.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == videoInfo.VideoDeviceId);
  1538. if (oldVideoInfo == null)
  1539. {
  1540. return true;
  1541. }
  1542. if (oldVideoInfo.VideoDeviceSourceType != videoInfo.VideoDeviceSourceType
  1543. || oldVideoInfo.Width != videoInfo.Width
  1544. || oldVideoInfo.Height != videoInfo.Height)
  1545. {
  1546. return true;
  1547. }
  1548. }
  1549. }
  1550. return false;
  1551. }
  1552. private VideoDeviceDTO InitOutputInfo(VideoDeviceInfo videoDeviceInfo, bool mergedChannel, bool screenAndCamera, int maxWidth, int maxHeight)
  1553. {
  1554. // 给到设备端的输出尺寸,一定需要保持上报设备分辨率的宽高比
  1555. // CPU好的输出尺寸不能超过1080P,CPU较差的输出尺寸不能超过720P
  1556. // 单路情况,主频画面小于推荐尺寸,保持不变;主屏画面大于推荐尺寸,保持上报设备分辨率宽高比缩小
  1557. // (CPU好的情况帧率20,码率3000,最小帧率设为0(SDK自由设置)
  1558. // (CPU较差的情况)帧率15,码率2000,最小帧率设为0(SDK自由设置)
  1559. // 多路情况:1080P降到1280*720,720P降到1280*540
  1560. // 多路分流,保持上报设备分辨率宽高比缩小
  1561. // 多路合流(摄像头):640*480(CPU好的情况);640*360(CPU较差的情况)
  1562. // (CPU好的情况帧率20,码率3000,最小帧率设为2000
  1563. // (CPU较差的情况)帧率15,码率2000,最小帧率设为1000
  1564. var bestCpu = maxWidth == 1920;
  1565. var outputInfo = new VideoDeviceDTO
  1566. {
  1567. VideoDeviceId = videoDeviceInfo.VideoDeviceId,
  1568. VideoDeviceSourceType = videoDeviceInfo.VideoDeviceSourceType,
  1569. Width = videoDeviceInfo.Width,
  1570. Height = videoDeviceInfo.Height,
  1571. OutputWidth = videoDeviceInfo.Width,
  1572. OutputHeight = videoDeviceInfo.Height,
  1573. };
  1574. //输出分辨率
  1575. var width = videoDeviceInfo.Width;
  1576. var height = Math.Max(videoDeviceInfo.Height, 1);
  1577. if (!screenAndCamera)
  1578. {
  1579. //单路
  1580. if (bestCpu)
  1581. {
  1582. InitFpsAndBitrate(outputInfo, 20, 3000, 0);
  1583. InitDesktopOutputSize(outputInfo, 1920, 1080);
  1584. }
  1585. else
  1586. {
  1587. InitFpsAndBitrate(outputInfo, 15, 2000, 0);
  1588. InitDesktopOutputSize(outputInfo, 1280, 720);
  1589. }
  1590. }
  1591. else
  1592. {
  1593. if (mergedChannel)
  1594. {
  1595. //多路合流
  1596. if (bestCpu)
  1597. {
  1598. InitFpsAndBitrate(outputInfo, 20, 3000, 2000);
  1599. InitDesktopOutputSize(outputInfo, 1280, 720);
  1600. InitCameraOutputSize(outputInfo, 640, 480, true);
  1601. }
  1602. else
  1603. {
  1604. InitFpsAndBitrate(outputInfo, 15, 2000, 1000);
  1605. InitDesktopOutputSize(outputInfo, 1280, 540);
  1606. InitCameraOutputSize(outputInfo, 640, 360, true);
  1607. }
  1608. }
  1609. else
  1610. {
  1611. //多路分流
  1612. if (bestCpu)
  1613. {
  1614. InitFpsAndBitrate(outputInfo, 20, 3000, 2000);
  1615. InitDesktopOutputSize(outputInfo, 1280, 720);
  1616. InitCameraOutputSize(outputInfo, 1280, 720);
  1617. }
  1618. else
  1619. {
  1620. InitFpsAndBitrate(outputInfo, 15, 2000, 1000);
  1621. InitDesktopOutputSize(outputInfo, 1280, 540);
  1622. InitCameraOutputSize(outputInfo, 1280, 540);
  1623. }
  1624. }
  1625. }
  1626. return outputInfo;
  1627. }
  1628. private void InitFpsAndBitrate(VideoDeviceDTO outputInfo, int videoFps, int videoBitrate, int minVideoBitrate)
  1629. {
  1630. outputInfo.VideoFps = videoFps;
  1631. outputInfo.VideoBitrate = videoBitrate;
  1632. outputInfo.MinVideoBitrate = minVideoBitrate;
  1633. }
  1634. private void InitDesktopOutputSize(VideoDeviceDTO outputInfo, int maxWidth, int maxHeight)
  1635. {
  1636. if (outputInfo.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Desktop)
  1637. {
  1638. if (outputInfo.Width <= maxWidth && outputInfo.Height <= maxHeight)
  1639. {
  1640. outputInfo.OutputWidth = outputInfo.Width;
  1641. outputInfo.OutputHeight = outputInfo.Height;
  1642. }
  1643. else
  1644. {
  1645. var radio = (double)outputInfo.Width / Math.Max(outputInfo.Height, 1);
  1646. if (outputInfo.Height > maxHeight)
  1647. {
  1648. outputInfo.OutputHeight = maxHeight;
  1649. outputInfo.OutputWidth = (int)(maxHeight * radio);
  1650. }
  1651. if (outputInfo.OutputWidth > maxWidth)
  1652. {
  1653. outputInfo.OutputWidth = maxWidth;
  1654. outputInfo.OutputHeight = (int)(maxWidth / radio);
  1655. }
  1656. }
  1657. }
  1658. }
  1659. private void InitCameraOutputSize(VideoDeviceDTO outputInfo, int maxWidth, int maxHeight, bool fixedSize = false)
  1660. {
  1661. if (outputInfo.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Camera)
  1662. {
  1663. if (fixedSize)
  1664. {
  1665. outputInfo.OutputWidth = maxWidth;
  1666. outputInfo.OutputHeight = maxHeight;
  1667. }
  1668. else if (outputInfo.Width <= maxWidth && outputInfo.Height <= maxHeight)
  1669. {
  1670. outputInfo.OutputWidth = outputInfo.Width;
  1671. outputInfo.OutputHeight = outputInfo.Height;
  1672. }
  1673. else
  1674. {
  1675. var radio = (double)outputInfo.Width / Math.Max(outputInfo.Height, 1);
  1676. if (outputInfo.Height > maxHeight)
  1677. {
  1678. outputInfo.OutputHeight = maxHeight;
  1679. outputInfo.OutputWidth = (int)(maxHeight * radio);
  1680. }
  1681. if (outputInfo.OutputWidth > maxWidth)
  1682. {
  1683. outputInfo.OutputWidth = maxWidth;
  1684. outputInfo.OutputHeight = (int)(maxWidth / radio);
  1685. }
  1686. }
  1687. }
  1688. }
  1689. /// <summary>
  1690. /// 查找有效设备总数量
  1691. /// </summary>
  1692. /// <returns></returns>
  1693. public async Task<long> GetActiveDeviceCount()
  1694. {
  1695. return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
  1696. }
  1697. /// <summary>
  1698. /// 设备发送调参初始化数据
  1699. /// </summary>
  1700. /// <param name="request">调参数据请求</param>
  1701. /// <returns></returns>
  1702. public async Task<bool> SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
  1703. {
  1704. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1705. var userCode = request.ControlUserCode;
  1706. //发送控制人通知
  1707. if (string.IsNullOrWhiteSpace(userCode))
  1708. {
  1709. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1710. }
  1711. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1712. if (userDTO == null)
  1713. {
  1714. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1715. }
  1716. var notify = new DeviceParametersNotification()
  1717. {
  1718. DeviceCode = deviceCode,
  1719. IsResponse = true
  1720. };
  1721. var key = deviceCode;
  1722. var cacheControllingParameter = new CacheControllingParameter()
  1723. {
  1724. Code = userCode + "_" + deviceCode,
  1725. ProbeApplication = Newtonsoft.Json.JsonConvert.SerializeObject(request.ProbeApplication),
  1726. Parameter = Newtonsoft.Json.JsonConvert.SerializeObject(request.Parameter),
  1727. };
  1728. AddControllingParameter(key, cacheControllingParameter);
  1729. var notificationRequest = new SendNotificationRequest()
  1730. {
  1731. ClientId = userCode,
  1732. Message = notify,
  1733. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1734. NotificationType = notify.NotificationType,
  1735. TransactionType = TransactionTypeEnum.ControlParameter,
  1736. RelevanceCode = userCode,
  1737. ReceiverType = ApplicantTypeEnum.Client,
  1738. WSConnectType = WSConnectTypeEnum.ConsultationSecondWindow,
  1739. IsNeedSyn = true,
  1740. };
  1741. await _notificationService.PostMessageAsync(notificationRequest);
  1742. return true;
  1743. }
  1744. private async Task AddControllingParameter(string key, CacheControllingParameter value)
  1745. {
  1746. _controllingParameterDevices.AddOrUpdate(key, value, (a, b) => value);
  1747. if (ConfigurationManager.IsDistributed)
  1748. {
  1749. await SyncControllingParameterToMasterAsync(0, key, value);
  1750. }
  1751. }
  1752. /// <summary>
  1753. /// 获取探头和应用数据
  1754. /// </summary>
  1755. /// <param name="key">键</param>
  1756. /// <returns></returns>
  1757. private async Task<CacheControllingParameter> GetControllingParameter(string key)
  1758. {
  1759. _controllingParameterDevices.TryGetValue(key, out CacheControllingParameter value);
  1760. return await Task.FromResult<CacheControllingParameter>(value);
  1761. }
  1762. /// <summary>
  1763. /// 获取设备参数调节数据请求
  1764. /// </summary>
  1765. /// <param name="request"></param>
  1766. /// <returns></returns>
  1767. public async Task<DeviceControlParameterDataDTO> GetControlParametersAsync(GetControlParametersRequest request)
  1768. {
  1769. var deviceCode = request.DeviceCode;
  1770. //检查设备编码不为空
  1771. if (string.IsNullOrWhiteSpace(deviceCode))
  1772. {
  1773. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1774. }
  1775. _controllingParameterDevices.TryGetValue(deviceCode, out var controlParameterData);
  1776. if (controlParameterData != null)
  1777. {
  1778. return new DeviceControlParameterDataDTO()
  1779. {
  1780. DeviceCode = controlParameterData.Code,
  1781. ProbeApplication = controlParameterData.ProbeApplication,
  1782. Parameter = controlParameterData.Parameter
  1783. };
  1784. }
  1785. return null;
  1786. }
  1787. /// <summary>
  1788. /// 上报直播状态
  1789. /// </summary>
  1790. /// <param name="request">上报直播状态请求实体</param>
  1791. /// <returns></returns>
  1792. public async Task<bool> ReportLiveStateAsync(ReportLiveStateRequest request)
  1793. {
  1794. var tokenInfo = await _authenticationService.GetTokenAsync(request);
  1795. var deviceCode = tokenInfo.ClientId;
  1796. switch (request.LiveState)
  1797. {
  1798. case DeviceLiveStateEnum.Error:
  1799. case DeviceLiveStateEnum.Warning:
  1800. Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1801. break;
  1802. default:
  1803. Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1804. break;
  1805. }
  1806. if (request.LiveState == DeviceLiveStateEnum.Closed)
  1807. {
  1808. var deviceCache = CacheMaintenance.Instance.Get<IDeviceInfosManager>().Get(deviceCode);
  1809. if (deviceCache != null && !string.IsNullOrWhiteSpace(deviceCache.Code))
  1810. {
  1811. await _rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
  1812. {
  1813. DeviceShortCode = deviceCache.ShortCode,
  1814. CloseDevicePush = true,
  1815. });
  1816. }
  1817. }
  1818. else if (request.LiveState == DeviceLiveStateEnum.Pushing)
  1819. {
  1820. //开始推流,调用会诊信息,通知客户端
  1821. var r = await NoticeClientBeginPushLive(deviceCode, true);
  1822. }
  1823. return await Task.FromResult(true);
  1824. }
  1825. /// <summary>
  1826. /// 开始推流后,通知客户端
  1827. /// </summary>
  1828. /// <param name="liveRoom">房间信息</param>
  1829. /// <param name="deviceCode">设备code</param>
  1830. /// <returns></returns>
  1831. private async Task<bool> NoticeClientBeginPushLive(string deviceCode, bool isNeedSyn = false)
  1832. {
  1833. var result = false;
  1834. var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
  1835. {
  1836. DeviceCode = deviceCode
  1837. });
  1838. if (liveRoom != null)
  1839. {
  1840. var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = liveRoom.LiveRoomCode };
  1841. var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
  1842. if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode) || liveRoom.Status != LiveRoomStatus.Initiating)
  1843. {
  1844. //会诊不存在,或不在会诊中,不需要发送通知
  1845. return result;
  1846. }
  1847. if (isNeedSyn)
  1848. {
  1849. var syncInfo = new JoinInConsultationJson
  1850. {
  1851. ConsultationRecordCode = liveRoom.LiveRoomCode,
  1852. RoomCode = liveRoom.LiveRoomCode,
  1853. InitatorCode = liveRoom.InitiatorCode,
  1854. OperatorCode = deviceCode
  1855. };
  1856. await SyncToMasterAsync(SyncTypeEnum.DeviceReStartPusing, liveRoom.LiveRoomCode, syncInfo);
  1857. }
  1858. var joiner = liveRoom.DeviceInfos.FirstOrDefault(c => c.Code == deviceCode);
  1859. if (!string.IsNullOrEmpty(joiner?.Code))
  1860. {
  1861. var userInfos = liveRoom.UserInfos.Where(x => x.Code != joiner.Code && x.Status == LiveMemberStatus.Joined);
  1862. if (userInfos?.Any() == true)
  1863. {
  1864. var sortUsers = liveRoom.UserInfos.OrderByDescending(x => x.FirstJoinTime).ThenByDescending(x => x.Code).ToList();
  1865. var sortNumber = sortUsers.IndexOf(joiner);
  1866. var joinerInfo = new LiveConsultationJoinerInfo
  1867. {
  1868. Id = joiner.Code,
  1869. Name = joiner.Name,
  1870. HeadImageUrl = joiner.HeadImageToken,
  1871. //IsOnline = joiner.IsOnline,
  1872. Mute = joiner.MuteOpened,
  1873. VideoOpend = joiner.VideoOpened,
  1874. SortLevel = joiner.SortLevel,
  1875. SortNumber = sortNumber,
  1876. LiveData = new LiveData
  1877. {
  1878. RtmpPushUrl = joiner.LiveData?.RtmpPushUrl,
  1879. RtmpPullUrl = joiner.LiveData?.RtmpPullUrl,
  1880. HlsPullUrl = joiner.LiveData?.HlsPullUrl,
  1881. HttpPullUrl = joiner.LiveData?.HttpPullUrl
  1882. },
  1883. };
  1884. if (joiner.MemberType == LiveMemberEnum.Device)
  1885. {
  1886. var deviceInfo = CacheMaintenance.Instance.Get<IDeviceInfosManager>().Get(deviceCode);
  1887. Logger.WriteLineInfo($"RtcService PushHeartRateJoinMessage, roomId:{liveRoom.LiveRoomCode}, rtcRoomId:{liveRoom.RtcRoomId}, deviceCode:{deviceInfo.ShortCode}");
  1888. var videoDeviceOutputInfos = new List<VideoDeviceOutputInfo>();
  1889. if (deviceInfo.VideoDeviceInfos?.Any() == true)
  1890. {
  1891. foreach (var video in deviceInfo.VideoDeviceInfos)
  1892. {
  1893. var deviceVideoId = video.VideoDeviceId == deviceCode ? video.VideoDeviceId : $"{deviceInfo.ShortCode}_{video.VideoDeviceId}";
  1894. if (deviceInfo.VideoDeviceInfos.Count == 1 && !deviceInfo.VideoDeviceInfos.Any(x => x.VideoDeviceSourceType == (int)VideoDeviceSourceTypeEnum.Desktop))
  1895. {
  1896. deviceVideoId = deviceCode;
  1897. }
  1898. var videoInfo = joiner.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == deviceVideoId);
  1899. if (videoInfo != null)
  1900. {
  1901. var deviceVideoIdSignRequest = new GetUserSignRequest { UserId = deviceVideoId };
  1902. var videoSign = await _wingRtcService.GetUserSignAsync(deviceVideoIdSignRequest);
  1903. videoDeviceOutputInfos.Add(new VideoDeviceOutputInfo
  1904. {
  1905. VideoDeviceId = deviceVideoId,
  1906. VideoDeviceSourceType = (VideoDeviceSourceTypeEnum)video.VideoDeviceSourceType,
  1907. OutputWidth = video.OutputWidth,
  1908. OutputHeight = video.OutputHeight,
  1909. VideoFps = video.VideoFps,
  1910. VideoBitrate = video.VideoBitrate,
  1911. MinVideoBitrate = video.MinVideoBitrate,
  1912. VideoDeviceSign = videoSign?.UserSign ?? string.Empty,
  1913. LiveData = new LiveData
  1914. {
  1915. RtmpPushUrl = videoInfo.LiveData?.RtmpPushUrl,
  1916. RtmpPullUrl = videoInfo.LiveData?.RtmpPullUrl,
  1917. HlsPullUrl = videoInfo.LiveData?.HlsPullUrl,
  1918. HttpPullUrl = videoInfo.LiveData?.HttpPullUrl
  1919. },
  1920. });
  1921. }
  1922. }
  1923. }
  1924. var deviceSignRequest = new GetUserSignRequest { UserId = deviceCode };
  1925. var deviceSign = await _wingRtcService.GetUserSignAsync(deviceSignRequest);
  1926. var consultationDeviceInfo = new LiveConsultationJoinDeviceInfo()
  1927. {
  1928. MergedChannel = deviceInfo.MergedChannel,
  1929. MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
  1930. MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
  1931. VideoDeviceOutputList = videoDeviceOutputInfos,
  1932. AppId = liveRoom.SdkAppId,
  1933. DeviceCode = deviceCode,
  1934. DeviceSign = deviceSign?.UserSign ?? string.Empty,
  1935. LiveProtocol = EnvironmentConfigs.General.LiveProtocolDetail<TransactionStatusEnum>(),
  1936. };
  1937. joinerInfo.ConsultationDeviceInfo = consultationDeviceInfo;
  1938. }
  1939. Logger.WriteLineInfo($"RTCService PushHeartRateJoinMessage roomId:{liveRoom.LiveRoomCode}, joiner:{Newtonsoft.Json.JsonConvert.SerializeObject(joinerInfo)}");
  1940. var message = new HeartRateJoinConsultationNotification
  1941. {
  1942. ConsultationCode = liveRoom.LiveRoomCode,
  1943. Joiner = joinerInfo
  1944. };
  1945. //PushMessage(userInfos, message);
  1946. if (userInfos?.Any() == true)
  1947. {
  1948. //开启独立队列
  1949. var openNotifyQueueRequest = new WingInterfaceLibrary.Request.Notification.OpenNotifyQueueRequest { Module = liveRoom.LiveRoomCode };
  1950. var msgQueueId = await _notificationService.OpenNotifyQueueAsync(openNotifyQueueRequest);
  1951. var clientIds = userInfos.Select(x => x.Code).ToList();
  1952. var tokenInfos = CacheMaintenance.Instance.Get<ITokensManager>().Where(x => clientIds.Contains(x.ClientId));
  1953. if (tokenInfos != null && tokenInfos.Any())
  1954. {
  1955. Logger.WriteLineInfo($"RtcService PushMessage, roomId:{liveRoom.LiveRoomCode}, type:{message.NotificationType.ToString()}, receivers:{string.Join(";", tokenInfos.Select(x => x.AccountName).Distinct())}");
  1956. }
  1957. var notificationRequest = new BroadcastNotificationRequest
  1958. {
  1959. MsgQueueId = msgQueueId,
  1960. ClientIds = clientIds,
  1961. Message = message,
  1962. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message),
  1963. NotificationType = message.NotificationType,
  1964. TransactionType = TransactionTypeEnum.Consultion,
  1965. RelevanceCode = liveRoom.LiveRoomCode,
  1966. ReceiverType = ApplicantTypeEnum.Client,
  1967. WSConnectType = WSConnectTypeEnum.ConsultationSecondWindow,
  1968. IsNeedSyn = true
  1969. };
  1970. var res = await _notificationService.BroadcastMessageAsync(notificationRequest);
  1971. }
  1972. }
  1973. }
  1974. result = true;
  1975. }
  1976. return result;
  1977. }
  1978. /// <summary>
  1979. /// 获取实时音视频参数
  1980. /// </summary>
  1981. /// <param name="request">获取实时音视频参数请求实体</param>
  1982. /// <returns></returns>
  1983. public async Task<CreateLiveRoomInfoResult> CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
  1984. {
  1985. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
  1986. var userCode = Guid.NewGuid().ToString("N");
  1987. var liveProtocol = EnvironmentConfigs.General.LiveProtocolDetail<TransactionStatusEnum>();
  1988. var resultData = new CreateLiveRoomInfoResult
  1989. {
  1990. UserCode = userCode,
  1991. AppId = GetAppId(),
  1992. LiveProtocol = liveProtocol,
  1993. };
  1994. if (liveProtocol == TransactionStatusEnum.TRTC || liveProtocol == TransactionStatusEnum.VRTC)
  1995. {
  1996. var getUserSignRequest = new GetUserSignRequest
  1997. {
  1998. UserId = userCode,
  1999. };
  2000. var getUserSignResult = await _wingRtcService.GetUserSignAsync(getUserSignRequest);
  2001. var userSign = getUserSignResult.UserSign;
  2002. var getRoomIdRequest = new GetRoomIdRequest
  2003. {
  2004. UniqueId = userCode,
  2005. };
  2006. var getRoomIdResult = await _wingRtcService.GetRoomIdAsync(getRoomIdRequest);
  2007. var intRoomNo = (int)getRoomIdResult.RoomId;
  2008. resultData.UserSign = userSign;
  2009. resultData.RoomNo = intRoomNo;
  2010. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
  2011. }
  2012. else
  2013. {
  2014. var rtmpResult = await _rtmpService.GetChannelAsync(new GetChannelRequest { });
  2015. if (rtmpResult != null)
  2016. {
  2017. resultData.LiveData = new LiveDataDTO
  2018. {
  2019. RtmpPushUrl = rtmpResult.PushUrl,
  2020. RtmpPullUrl = rtmpResult.RtmpPullUrl,
  2021. HlsPullUrl = rtmpResult.HlsPullUrl,
  2022. HttpPullUrl = rtmpResult.HttpPullUrl,
  2023. };
  2024. }
  2025. }
  2026. var rtcType = EnvironmentConfigManager.GetParammeter<StringParameter>("Rtc", "RTCType").Value;
  2027. var _isRTCSelf = (rtcType == "VRTC" ? true : false);
  2028. resultData.IsTrtc = _isRTCSelf;
  2029. return resultData;
  2030. }
  2031. /// <summary>
  2032. /// Get the trtc app id
  2033. /// </summary>
  2034. /// <returns>string</returns>
  2035. private int GetAppId()
  2036. {
  2037. var appIdStr = EnvironmentConfigManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
  2038. int.TryParse(appIdStr, out int appId);
  2039. if (appId <= 0)
  2040. {
  2041. appId = 1400299969;
  2042. }
  2043. return appId;
  2044. }
  2045. private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> clientIds, NotificationDTO message)
  2046. {
  2047. var broadcastNotificationRequest = new BroadcastNotificationRequest
  2048. {
  2049. ClientIds = clientIds,
  2050. Message = message,
  2051. TransactionType = TransactionTypeEnum.Live,
  2052. RelevanceCode = roomId,
  2053. ReceiverType = ApplicantTypeEnum.Client,
  2054. WSConnectType = WSConnectTypeEnum.Default
  2055. };
  2056. return await _notificationService.BroadcastMessageAsync(broadcastNotificationRequest);
  2057. }
  2058. // /// <summary>
  2059. // /// 拒绝远程控制
  2060. // /// </summary>
  2061. // /// <param name="request"></param>
  2062. // /// <returns></returns>
  2063. // public async Task<bool> RejectRemoteControl(RemoteControlRequest request)
  2064. // {
  2065. // string deviceCode = await GetClientIdByTokenAsync(request.Token);
  2066. // string userCode = request.ControlUserCode;
  2067. // //发送控制人通知
  2068. // if (string.IsNullOrWhiteSpace(userCode))
  2069. // {
  2070. // ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  2071. // }
  2072. // var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  2073. // if (userDTO == null)
  2074. // {
  2075. // ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  2076. // }
  2077. // var notify = new DeviceRejectRemoteControlNotification()
  2078. // {
  2079. // DeviceCode = deviceCode,
  2080. // };
  2081. // var notificationRequest = new SendNotificationRequest()
  2082. // {
  2083. // ClientId = userCode,
  2084. // Message = notify,
  2085. // JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  2086. // NotificationType = notify.NotificationType,
  2087. // TransactionType = TransactionTypeEnum.RemoteControl,
  2088. // RelevanceCode = userCode,
  2089. // ReceiverType = ApplicantTypeEnum.Client
  2090. // };
  2091. // await _notificationService.PostMessageAsync(notificationRequest);
  2092. // //更改房间调参状态
  2093. // // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  2094. // // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  2095. // // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  2096. // // {
  2097. // // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  2098. // // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  2099. // // }
  2100. // // var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  2101. // // await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  2102. // return true;
  2103. // }
  2104. // /// <summary>
  2105. // /// 断开远程控制
  2106. // /// </summary>
  2107. // /// <param name="request"></param>
  2108. // /// <returns></returns>
  2109. // public async Task<bool> DisconnectRemoteControl(RemoteControlRequest request)
  2110. // {
  2111. // string deviceCode = await GetClientIdByTokenAsync(request.Token);
  2112. // string userCode = request.ControlUserCode;
  2113. // //发送控制人通知
  2114. // if (string.IsNullOrWhiteSpace(userCode))
  2115. // {
  2116. // ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  2117. // }
  2118. // var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  2119. // if (userDTO == null)
  2120. // {
  2121. // ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  2122. // }
  2123. // var notify = new DeviceDisconnectRemoteControlNotification()
  2124. // {
  2125. // DeviceCode = deviceCode,
  2126. // };
  2127. // var notificationRequest = new SendNotificationRequest()
  2128. // {
  2129. // ClientId = userCode,
  2130. // Message = notify,
  2131. // JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  2132. // NotificationType = notify.NotificationType,
  2133. // TransactionType = TransactionTypeEnum.RemoteControl,
  2134. // RelevanceCode = userCode,
  2135. // ReceiverType = ApplicantTypeEnum.Client
  2136. // };
  2137. // await _notificationService.PostMessageAsync(notificationRequest);
  2138. // // var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  2139. // // await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  2140. // return true;
  2141. // }
  2142. public async Task<bool> UploadConsultationDataAsync(UploadConsultationDataRequest request)
  2143. {
  2144. var deviceInfo = await GetDeviceByTokenAsync(request);
  2145. var consultationCode = request.ConsultationCode;
  2146. if (string.IsNullOrWhiteSpace(consultationCode))
  2147. {
  2148. ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
  2149. }
  2150. if (string.IsNullOrWhiteSpace(request.FileToken))
  2151. {
  2152. ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
  2153. }
  2154. var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
  2155. var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
  2156. if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
  2157. {
  2158. ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
  2159. }
  2160. var dataDTO = new RemedicalInfoDTO();
  2161. dataDTO.DeviceCode = deviceInfo.DeviceCode;
  2162. dataDTO.RecordCode = consultationRecord.ConsultationCode;
  2163. dataDTO.ApplicationCategory = request.ApplicationCategory;
  2164. dataDTO.Application = request.Application;
  2165. dataDTO.TerminalImages = new TerminalImageDTO();
  2166. var originImageUrl = request.FileToken;
  2167. dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
  2168. dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
  2169. dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
  2170. dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
  2171. dataDTO.TerminalImages.ImageSize = request.FileSize;
  2172. dataDTO.FileDataType = request.FileDataType;
  2173. dataDTO.MeasuredResult = request.MeasuredResult;
  2174. dataDTO.CommentResult = request.CommentResult;
  2175. dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
  2176. dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
  2177. //更新会诊记录
  2178. if (consultationRecord.ConsultationFileList == null)
  2179. {
  2180. consultationRecord.ConsultationFileList = new List<ConsultationFileDTO>();
  2181. }
  2182. var consultationFileDTO = new ConsultationFileDTO
  2183. {
  2184. SourceUrl = originImageUrl,
  2185. CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
  2186. PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
  2187. FileDataType = request.FileDataType,
  2188. CreateTime = DateTime.UtcNow,
  2189. ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
  2190. RemedicalCode = dataDTO.RemedicalCode
  2191. };
  2192. consultationRecord.ConsultationFileList.Add(consultationFileDTO);
  2193. var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
  2194. return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
  2195. }
  2196. /// <summary>
  2197. /// 手机个人添加超声机,PC个人短码添加设备
  2198. /// </summary>
  2199. /// <param name="request">请求实体</param>
  2200. /// <returns>是否成功</returns>
  2201. /// <value>true</value>
  2202. /// <errorCodes></errorCodes>
  2203. public async Task<bool> ScanBindDeviceAsync(ScanBindDeviceRequest request)
  2204. {
  2205. //验证
  2206. var userCode = await GetClientIdByTokenAsync(request.Token);
  2207. //查询用户是否存在
  2208. var userInfoDO = await _userServiceProxy.FindUserAsync(new FindUserRequest() { Code = userCode });
  2209. if (userInfoDO == null)
  2210. {
  2211. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  2212. }
  2213. // if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  2214. // {
  2215. // ThrowCustomerException(CustomerRpcCode.UserHaveNoOrg, "UserHaveNoOrg");
  2216. // }
  2217. // //只给非机构负责人用
  2218. // if (userInfoDO.IsDirector)
  2219. // {
  2220. // ThrowCustomerException(CustomerRpcCode.OnlyCommonUserUsed, "Only common user used");
  2221. // }
  2222. //获取用户机构和所属部门
  2223. var organizationCode = userInfoDO.RootOrganizationCode;
  2224. var departmentCode = userInfoDO.OrganizationCode;
  2225. if (userInfoDO.RootOrganizationCode == userInfoDO.OrganizationCode)
  2226. {
  2227. //相同表示没有部门
  2228. departmentCode = "";
  2229. }
  2230. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  2231. if (deviceDb == null)
  2232. {
  2233. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  2234. }
  2235. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  2236. {
  2237. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  2238. }
  2239. if (string.IsNullOrEmpty(deviceDb.Description) || deviceDb.Description == deviceDb.Name)
  2240. {
  2241. if (!string.IsNullOrWhiteSpace(request.Description))
  2242. {
  2243. deviceDb.Description = request.Description;
  2244. }
  2245. }
  2246. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  2247. if (!string.IsNullOrEmpty(deviceDb.Description) && !string.IsNullOrEmpty(request.Description) && deviceDb.Description != request.Description)
  2248. {
  2249. ThrowCustomerException(CustomerRpcCode.DeviceDescriptionNotModify, "Device description not modify");
  2250. }
  2251. // //判断设备绑定机构是否跟用户的机构一致
  2252. // //判断父子级,父级可以绑定子集机构的设备 杏聆荟平台可以绑定任何设备
  2253. // var orgCodes = new List<string> { userInfoDO.RootOrganizationCode };
  2254. // var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
  2255. // if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
  2256. // {
  2257. // orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
  2258. // }
  2259. // if (userInfoDO.RootOrganizationCode != "VINNO_FIS" && !string.IsNullOrEmpty(deviceDb.OrganizationCode) && !orgCodes.Contains(deviceDb.OrganizationCode))
  2260. // {
  2261. // ThrowCustomerException(CustomerRpcCode.OrganizationCodeInconformity, "Organization code inconformity");
  2262. // }
  2263. //用户和设备分属不同组织架构,用户扫描二维码提示“该设备归属其他部门,暂时无法添加”
  2264. // if (!string.IsNullOrEmpty(deviceDb.DepartmentCode) && !string.IsNullOrEmpty(departmentCode) && departmentCode != deviceDb.DepartmentCode)
  2265. // {
  2266. // ThrowCustomerException(CustomerRpcCode.DeviceBelongOtherDepartment, "Device belong other department");
  2267. // }
  2268. // //设备有组织架构,用户无组织架构时,用户扫描二维码提示“该设备归属其他部门,暂时无法添加”
  2269. // if (!string.IsNullOrEmpty(deviceDb.DepartmentCode) && string.IsNullOrEmpty(departmentCode))
  2270. // {
  2271. // ThrowCustomerException(CustomerRpcCode.DeviceBelongOtherDepartment, "Device belong other department");
  2272. // }
  2273. try
  2274. {
  2275. var userCodes = new List<string>() { userCode };
  2276. //新设备,绑定机构,且绑定到机构管理员名下
  2277. if (string.IsNullOrEmpty(deviceDb.OrganizationCode))
  2278. {
  2279. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  2280. {
  2281. deviceDb.OrganizationCode = "VINNO_FIS";
  2282. if (string.IsNullOrEmpty(deviceDb.Name))
  2283. {
  2284. deviceDb.Name = userInfoDO.OrganizationName + "_" + deviceDb.ShortCode;
  2285. }
  2286. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  2287. }
  2288. else
  2289. {
  2290. //添加机构管理员绑定设备信息
  2291. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == "VINNO_FIS") ? true : false;
  2292. if (string.IsNullOrEmpty(deviceDb.Name))
  2293. {
  2294. deviceDb.Name = userInfoDO.OrganizationName + "_" + deviceDb.ShortCode;
  2295. }
  2296. deviceDb.DepartmentCode = departmentCode;
  2297. deviceDb.OrganizationCode = organizationCode;
  2298. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  2299. if (isInvented && !string.IsNullOrWhiteSpace(organizationCode)) //虚拟机构改为正常机构
  2300. {
  2301. var newOrgCode = string.IsNullOrWhiteSpace(departmentCode) ? organizationCode : departmentCode;
  2302. // //迁移数据超声机上传检查记录
  2303. // await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  2304. // //迁移数据超声机上传病人
  2305. // await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  2306. _modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
  2307. }
  2308. //查询机构信息,以及机构管理员
  2309. var organizationCacheDTO = CacheMaintenance.Instance.Get<IOrganizationsManager>().Get(organizationCode) ?? new CacheOrganizationDTO();
  2310. if (organizationCacheDTO.Directors?.Count > 0)
  2311. {
  2312. userCodes.AddRange(organizationCacheDTO.Directors);
  2313. userCodes = userCodes.Distinct().ToList();
  2314. }
  2315. }
  2316. }
  2317. else
  2318. {
  2319. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  2320. }
  2321. var updateResult = await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  2322. {
  2323. DeviceCodes = new List<string>() { deviceDb.DeviceCode },
  2324. OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
  2325. UserCodes = userCodes
  2326. });
  2327. var result = updateResult > 0 ? true : false;
  2328. return result;
  2329. }
  2330. catch (Exception ex)
  2331. {
  2332. Logger.WriteLineError($"ScanBindDeviceAsync error {ex}");
  2333. return false;
  2334. }
  2335. }
  2336. /// <summary>
  2337. /// 新增设备画面尺寸
  2338. /// </summary>
  2339. /// <returns>是否操作成功</returns>
  2340. public async Task<bool> ReportBrandModelOutputConfigAsync(ReportBrandModelOutputConfigRequest request)
  2341. {
  2342. return await _deviceInfoDBServiceProxy.AddBrandModelOutputConfigAsync(new AddBrandModelOutputConfigDBRequest
  2343. {
  2344. Brand = request.Brand,
  2345. Model = request.Model,
  2346. ShortCode = request.ShortCode,
  2347. VideoWidth = request.VideoWidth,
  2348. VideoHeight = request.VideoHeight
  2349. });
  2350. }
  2351. /// <summary>
  2352. /// 获取设备画面尺寸
  2353. /// </summary>
  2354. /// <returns>是否操作成功</returns>
  2355. public async Task<List<BrandModelOutputConfigDTO>> SyncBrandModelOutputConfigAsync(SyncBrandModelOutputConfigRequest request)
  2356. {
  2357. var configs = await _deviceInfoDBServiceProxy.GetBrandModelOutputConfigAsync(new GetBrandModelOutputConfigDBRequest
  2358. {
  2359. Brand = request.Brand,
  2360. Model = request.Model,
  2361. ShortCode = request.ShortCode,
  2362. });
  2363. var newBrandModelList = new List<BrandModelOutputConfigDTO>();
  2364. var first = configs.FirstOrDefault(w => w.IsSelect);
  2365. if (first != null)
  2366. {
  2367. newBrandModelList.Add(first);
  2368. }
  2369. foreach (var config in configs)
  2370. {
  2371. if (!newBrandModelList.Any(a => a.VideoWidth == config.VideoWidth && a.VideoHeight == config.VideoHeight))
  2372. {
  2373. newBrandModelList.Add(new BrandModelOutputConfigDTO
  2374. {
  2375. VideoWidth = config.VideoWidth,
  2376. VideoHeight = config.VideoHeight
  2377. });
  2378. }
  2379. }
  2380. return newBrandModelList;
  2381. }
  2382. /// <summary>
  2383. /// 获取品牌列表
  2384. /// </summary>
  2385. /// <returns></returns>
  2386. public Task<List<string>> GetBrandsAsync(GetBrandsRequest request)
  2387. {
  2388. return _deviceInfoDBServiceProxy.GetBrandsAsync();
  2389. }
  2390. /// <summary>
  2391. /// 获取品牌型号列表
  2392. /// </summary>
  2393. /// <returns></returns>
  2394. public Task<List<string>> GetModelsAsync(GetModelsRequest request)
  2395. {
  2396. return _deviceInfoDBServiceProxy.GetModelsAsync(new GetModelsDBRequest
  2397. {
  2398. Brand = request.Brand
  2399. });
  2400. }
  2401. /// <summary>
  2402. /// 修改用户急诊设备
  2403. /// </summary>
  2404. /// <param name="request">修改用户急诊设备请求</param>
  2405. /// <returns></returns>
  2406. public async Task<bool> ModifyEmergencyDeviceCodeAsync(ModifyEmergencyDeviceCodeRequest request)
  2407. {
  2408. var userCode = await GetClientIdByTokenAsync(request.Token);
  2409. return await _userServiceProxy.UpdateEmergencyDeviceCodeDBAsync(new UpdateEmergencyDeviceCodeDBRequest
  2410. {
  2411. UserCode = userCode,
  2412. EmergencyDeviceCode = request.EmergencyDeviceCode,
  2413. });
  2414. }
  2415. /// <summary>
  2416. /// 批量新增打印机驱动
  2417. /// </summary>
  2418. /// <param name="request">请求实体</param>
  2419. /// <returns>是否成功</returns>
  2420. public async Task<bool> BatchInsertDevicePrintersDataAsync(MigrateDevicePrinterRequest request)
  2421. {
  2422. return await _deviceInfoDBServiceProxy.BatchInsertDevicePrintersDataAsync(request);
  2423. }
  2424. /// <summary>
  2425. /// 批量新增补丁包
  2426. /// </summary>
  2427. /// <param name="request">请求实体</param>
  2428. /// <returns>是否成功</returns>
  2429. public async Task<bool> BatchInsertDevicePatchsDataAsync(MigrateDevicePatchRequest request)
  2430. {
  2431. return await _deviceInfoDBServiceProxy.BatchInsertDevicePatchsDataAsync(request);
  2432. }
  2433. /// <summary>
  2434. /// 获取个人绑定设备分页
  2435. /// </summary>
  2436. /// <param name="request"></param>
  2437. /// <returns></returns>
  2438. public async Task<PageCollection<SelectItemDTO>> GetPersonDeviceDropdownPageAsync(GetPersonDeviceDropdownPageRequest request)
  2439. {
  2440. //验证
  2441. var userCode = await GetClientIdByTokenAsync(request.Token);
  2442. //查询用户是否存在
  2443. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  2444. if (userInfoDO == null)
  2445. {
  2446. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  2447. }
  2448. // //查询用户的医院是否存在
  2449. // if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  2450. // {
  2451. // ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  2452. // }
  2453. var selectItemDTOList = new List<SelectItemDTO>();
  2454. //普通用户,查询用户绑定的设备
  2455. var dbPage = new PageResult<DeviceInfoDTO>();
  2456. var dbRequest = new FindDeviceInfoPageRequest()
  2457. {
  2458. PageIndex = request.PageIndex,
  2459. PageSize = request.PageSize,
  2460. KeyWord = request.KeyWord,
  2461. UserCode = userCode,
  2462. IsIncloudReferral = request.IsIncloudReferral
  2463. };
  2464. dbRequest.DeviceCodes = userInfoDO.BindDevices;
  2465. dbRequest.RestrictOrgCodes = request.RestrictOrgCodes;
  2466. dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
  2467. if (dbPage?.PageData?.Count > 0)
  2468. {
  2469. selectItemDTOList = dbPage.PageData.Select(c => new SelectItemDTO()
  2470. {
  2471. Key = c.DeviceCode,
  2472. Value = string.IsNullOrWhiteSpace(c.Description) ? c.Name : c.Description
  2473. }).ToList();
  2474. }
  2475. if (!selectItemDTOList.Any())
  2476. {
  2477. return new PageCollection<SelectItemDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<SelectItemDTO>() };
  2478. }
  2479. var pagedResult = new PageCollection<SelectItemDTO>
  2480. {
  2481. CurrentPage = request.PageIndex,
  2482. PageSize = request.PageSize,
  2483. DataCount = dbPage.TotalCount,
  2484. PageData = selectItemDTOList
  2485. };
  2486. return pagedResult;
  2487. }
  2488. /// <summary>
  2489. /// 根据名称查询设备信息
  2490. /// </summary>
  2491. /// <param name="request">请求实体</param>
  2492. /// <returns>设备信息</returns>
  2493. public async Task<DeviceInfoDTO> FindDeviceInfoByNameAsync(FindDeviceInfoByNameRequest request)
  2494. {
  2495. var result = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.Name);
  2496. return result;
  2497. }
  2498. /// <summary>
  2499. /// 新增老版本设备
  2500. /// </summary>
  2501. /// <param name="request"></param>
  2502. /// <returns></returns>
  2503. public async Task<DeviceInfoDTO> AddOldVersionDeviceAsync(AddOldVersionDeviceRequest request)
  2504. {
  2505. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.TerminalName);
  2506. if (deviceInfo != null && !string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  2507. {
  2508. return deviceInfo;
  2509. }
  2510. var organizationName = request.OrganizationName;
  2511. var organizationCode = "";
  2512. //查询医院是否存在 不存在则新增医院
  2513. var orgRequest = new GetOrganizationByNameDBRequest { OrganizationName = request.OrganizationName };
  2514. var organizationDetail = await _organizationDBService.GetOrganizationDetailByNameAsync(orgRequest);
  2515. if (organizationDetail == null || string.IsNullOrWhiteSpace(organizationDetail.OrganizationCode))
  2516. {
  2517. //创建机构
  2518. organizationCode = CodeCreator.CreateCode("Organization");
  2519. var organizationDB = new OrganizationDTO();
  2520. organizationDB.OrganizationCode = organizationCode;
  2521. organizationDB.RootCode = organizationCode;
  2522. organizationDB.State = OrganizationStateEnum.Audited;
  2523. organizationDB.ReferralOrganizationCodes = null;
  2524. organizationDB.OrganizationName = organizationName;
  2525. if (organizationName.Contains("动物") || organizationName.Contains("宠物") || organizationName.ToLower().Contains("animal") || organizationName.ToLower().Contains("pet"))
  2526. {
  2527. organizationDB.PatientType = OrganizationPatientTypeEnum.Animals;
  2528. }
  2529. var dbRequest = new CreateOrganizationsDBRequest();
  2530. dbRequest.Infos = new List<TableDataItem<OrganizationDTO>>();
  2531. dbRequest.Infos.Add(new TableDataItem<OrganizationDTO> { Data = organizationDB });
  2532. await _organizationDBService.CreateOrganizationsAsync(dbRequest);
  2533. }
  2534. else
  2535. {
  2536. organizationCode = organizationDetail.OrganizationCode;
  2537. }
  2538. var deviceDto = new DeviceInfoDTO()
  2539. {
  2540. SerialNumber = "",
  2541. Name = request.TerminalName,
  2542. Password = request.TerminalPassword,
  2543. OrganizationCode = organizationCode,
  2544. DeviceModel = request.TerminalModel,
  2545. IsEncryptedShow = false,
  2546. MergedChannel = _isMergedChannel,
  2547. DeviceType = "US",
  2548. };
  2549. var shortCode = deviceDto.ShortCode;
  2550. for (var i = 0; i < 5; i++)
  2551. {
  2552. shortCode = GenerateShortCode();
  2553. if (!string.IsNullOrWhiteSpace(shortCode))
  2554. {
  2555. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  2556. if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
  2557. {
  2558. break;
  2559. }
  2560. }
  2561. shortCode = string.Empty;
  2562. }
  2563. deviceDto.ShortCode = shortCode;
  2564. if (string.IsNullOrWhiteSpace(deviceDto.OrganizationCode))
  2565. {
  2566. deviceDto.OrganizationCode = "VINNO_FIS";
  2567. }
  2568. deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  2569. {
  2570. Data = deviceDto
  2571. });
  2572. return deviceDto;
  2573. }
  2574. /// <summary>
  2575. /// 获取license信息列表
  2576. /// </summary>
  2577. /// <param name="request"></param>
  2578. /// <returns></returns>
  2579. public async Task<IList<LicenseInfoBasicDTO>> GetLicenseInfoListAsync(TokenRequest request)
  2580. {
  2581. var dataResult = await _deviceInfoDBServiceProxy.GetLicenseInfoListDBAsync(request);
  2582. return dataResult;
  2583. }
  2584. /// <summary>
  2585. /// 保存License信息数据
  2586. /// </summary>
  2587. /// <param name="request"></param>
  2588. /// <returns></returns>
  2589. public async Task<bool> SaveLicenseInfoListAsync(SaveLicenseInfoRequest request)
  2590. {
  2591. var dataResult = await _deviceInfoDBServiceProxy.SaveLicenseInfoListDBAsync(request);
  2592. return dataResult;
  2593. }
  2594. /// <summary>
  2595. /// 保存Dongle信息数据
  2596. /// </summary>
  2597. /// <param name="request"></param>
  2598. /// <returns></returns>
  2599. public async Task<bool> SaveDongleInfoListAsync(SaveDongleInfoRequest request)
  2600. {
  2601. var dataResult = await _deviceInfoDBServiceProxy.SaveDongleInfoListDBAsync(request);
  2602. return dataResult;
  2603. }
  2604. }
  2605. }