DeviceService.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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.Enum.CommentEnum;
  33. using WingInterfaceLibrary.DTO.RTC;
  34. using Newtonsoft.Json;
  35. using WingInterfaceLibrary.Notifications.Live;
  36. using WingInterfaceLibrary.Enum.NotificationEnum;
  37. using WingInterfaceLibrary.DTO.LiveRoom;
  38. using WingInterfaceLibrary.Request.DBRequest;
  39. using WingInterfaceLibrary.DTO.Record;
  40. using WingInterfaceLibrary.DTO.Consultation;
  41. namespace WingDeviceService.Service
  42. {
  43. /// <summary>
  44. /// 设备管理服务
  45. /// </summary>
  46. public partial class DeviceService : JsonRpcService, IDeviceService
  47. {
  48. private IUserDBService _userServiceProxy;
  49. private IDeviceInfoDBService _deviceInfoDBServiceProxy;
  50. private IAuthenticationService _authenticationService;
  51. private IOrganizationDBService _organizationDBService;
  52. private INotificationService _notificationService;
  53. private IRecordsInfoDBService _recordsInfoDBService;
  54. private IPatientInfoDBService _patientInfoDBService;
  55. private IDiagnosisModuleDBService _diagnosisModuleService;
  56. private IRemedicalService _remedicalService;
  57. private IWingRtcService _rtcService;
  58. private int _heartRateSeconds;
  59. private DeviceHeartRateManager _deviceHeartRateManager;
  60. private string _webSocketUrl = string.Empty;
  61. private int _liveConsultationRateSeconds = 0;
  62. private bool _isRTCSelf = false;
  63. private int _sdkAppId = 0;
  64. private int _remoteControlAskTimeoutSec = 0;
  65. private int _reportStateIntervalSeconds = 0;
  66. private int _reportStateTimeout = 0;
  67. private ILiveConsultationService _liveConsultationService;
  68. private IConsultationRecordDBService _consultationRecordDBService;
  69. private IRemedicalDBService _remedicalDBService;
  70. /// <summary>
  71. /// Init service
  72. /// </summary>
  73. public override void Load(JsonRpcClientPool jsonRpcClientPool)
  74. {
  75. base.Load(jsonRpcClientPool);
  76. _userServiceProxy = GetProxy<IUserDBService>();
  77. _authenticationService = GetProxy<IAuthenticationService>();
  78. _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
  79. _organizationDBService = GetProxy<IOrganizationDBService>();
  80. _notificationService = GetProxy<INotificationService>();
  81. _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
  82. _patientInfoDBService = GetProxy<IPatientInfoDBService>();
  83. _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
  84. _remedicalService = GetProxy<IRemedicalService>();
  85. _rtcService = GetProxy<IWingRtcService>();
  86. _liveConsultationService = GetProxy<ILiveConsultationService>();
  87. _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
  88. _remedicalDBService = GetProxy<IRemedicalDBService>();
  89. _heartRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
  90. _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
  91. _webSocketUrl = ConfigurationManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
  92. _liveConsultationRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "HeartRateSeconds").Value;
  93. _isRTCSelf = ConfigurationManager.GetParammeter<BoolParameter>("Rtc", "IsSelf").Value;
  94. var sdkAppIdString = ConfigurationManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
  95. if (int.TryParse(sdkAppIdString, out int sdkAppId))
  96. {
  97. _sdkAppId = sdkAppId;
  98. }
  99. _remoteControlAskTimeoutSec = ConfigurationManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
  100. var _reportStateIntervalSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateIntervalSeconds").Value;
  101. var _reportStateTimeout = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateTimeout").Value;
  102. }
  103. /// <summary>
  104. /// 设备心跳
  105. /// </summary>
  106. /// <param name="request"></param>
  107. /// <returns></returns>
  108. public async Task<bool> HeartRateAsync(TokenRequest request)
  109. {
  110. _deviceHeartRateManager.AddOrUpdate(request.Token);
  111. var result = SetOnlineState(request.Token, true);
  112. return result;
  113. }
  114. private bool SetOnlineState(string token, bool isOnline)
  115. {
  116. return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
  117. }
  118. /// <summary>
  119. /// 添加分享设备关联用户请求
  120. /// </summary>
  121. /// <param name="request"></param>
  122. /// <returns></returns>
  123. public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
  124. {
  125. var userCodes = request.UserCodes;
  126. var deviceCode = request.DeviceCode;
  127. //检查设备编码不为空
  128. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  129. {
  130. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  131. }
  132. if (userCodes == null || userCodes.Count <= 0)
  133. {
  134. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  135. }
  136. //查询设备对象
  137. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  138. if (deviceDb == null)
  139. {
  140. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  141. }
  142. foreach (var userCode in userCodes)
  143. {
  144. var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
  145. if (existUser == null)
  146. {
  147. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  148. }
  149. }
  150. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  151. {
  152. DeviceCodes = new List<string> { deviceCode },
  153. UserCodes = userCodes.ToList()
  154. });
  155. return true;
  156. }
  157. /// <summary>
  158. /// 根据设备code获取设备信息
  159. /// </summary>
  160. /// <param name="request">设备code请求实体</param>
  161. /// <returns>返回查询到的设备对象信息</returns>
  162. public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
  163. {
  164. //验证
  165. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  166. {
  167. ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
  168. }
  169. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  170. if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
  171. {
  172. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  173. }
  174. //根据机构编号查询机构名称
  175. var organizationName = "";
  176. if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
  177. {
  178. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
  179. organizationName = organization?.OrganizationName ?? string.Empty;
  180. }
  181. //根据机构编号查询科室名称
  182. var departmentName = "";
  183. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  184. {
  185. var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
  186. departmentName = department?.OrganizationName ?? string.Empty;
  187. }
  188. //是否在线 todo
  189. var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
  190. var result = new DeviceExtendInfoDTO()
  191. {
  192. DepartmentName = departmentName,
  193. OrganizationName = organizationName,
  194. IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
  195. DeviceCode = deviceDb.DeviceCode,
  196. SerialNumber = deviceDb.SerialNumber,
  197. Name = deviceDb.Name,
  198. Description = deviceDb.Description,
  199. DeviceModel = deviceDb.DeviceModel,
  200. DeviceType = deviceDb.DeviceType,
  201. HeadPicUrl = deviceDb.HeadPicUrl,
  202. DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
  203. SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
  204. OrganizationCode = deviceDb.OrganizationCode,
  205. DepartmentCode = deviceDb.DepartmentCode,
  206. ShortCode = deviceDb.ShortCode,
  207. LanguageConfigs = deviceTypeModel.LanguageConfigs
  208. };
  209. return result;
  210. }
  211. /// <summary>
  212. /// 根据设备动态唯一码获取设备信息
  213. /// </summary>
  214. /// <param name="request"></param>
  215. /// <returns></returns>
  216. public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
  217. {
  218. //验证
  219. if (string.IsNullOrWhiteSpace(request.ShortCode))
  220. {
  221. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
  222. }
  223. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  224. if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
  225. {
  226. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  227. }
  228. return await MapToExtendDTO(deviceDb);
  229. }
  230. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
  231. {
  232. throw new System.NotImplementedException();
  233. }
  234. public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
  235. {
  236. var userCodes = request.UserCodes;
  237. var deviceCode = request.DeviceCode;
  238. //检查设备编码不为空
  239. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  240. {
  241. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  242. }
  243. //用户编码集合检查
  244. if (userCodes == null || userCodes.Count <= 0)
  245. {
  246. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  247. }
  248. //查询设备对象
  249. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  250. if (deviceDb == null)
  251. {
  252. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  253. }
  254. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  255. foreach (var userCode in userCodes)
  256. {
  257. var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
  258. if (user != null)
  259. {
  260. if (user.BindDevices.Contains(deviceCode))
  261. {
  262. user.BindDevices.Remove(deviceCode);
  263. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  264. {
  265. Data = user.MappingTo<UserPasswordDTO>(),
  266. });
  267. }
  268. }
  269. }
  270. if (updateUsers.Count > 0)
  271. {
  272. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  273. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  274. }
  275. return true;
  276. }
  277. /// <summary>
  278. /// 机构设备移除-根据机构code和设备code解除其绑定关系
  279. /// </summary>
  280. /// <param name="request">移除设备请求实体</param>
  281. /// <returns>移除是否成功:true-成功;false-失败</returns>
  282. public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
  283. {
  284. //验证
  285. if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
  286. {
  287. ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
  288. }
  289. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  290. if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
  291. {
  292. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
  293. }
  294. //根据设备code和机构code查询相关数据,查到则删除关联
  295. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  296. {
  297. deviceDb.DepartmentCode = "";
  298. deviceDb.OrganizationCode = "";
  299. }
  300. else
  301. {
  302. deviceDb.OrganizationCode = "";
  303. }
  304. bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  305. return removeDeviceResult;
  306. }
  307. private async Task<string> GetClientIdByTokenAsync(string token)
  308. {
  309. var request = new TokenRequest() { Token = token };
  310. var result = await _authenticationService.GetTokenAsync(request);
  311. return result.ClientId; //return User code
  312. }
  313. /// <summary>
  314. /// 查询个人名下所有设备列表接口
  315. /// </summary>
  316. /// <param name="request">查询个人名下所有设备列表请求实体</param>
  317. /// <returns>返回设备信息列表</returns>
  318. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
  319. {
  320. //验证
  321. var userCode = await GetClientIdByTokenAsync(request.Token);
  322. //查询用户是否存在
  323. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  324. if (userInfoDO == null)
  325. {
  326. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  327. }
  328. //查询用户的医院是否存在
  329. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  330. {
  331. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  332. }
  333. var deviceInfoDOList = new List<DeviceInfoDTO>();
  334. if (!userInfoDO.IsDirector)
  335. {
  336. //普通用户,查询用户绑定的设备
  337. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
  338. {
  339. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  340. }
  341. }
  342. else
  343. {
  344. //机构负责人
  345. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  346. }
  347. if (!deviceInfoDOList.Any())
  348. {
  349. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  350. }
  351. var deviceList = await MapToExtendDTO(deviceInfoDOList);
  352. //条件筛选
  353. if (!string.IsNullOrWhiteSpace(request.DeviceType))
  354. {
  355. deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  356. }
  357. if (!string.IsNullOrWhiteSpace(request.DeviceModel))
  358. {
  359. deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  360. }
  361. if (!string.IsNullOrWhiteSpace(request.KeyWord))
  362. {
  363. var keyword = request.KeyWord.Trim().ToLower();
  364. deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List<DeviceExtendInfoDTO>();
  365. }
  366. if (request.IsOnline != null)
  367. {
  368. deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  369. }
  370. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  371. {
  372. CurrentPage = request.PageIndex,
  373. PageSize = request.PageSize,
  374. DataCount = deviceList.Count,
  375. PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
  376. };
  377. return pagedResult;
  378. }
  379. /// <summary>
  380. /// 绑定设备
  381. /// </summary>
  382. /// <param name="request"></param>
  383. /// <returns></returns>
  384. public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
  385. {
  386. //验证
  387. var userCode = await GetClientIdByTokenAsync(request.Token);
  388. //查询用户是否存在
  389. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  390. if (userInfoDO == null)
  391. {
  392. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  393. }
  394. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  395. if (deviceDb == null)
  396. {
  397. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  398. }
  399. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  400. {
  401. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  402. }
  403. try
  404. {
  405. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
  406. deviceDb.Name = request.Name;
  407. deviceDb.SerialNumber = request.SerialNumber;
  408. deviceDb.Description = request.Description;
  409. if (!string.IsNullOrEmpty(request.HeadPicUrl))
  410. {
  411. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  412. }
  413. deviceDb.DepartmentCode = request.DepartmentCode;
  414. deviceDb.IsAutoShared = request.IsAutoShared;
  415. deviceDb.OrganizationCode = request.OrganizationCode;
  416. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  417. if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
  418. {
  419. var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
  420. //迁移数据超声机上传检查记录
  421. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  422. //迁移数据超声机上传病人
  423. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  424. }
  425. if (deviceDb.IsAutoShared)
  426. {
  427. var users = new List<UserDTO>();
  428. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  429. {
  430. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  431. }
  432. else
  433. {
  434. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  435. }
  436. var userCodes = users.Select(f => f.UserCode).ToList();
  437. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  438. {
  439. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  440. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  441. });
  442. }
  443. return true;
  444. }
  445. catch (Exception ex)
  446. {
  447. Logger.WriteLineError($"BindDeviceAsync error {ex}");
  448. }
  449. return false;
  450. }
  451. /// <summary>
  452. /// 修改设备
  453. /// </summary>
  454. /// <param name="request"></param>
  455. /// <returns></returns>
  456. public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
  457. {
  458. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  459. if (deviceDb == null)
  460. {
  461. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  462. }
  463. if (string.IsNullOrWhiteSpace(request.Name))
  464. {
  465. ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
  466. }
  467. deviceDb.Name = request.Name;
  468. if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
  469. {
  470. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  471. }
  472. else
  473. {
  474. deviceDb.HeadPicUrl = string.Empty;
  475. }
  476. deviceDb.DepartmentCode = request.DepartmentCode;
  477. //修改自动分享
  478. deviceDb.IsAutoShared = request.IsAutoShared;
  479. if (deviceDb.IsAutoShared)
  480. {
  481. var users = new List<UserDTO>();
  482. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  483. {
  484. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  485. }
  486. else
  487. {
  488. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  489. }
  490. var userCodes = users.Select(f => f.UserCode).ToList();
  491. //先解绑,再绑定,避免绑定重复设备code
  492. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  493. foreach (var user in users)
  494. {
  495. var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
  496. user.BindDevices?.Remove(deviceDb.DeviceCode);
  497. await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
  498. }
  499. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  500. {
  501. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  502. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  503. });
  504. }
  505. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  506. }
  507. /// <summary>
  508. /// 创建字典
  509. /// </summary>
  510. /// <param name="request"></param>
  511. /// <returns></returns>
  512. public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
  513. {
  514. return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
  515. {
  516. Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
  517. ExtensionData = string.Empty
  518. });
  519. }
  520. /// <summary>
  521. /// 查找设备型号所有字典项
  522. /// </summary>
  523. /// <param name="request"></param>
  524. /// <returns></returns>
  525. public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
  526. {
  527. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  528. {
  529. DictionaryType = (int)request.DictionaryType,
  530. ParentCode = request.DeviceTypeCode
  531. });
  532. return dictionaryDOList;
  533. }
  534. /// <summary>
  535. /// 查找设备类型所有字典项
  536. /// </summary>
  537. /// <param name="request"></param>
  538. /// <returns></returns>
  539. public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
  540. {
  541. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  542. {
  543. DictionaryType = (int)request.DictionaryType
  544. });
  545. return dictionaryDOList;
  546. }
  547. /// <summary>
  548. /// 根据组织编码查询所属全部设备信息
  549. /// </summary>
  550. /// <param name="request"></param>
  551. /// <returns></returns>
  552. public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
  553. {
  554. var result = new List<DeviceExtendInfoDTO>();
  555. var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
  556. if (deviceInfoDOList?.Count > 0)
  557. {
  558. //根据机构编号查询机构名称
  559. var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
  560. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
  561. var organizationName = organization?.OrganizationName ?? string.Empty;
  562. //根据机构编号查询科室名称
  563. var organizationFilter = new Dictionary<string, string>();
  564. organizationFilter.Add("RootCode", organizationCode);
  565. var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
  566. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  567. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  568. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  569. foreach (var c in deviceInfoDOList)
  570. {
  571. var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
  572. result.Add(new DeviceExtendInfoDTO
  573. {
  574. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  575. OrganizationName = organizationName,
  576. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  577. DeviceCode = c.DeviceCode,
  578. SerialNumber = c.SerialNumber,
  579. Name = c.Name,
  580. Description = c.Description,
  581. DeviceModel = c.DeviceModel,
  582. DeviceType = c.DeviceType,
  583. HeadPicUrl = c.HeadPicUrl,
  584. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  585. SDKSoftwareVersion = c.SDKSoftwareVersion,
  586. OrganizationCode = c.OrganizationCode,
  587. DepartmentCode = c.DepartmentCode,
  588. ShortCode = c.ShortCode,
  589. LanguageConfigs = deviceTypeModel?.LanguageConfigs
  590. });
  591. }
  592. }
  593. return result;
  594. }
  595. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  596. {
  597. throw new NotImplementedException();
  598. }
  599. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  600. {
  601. //验证
  602. var userCode = await GetClientIdByTokenAsync(request.Token);
  603. //查询用户是否存在
  604. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  605. if (userInfoDO == null)
  606. {
  607. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  608. }
  609. var result = new List<SelectItemDTO>();
  610. //查询用户的医院是否存在
  611. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  612. {
  613. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  614. }
  615. var deviceInfoDOList = new List<DeviceInfoDTO>();
  616. if (userInfoDO.IsDirector)
  617. {
  618. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  619. }
  620. else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  621. {
  622. //查询用户绑定的设备
  623. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  624. {
  625. return result;
  626. }
  627. //根据用户名下的设备id查询所有的设备信息
  628. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  629. }
  630. else
  631. {
  632. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  633. if (experts.Any())
  634. {
  635. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  636. if (bindDeviceCodes.Any())
  637. {
  638. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  639. }
  640. }
  641. else
  642. {
  643. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  644. }
  645. }
  646. if (deviceInfoDOList?.Count > 0)
  647. {
  648. result = deviceInfoDOList.Select(c => new SelectItemDTO()
  649. {
  650. Key = c.DeviceCode,
  651. Value = c.Name
  652. }).ToList();
  653. }
  654. return result;
  655. }
  656. /// <summary>
  657. /// 设备端调用,查询获取服务器配置信息接口
  658. /// </summary>
  659. /// <param name="request">Token验证</param>
  660. /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
  661. public async Task<DeviceServerSettingResult> QueryServerConfigAsync(TokenRequest request)
  662. {
  663. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  664. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  665. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  666. {
  667. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  668. }
  669. var org = new OrganizationDTO();
  670. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  671. {
  672. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  673. if (org == null)
  674. {
  675. org = new OrganizationDTO();
  676. }
  677. }
  678. var dictionary = new Dictionary<string, string>();
  679. //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
  680. //TODO 配置信息: 直播配置、存储配置、
  681. //存储上传图像或者视频是 是否本地上传缩略图
  682. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  683. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  684. dictionary.Add("PatientType", org.PatientType.ToString());
  685. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  686. dictionary.Add("NotificationUrl", _webSocketUrl);
  687. dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
  688. dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
  689. var result = new DeviceServerSettingResult()
  690. {
  691. ServerConfigList = dictionary,
  692. IsUploadThumbnail = isUploadThumbnail,
  693. PatientType = org.PatientType,
  694. HeartRateSeconds = _heartRateSeconds,
  695. NotificationUrl = _webSocketUrl,
  696. LiveConsultationRateSeconds = _liveConsultationRateSeconds,
  697. MergedChannel = deviceInfo.MergedChannel,
  698. MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
  699. MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
  700. IsSelfRtcService = _isRTCSelf,
  701. RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec
  702. };
  703. return result;
  704. }
  705. /// <summary>
  706. /// 添加或迁移设备到医院请求
  707. /// </summary>
  708. /// <param name="request"></param>
  709. /// <returns></returns>
  710. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  711. {
  712. var shortCode = request.UniqueCode;
  713. #region Params Check
  714. var userCode = await GetClientIdByTokenAsync(request.Token);
  715. if (string.IsNullOrEmpty(shortCode))
  716. {
  717. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  718. }
  719. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  720. if (device == null)
  721. {
  722. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  723. }
  724. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  725. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  726. {
  727. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  728. }
  729. //用户
  730. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  731. if (userDTO == null)
  732. {
  733. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  734. }
  735. if (!userDTO.IsDirector)
  736. {
  737. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  738. }
  739. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  740. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  741. {
  742. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  743. }
  744. #endregion
  745. try
  746. {
  747. var newOrgode = org.OrganizationCode;
  748. //设备更新医院
  749. if (!string.IsNullOrEmpty(device.DepartmentCode))
  750. {
  751. device.DepartmentCode = "";
  752. }
  753. if (!string.IsNullOrEmpty(device.Name))
  754. {
  755. device.Name = "";
  756. }
  757. device.HeadPicUrl = "";
  758. device.Description = "";
  759. device.IsAutoShared = false;
  760. device.OrganizationCode = newOrgode;
  761. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  762. if (success)
  763. {
  764. // 删除已知绑定的用户
  765. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  766. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  767. foreach (var user in users)
  768. {
  769. user.BindDevices.Remove(device.DeviceCode);
  770. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  771. {
  772. Data = user.MappingTo<UserPasswordDTO>(),
  773. });
  774. }
  775. if (updateUsers.Count > 0)
  776. {
  777. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  778. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  779. }
  780. if (oldOrg.Isinvented) // 虚拟医院
  781. {
  782. //迁移数据超声机上传检查记录
  783. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  784. //迁移数据超声机上传病人
  785. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  786. }
  787. }
  788. return success;
  789. }
  790. catch (System.Exception ex)
  791. {
  792. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  793. }
  794. return false;
  795. }
  796. /// <summary>
  797. /// 补齐设备扩展信息
  798. /// </summary>
  799. /// <param name="deviceInfoDOList"></param>
  800. /// <returns></returns>
  801. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
  802. {
  803. var deviceList = new List<DeviceExtendInfoDTO>();
  804. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  805. {
  806. //查询机构
  807. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  808. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  809. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  810. //查询机构负责人
  811. var organizationDirectorCodes = new List<string>();
  812. foreach (var org in organizations)
  813. {
  814. if (org.Directors != null && org.Directors.Any())
  815. {
  816. organizationDirectorCodes.AddRange(org.Directors);
  817. }
  818. }
  819. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  820. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  821. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  822. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  823. foreach (var dto in deviceInfoDOList)
  824. {
  825. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  826. device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
  827. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  828. device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
  829. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  830. if (organization != null)
  831. {
  832. device.OrganizationName = organization.OrganizationName;
  833. if (organization.Directors != null && organization.Directors.Any())
  834. {
  835. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  836. device.OrganizationDirectorCode = director?.UserCode;
  837. device.OrganizationDirectorUserName = director?.UserName;
  838. device.OrganizationDirectorFullName = director?.FullName;
  839. }
  840. }
  841. deviceList.Add(device);
  842. }
  843. }
  844. return deviceList;
  845. }
  846. /// <summary>
  847. /// 补齐设备扩展信息
  848. /// </summary>
  849. /// <param name="deviceInfoDOList"></param>
  850. /// <returns></returns>
  851. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  852. {
  853. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  854. return deviceList.FirstOrDefault();
  855. }
  856. /// <summary>
  857. /// 获取设备绑定用户codes
  858. /// </summary>
  859. /// <param name="request">获取设备绑定用户codes请求实体</param>
  860. /// <returns>test01,test02</returns>
  861. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  862. {
  863. //检查设备编码不为空
  864. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  865. {
  866. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  867. }
  868. //查询设备对象
  869. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  870. if (deviceDb == null)
  871. {
  872. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  873. }
  874. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  875. if (userListResult != null && userListResult.Count > 0)
  876. {
  877. return userListResult.Select(u => u.UserCode).ToList();
  878. }
  879. return new List<string>();
  880. }
  881. /// <summary>
  882. /// 查询设备AI应用的状态
  883. /// </summary>
  884. /// <param name="request">请求参数</param>
  885. /// <returns>AI应用集合</returns>
  886. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  887. {
  888. //检查设备编码不为空
  889. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  890. {
  891. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  892. }
  893. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  894. }
  895. /// <summary>
  896. /// 修改设备AI应用启用状态
  897. /// </summary>
  898. /// <param name="request">修改设备AI应用启用状态请求实体</param>
  899. /// <returns>是否成功</returns>
  900. /// <para>DeviceErrorCodeEnum</para>
  901. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  902. {
  903. //检查设备编码不为空
  904. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  905. {
  906. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  907. }
  908. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  909. {
  910. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  911. }
  912. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  913. {
  914. DeviceCode = request.DeviceCode,
  915. DiagnosisModule = request.DiagnosisModule,
  916. Enabled = request.Enabled
  917. });
  918. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  919. return result;
  920. }
  921. /// <summary>
  922. /// 设备离开会诊房间
  923. /// </summary>
  924. /// <param name="request">设备离开会诊房间请求实体</param>
  925. /// <returns></returns>
  926. public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
  927. {
  928. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  929. var result = new DeviceLeaveLiveConsultationResult
  930. {
  931. Success = false,
  932. };
  933. return result;
  934. }
  935. /// <summary>
  936. /// 通用异常处理方法
  937. /// </summary>
  938. /// <param name="customerRpcCodeEnum">异常标识码</param>
  939. /// <param name="msg">异常信息</param>
  940. /// <param name="internalMessage">内部异常信息,非必填</param>
  941. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  942. {
  943. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  944. }
  945. /// <summary>
  946. /// 上报设备画面尺寸相关信息
  947. /// </summary>
  948. /// <param name="request"></param>
  949. /// <docFirstDirectory>设备端API</docFirstDirectory>
  950. /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
  951. /// <docThirdDirectory>会诊</docThirdDirectory>
  952. /// <returns></returns>
  953. public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
  954. {
  955. var result = new ReportVideoDeviceInfoResult();
  956. if (request.VideoDeviceInfos == null || request.VideoDeviceInfos.Count == 0)
  957. {
  958. //视屏设备画面信息为空
  959. ThrowCustomerException(CustomerRpcCode.VideoDeviceInfosEmpty, "VideoDeviceInfosEmpty");
  960. }
  961. if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
  962. {
  963. //视屏设备ID为空
  964. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
  965. }
  966. var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
  967. if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
  968. {
  969. //视屏设备ID重复
  970. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
  971. }
  972. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  973. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  974. var videoDeviceInfos = new List<VideoDeviceDTO>();
  975. foreach (var video in request.VideoDeviceInfos)
  976. {
  977. var videoDeviceInfo = new VideoDeviceDTO
  978. {
  979. VideoDeviceId = video.VideoDeviceId,
  980. VideoDeviceSourceType = video.VideoDeviceSourceType,
  981. Width = video.Width,
  982. Height = video.Height,
  983. OutputWidth = video.Width,
  984. OutputHeight = video.Height
  985. };
  986. if (deviceDTO.VideoDeviceInfos != null && deviceDTO.VideoDeviceInfos.Any(x => x.VideoDeviceId == video.VideoDeviceId))
  987. {
  988. var oldVideo = deviceDTO.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == video.VideoDeviceId);
  989. videoDeviceInfo.OutputWidth = oldVideo.OutputWidth;
  990. videoDeviceInfo.OutputHeight = oldVideo.OutputHeight;
  991. videoDeviceInfo.VideoFps = oldVideo.VideoFps;
  992. videoDeviceInfo.VideoBitrate = oldVideo.VideoBitrate;
  993. videoDeviceInfo.MinVideoBitrate = oldVideo.MinVideoBitrate;
  994. }
  995. videoDeviceInfos.Add(videoDeviceInfo);
  996. }
  997. deviceDTO.VideoDeviceInfos = videoDeviceInfos;
  998. var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
  999. {
  1000. DeviceCode = deviceDTO.DeviceCode,
  1001. LiveOpened = request.LiveOpened,
  1002. VideoDeviceInfos = videoDeviceInfos
  1003. };
  1004. await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
  1005. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(deviceDTO.DeviceCode);
  1006. result.Success = true;
  1007. return result;
  1008. }
  1009. /// <summary>
  1010. /// 查找有效设备总数量
  1011. /// </summary>
  1012. /// <returns></returns>
  1013. public async Task<long> GetActiveDeviceCount()
  1014. {
  1015. return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
  1016. }
  1017. /// <summary>
  1018. /// 设备发送调参初始化数据
  1019. /// </summary>
  1020. /// <param name="request">调参数据请求</param>
  1021. /// <returns></returns>
  1022. public async Task<bool> SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
  1023. {
  1024. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1025. var userCode = request.ControlUserCode;
  1026. //发送控制人通知
  1027. if (string.IsNullOrWhiteSpace(userCode))
  1028. {
  1029. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1030. }
  1031. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1032. if (userDTO == null)
  1033. {
  1034. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1035. }
  1036. var notify = new DeviceParametersNotification()
  1037. {
  1038. DeviceCode = deviceCode,
  1039. ProbeApplication = request.ProbeApplication,
  1040. Parameter = request.Parameter,
  1041. IsResponse = true
  1042. };
  1043. var notificationRequest = new SendNotificationRequest()
  1044. {
  1045. ClientId = userCode,
  1046. Message = notify,
  1047. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1048. NotificationType = notify.NotificationType,
  1049. TransactionType = TransactionTypeEnum.ControlParameter,
  1050. RelevanceCode = userCode,
  1051. ReceiverType = ApplicantTypeEnum.Client
  1052. };
  1053. await _notificationService.PostMessageAsync(notificationRequest);
  1054. return true;
  1055. }
  1056. /// <summary>
  1057. /// 用户进入设备直播房间
  1058. /// </summary>
  1059. /// <param name="request">用户进入设备直播房间请求实体</param>
  1060. /// <returns></returns>
  1061. public async Task<JoinDeviceLiveRoomResult> JoinDeviceLiveRoomAsync(JoinDeviceLiveRoomRequest request)
  1062. {
  1063. var userInfo = await _authenticationService.GetTokenAsync(request);
  1064. var deviceCode = request.DeviceCode;
  1065. var liveRooms = await _rtcService.GetLiveRoomsByDeviceCodeAsync(new GetLiveRoomsByDeviceCodeRequest
  1066. {
  1067. DeviceCode = deviceCode
  1068. });
  1069. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1070. LiveMemberDTO deviceMemberInfo;
  1071. if (liveRoom != null)
  1072. {
  1073. //设备正在推流
  1074. deviceMemberInfo = liveRoom.Members.FirstOrDefault(x => x.Code == deviceCode);
  1075. if (deviceMemberInfo?.Status == LiveMemberStatus.Joined)
  1076. {
  1077. return new JoinDeviceLiveRoomResult
  1078. {
  1079. RoomNo = liveRoom.RoomNo,
  1080. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1081. };
  1082. }
  1083. }
  1084. //新增或更新设备直播间 TODO
  1085. var rtcRoomResult = await _rtcService.GetRoomIdAsync(new GetRoomIdRequest
  1086. {
  1087. UniqueId = deviceCode,
  1088. });
  1089. var rtcRoomId = (int)rtcRoomResult.RoomId;
  1090. var initiateResult = await _rtcService.InitiateLiveAsync(new InitiateLiveRequest
  1091. {
  1092. RoomId = deviceCode,
  1093. InitiatorCode = deviceCode,
  1094. IntegerRoomId = rtcRoomId
  1095. });
  1096. //添加观众
  1097. var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1098. {
  1099. LiveRoomCode = initiateResult.RoomId,
  1100. UserCode = userInfo.ClientId,
  1101. UserName = userInfo.AccountName,
  1102. });
  1103. //通知设备推流
  1104. deviceMemberInfo = initiateResult.Members.FirstOrDefault(x => x.Code == deviceCode);
  1105. var message = new StartLiveToDeviceNotification
  1106. {
  1107. LiveRoomCode = initiateResult.RoomId,
  1108. RoomNo = initiateResult.RoomNo,
  1109. AppId = _sdkAppId,
  1110. // MergedChannel = deviceMemberInfo.MergedChannel,
  1111. // MergedVideoOutputWidth = deviceMemberInfo.MergedVideoOutputWidth,
  1112. // MergedVideoOutputHeight = deviceMemberInfo.MergedVideoOutputHeight,
  1113. // VideoDeviceOutputList = deviceMemberInfo.VideoDeviceInfos.ToList(),
  1114. };
  1115. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1116. return new JoinDeviceLiveRoomResult
  1117. {
  1118. RoomNo = initiateResult.RoomNo,
  1119. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1120. ReportStateIntervalSeconds = _reportStateIntervalSeconds,
  1121. };
  1122. }
  1123. /// <summary>
  1124. /// 用户离开设备直播房间
  1125. /// </summary>
  1126. /// <param name="request">用户离开设备直播房间请求实体</param>
  1127. /// <returns></returns>
  1128. public async Task<bool> LeaveDeviceLiveRoomAsync(LeaveDeviceLiveRoomRequest request)
  1129. {
  1130. var userInfo = await _authenticationService.GetTokenAsync(request);
  1131. var userCode = userInfo.ClientId;
  1132. var rtcRoomId = request.RoomNo;
  1133. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1134. {
  1135. RtcRoomId = rtcRoomId
  1136. });
  1137. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1138. if (liveRoom != null)
  1139. {
  1140. var deviceCode = liveRoom.DeviceInfos?.FirstOrDefault()?.Code;
  1141. //移除观众
  1142. var removeViewerResult = await _rtcService.RemoveViewerAsync(new RemoveViewerRequest
  1143. {
  1144. LiveRoomCode = liveRoom.RoomId,
  1145. UserCode = userInfo.ClientId,
  1146. });
  1147. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1148. if (!liveRoom.ViewerInfos.Any(x => x.UserCode != userCode && x.LastReportTime >= expireTime) && !string.IsNullOrWhiteSpace(deviceCode))
  1149. {
  1150. //关闭直播 to device
  1151. var message = new CloseLiveToDeviceNotification
  1152. {
  1153. LiveRoomCode = liveRoom.RoomId,
  1154. };
  1155. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1156. }
  1157. }
  1158. return true;
  1159. }
  1160. /// <summary>
  1161. /// 上报观看直播状态
  1162. /// </summary>
  1163. /// <param name="request">上报观看直播状态请求实体</param>
  1164. /// <returns></returns>
  1165. public async Task<bool> ReportLiveViewStateAsync(ReportLiveViewStateRequest request)
  1166. {
  1167. var userInfo = await _authenticationService.GetTokenAsync(request);
  1168. var rtcRoomId = request.RoomNo;
  1169. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1170. {
  1171. RtcRoomId = rtcRoomId
  1172. });
  1173. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1174. if (liveRoom != null)
  1175. {
  1176. //添加观众
  1177. var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1178. {
  1179. LiveRoomCode = liveRoom.RoomId,
  1180. UserCode = userInfo.ClientId,
  1181. UserName = userInfo.AccountName,
  1182. });
  1183. }
  1184. return true;
  1185. }
  1186. /// <summary>
  1187. /// 上报直播状态
  1188. /// </summary>
  1189. /// <param name="request">上报直播状态请求实体</param>
  1190. /// <returns></returns>
  1191. public async Task<bool> ReportLiveStateAsync(ReportLiveStateRequest request)
  1192. {
  1193. var tokenInfo = await _authenticationService.GetTokenAsync(request);
  1194. var deviceCode = tokenInfo.ClientId;
  1195. switch (request.LiveState)
  1196. {
  1197. case DeviceLiveStateEnum.Error:
  1198. case DeviceLiveStateEnum.Warning:
  1199. Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1200. break;
  1201. default:
  1202. Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1203. break;
  1204. }
  1205. if (request.LiveState == DeviceLiveStateEnum.Pushing || request.LiveState == DeviceLiveStateEnum.Closed)
  1206. {
  1207. var rtcRoomId = request.RoomNo;
  1208. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1209. {
  1210. RtcRoomId = rtcRoomId
  1211. });
  1212. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1213. if (liveRoom != null)
  1214. {
  1215. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1216. var validViewers = liveRoom.ViewerInfos.Where(x => x.LastReportTime >= expireTime)?.ToList() ?? new List<LiveViewerDTO>();
  1217. if (request.LiveState == DeviceLiveStateEnum.Closed && validViewers.Any())
  1218. {
  1219. //关闭直播 to users
  1220. var message = new DeviceLiveFinishedNotification
  1221. {
  1222. LiveRoomCode = liveRoom.RoomId,
  1223. };
  1224. await BroadcastNotificationAsync(liveRoom.RoomId, validViewers.Select(x => x.UserCode).ToList(), message);
  1225. }
  1226. if (request.LiveState == DeviceLiveStateEnum.Pushing && !validViewers.Any())
  1227. {
  1228. //关闭直播 to device
  1229. var message = new CloseLiveToDeviceNotification
  1230. {
  1231. LiveRoomCode = liveRoom.RoomId,
  1232. };
  1233. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1234. }
  1235. }
  1236. }
  1237. return await Task.FromResult(true);
  1238. }
  1239. /// <summary>
  1240. /// 获取实时音视频参数
  1241. /// </summary>
  1242. /// <param name="request">获取实时音视频参数请求实体</param>
  1243. /// <returns></returns>
  1244. public async Task<CreateLiveRoomInfoResult> CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
  1245. {
  1246. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
  1247. var userCode = Guid.NewGuid().ToString("N");
  1248. var getUserSignRequest = new GetUserSignRequest
  1249. {
  1250. UserId = userCode,
  1251. };
  1252. var getUserSignResult = await _rtcService.GetUserSignAsync(getUserSignRequest);
  1253. var userSign = getUserSignResult.UserSign;
  1254. var getRoomIdRequest = new GetRoomIdRequest
  1255. {
  1256. UniqueId = userCode,
  1257. };
  1258. var getRoomIdResult = await _rtcService.GetRoomIdAsync(getRoomIdRequest);
  1259. var intRoomNo = (int)getRoomIdResult.RoomId;
  1260. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
  1261. return new CreateLiveRoomInfoResult
  1262. {
  1263. IsTrtc = !_isRTCSelf,
  1264. UserCode = userCode,
  1265. UserSign = userSign,
  1266. AppId = _sdkAppId,
  1267. RoomNo = intRoomNo,
  1268. };
  1269. }
  1270. private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> clientIds, NotificationDTO message)
  1271. {
  1272. var broadcastNotificationRequest = new BroadcastRoomNotificationRequest
  1273. {
  1274. RoomId = roomId,
  1275. ClientIds = clientIds,
  1276. Message = message,
  1277. TransactionType = TransactionTypeEnum.Live,
  1278. RelevanceCode = roomId,
  1279. ReceiverType = ApplicantTypeEnum.Client,
  1280. WSConnectType = WSConnectTypeEnum.Default
  1281. };
  1282. return await _rtcService.BroadcastRoomNotificationAsync(broadcastNotificationRequest);
  1283. }
  1284. /// <summary>
  1285. /// 拒绝远程控制
  1286. /// </summary>
  1287. /// <param name="request"></param>
  1288. /// <returns></returns>
  1289. public async Task<bool> RejectRemoteControl(RemoteControlRequest request)
  1290. {
  1291. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1292. string userCode = request.ControlUserCode;
  1293. //发送控制人通知
  1294. if (string.IsNullOrWhiteSpace(userCode))
  1295. {
  1296. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1297. }
  1298. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1299. if (userDTO == null)
  1300. {
  1301. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1302. }
  1303. var notify = new DeviceRejectRemoteControlNotification()
  1304. {
  1305. DeviceCode = deviceCode,
  1306. };
  1307. var notificationRequest = new SendNotificationRequest()
  1308. {
  1309. ClientId = userCode,
  1310. Message = notify,
  1311. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1312. NotificationType = notify.NotificationType,
  1313. TransactionType = TransactionTypeEnum.RemoteControl,
  1314. RelevanceCode = userCode,
  1315. ReceiverType = ApplicantTypeEnum.Client
  1316. };
  1317. await _notificationService.PostMessageAsync(notificationRequest);
  1318. //更改房间调参状态
  1319. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1320. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1321. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1322. // {
  1323. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1324. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1325. // }
  1326. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1327. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1328. return true;
  1329. }
  1330. /// <summary>
  1331. /// 断开远程控制
  1332. /// </summary>
  1333. /// <param name="request"></param>
  1334. /// <returns></returns>
  1335. public async Task<bool> DisconnectRemoteControl(RemoteControlRequest request)
  1336. {
  1337. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1338. string userCode = request.ControlUserCode;
  1339. //发送控制人通知
  1340. if (string.IsNullOrWhiteSpace(userCode))
  1341. {
  1342. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1343. }
  1344. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1345. if (userDTO == null)
  1346. {
  1347. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1348. }
  1349. var notify = new DeviceDisconnectRemoteControlNotification()
  1350. {
  1351. DeviceCode = deviceCode,
  1352. };
  1353. var notificationRequest = new SendNotificationRequest()
  1354. {
  1355. ClientId = userCode,
  1356. Message = notify,
  1357. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1358. NotificationType = notify.NotificationType,
  1359. TransactionType = TransactionTypeEnum.RemoteControl,
  1360. RelevanceCode = userCode,
  1361. ReceiverType = ApplicantTypeEnum.Client
  1362. };
  1363. await _notificationService.PostMessageAsync(notificationRequest);
  1364. //更改房间调参状态
  1365. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1366. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1367. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1368. // {
  1369. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1370. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1371. // }
  1372. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1373. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1374. return true;
  1375. }
  1376. public async Task<bool> UploadConsultationDataAsync(UploadConsultationDataRequest request)
  1377. {
  1378. var deviceInfo = await GetDeviceByTokenAsync(request);
  1379. var consultationCode = request.ConsultationCode;
  1380. if (string.IsNullOrWhiteSpace(consultationCode))
  1381. {
  1382. ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
  1383. }
  1384. if (string.IsNullOrWhiteSpace(request.FileToken))
  1385. {
  1386. ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
  1387. }
  1388. var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
  1389. var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
  1390. if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
  1391. {
  1392. ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
  1393. }
  1394. var dataDTO = new RemedicalInfoDTO();
  1395. dataDTO.DeviceCode = deviceInfo.DeviceCode;
  1396. dataDTO.RecordCode = consultationRecord.ConsultationCode;
  1397. dataDTO.ApplicationCategory = request.ApplicationCategory;
  1398. dataDTO.Application = request.Application;
  1399. dataDTO.TerminalImages = new TerminalImageDTO();
  1400. var originImageUrl = request.FileToken;
  1401. dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
  1402. dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
  1403. dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
  1404. dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
  1405. dataDTO.TerminalImages.ImageSize = request.FileSize;
  1406. dataDTO.FileDataType = request.FileDataType;
  1407. dataDTO.MeasuredResult = request.MeasuredResult;
  1408. dataDTO.CommentResult = request.CommentResult;
  1409. dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
  1410. dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
  1411. //更新会诊记录
  1412. if (consultationRecord.ConsultationFileList == null)
  1413. {
  1414. consultationRecord.ConsultationFileList = new List<ConsultationFileDTO>();
  1415. }
  1416. var consultationFileDTO = new ConsultationFileDTO
  1417. {
  1418. SourceUrl = originImageUrl,
  1419. CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
  1420. PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
  1421. FileDataType = request.FileDataType,
  1422. CreateTime = DateTime.UtcNow,
  1423. ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
  1424. RemedicalCode = dataDTO.RemedicalCode
  1425. };
  1426. consultationRecord.ConsultationFileList.Add(consultationFileDTO);
  1427. var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
  1428. return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
  1429. }
  1430. }
  1431. }