DeviceService.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using JsonRpcLite.Services;
  6. using WingInterfaceLibrary.DTO.Device;
  7. using WingInterfaceLibrary.Interface;
  8. using WingInterfaceLibrary.Request.Device;
  9. using WingInterfaceLibrary.DTO.Dictionary;
  10. using WingServerCommon.Log;
  11. using WingServerCommon.Service;
  12. using WingInterfaceLibrary.Interface.DBInterface;
  13. using WingInterfaceLibrary.DB.Request;
  14. using WingServerCommon.Mapper;
  15. using WingInterfaceLibrary.Request;
  16. using WingInterfaceLibrary.Request.Authentication;
  17. using WingInterfaceLibrary.DTO.User;
  18. using WingInterfaceLibrary.DTO.Management;
  19. using WingServerCommon.Config;
  20. using WingDeviceService.Common;
  21. using WingInterfaceLibrary.Request.User;
  22. using WingInterfaceLibrary.Enum;
  23. using WingInterfaceLibrary.DTO.Organization;
  24. using WingInterfaceLibrary.DTO.DiagnosisModule;
  25. using WingServerCommon.Config.Parameters;
  26. using WingServerCommon.Interfaces.Cache;
  27. namespace WingDeviceService.Service
  28. {
  29. /// <summary>
  30. /// 设备管理服务
  31. /// </summary>
  32. public partial class DeviceService : JsonRpcService, IDeviceService
  33. {
  34. private IUserDBService _userServiceProxy;
  35. private IDeviceInfoDBService _deviceInfoDBServiceProxy;
  36. private IAuthenticationService _authenticationService;
  37. private IOrganizationDBService _organizationDBService;
  38. private INotificationService _notificationService;
  39. private IRecordsInfoDBService _recordsInfoDBService;
  40. private IPatientInfoDBService _patientInfoDBService;
  41. private IDiagnosisModuleDBService _diagnosisModuleService;
  42. private IRemedicalService _remedicalService;
  43. private int _heartRateSeconds;
  44. private DeviceHeartRateManager _deviceHeartRateManager;
  45. /// <summary>
  46. /// Init service
  47. /// </summary>
  48. public override void Load(JsonRpcClientPool jsonRpcClientPool)
  49. {
  50. base.Load(jsonRpcClientPool);
  51. _userServiceProxy = GetProxy<IUserDBService>();
  52. _authenticationService = GetProxy<IAuthenticationService>();
  53. _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
  54. _organizationDBService = GetProxy<IOrganizationDBService>();
  55. _notificationService = GetProxy<INotificationService>();
  56. _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
  57. _patientInfoDBService = GetProxy<IPatientInfoDBService>();
  58. _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
  59. _remedicalService = GetProxy<IRemedicalService>();
  60. _heartRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
  61. _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
  62. }
  63. /// <summary>
  64. /// 设备心跳
  65. /// </summary>
  66. /// <param name="request"></param>
  67. /// <returns></returns>
  68. public async Task<bool> HeartRateAsync(TokenRequest request)
  69. {
  70. _deviceHeartRateManager.AddOrUpdate(request.Token);
  71. var result = SetOnlineState(request.Token, true);
  72. return result;
  73. }
  74. private bool SetOnlineState(string token, bool isOnline)
  75. {
  76. return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
  77. }
  78. /// <summary>
  79. /// 添加分享设备关联用户请求
  80. /// </summary>
  81. /// <param name="request"></param>
  82. /// <returns></returns>
  83. public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
  84. {
  85. var userCodes = request.UserCodes;
  86. var deviceCode = request.DeviceCode;
  87. //检查设备编码不为空
  88. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  89. {
  90. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  91. }
  92. if (userCodes == null || userCodes.Count <= 0)
  93. {
  94. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  95. }
  96. //查询设备对象
  97. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  98. if (deviceDb == null)
  99. {
  100. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  101. }
  102. foreach (var userCode in userCodes)
  103. {
  104. var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
  105. if (existUser == null)
  106. {
  107. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  108. }
  109. }
  110. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  111. {
  112. DeviceCodes = new List<string> { deviceCode },
  113. UserCodes = userCodes.ToList()
  114. });
  115. return true;
  116. }
  117. /// <summary>
  118. /// 根据设备code获取设备信息
  119. /// </summary>
  120. /// <param name="request">设备code请求实体</param>
  121. /// <returns>返回查询到的设备对象信息</returns>
  122. public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
  123. {
  124. //验证
  125. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  126. {
  127. ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
  128. }
  129. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  130. if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
  131. {
  132. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  133. }
  134. //根据机构编号查询机构名称
  135. var organizationName = "";
  136. if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
  137. {
  138. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
  139. organizationName = organization?.OrganizationName ?? string.Empty;
  140. }
  141. //根据机构编号查询科室名称
  142. var departmentName = "";
  143. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  144. {
  145. var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
  146. departmentName = department?.OrganizationName ?? string.Empty;
  147. }
  148. //是否在线 todo
  149. var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
  150. var result = new DeviceExtendInfoDTO()
  151. {
  152. DepartmentName = departmentName,
  153. OrganizationName = organizationName,
  154. IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
  155. DeviceCode = deviceDb.DeviceCode,
  156. SerialNumber = deviceDb.SerialNumber,
  157. Name = deviceDb.Name,
  158. Description = deviceDb.Description,
  159. DeviceModel = deviceDb.DeviceModel,
  160. DeviceType = deviceDb.DeviceType,
  161. HeadPicUrl = deviceDb.HeadPicUrl,
  162. DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
  163. SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
  164. OrganizationCode = deviceDb.OrganizationCode,
  165. DepartmentCode = deviceDb.DepartmentCode,
  166. ShortCode = deviceDb.ShortCode,
  167. DeviceTypeName = deviceTypeModel.Value
  168. };
  169. return result;
  170. }
  171. /// <summary>
  172. /// 根据设备动态唯一码获取设备信息
  173. /// </summary>
  174. /// <param name="request"></param>
  175. /// <returns></returns>
  176. public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
  177. {
  178. //验证
  179. if (string.IsNullOrWhiteSpace(request.ShortCode))
  180. {
  181. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
  182. }
  183. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  184. if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
  185. {
  186. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  187. }
  188. return await MapToExtendDTO(deviceDb);
  189. }
  190. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
  191. {
  192. throw new System.NotImplementedException();
  193. }
  194. public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
  195. {
  196. var userCodes = request.UserCodes;
  197. var deviceCode = request.DeviceCode;
  198. //检查设备编码不为空
  199. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  200. {
  201. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  202. }
  203. //用户编码集合检查
  204. if (userCodes == null || userCodes.Count <= 0)
  205. {
  206. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  207. }
  208. //查询设备对象
  209. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  210. if (deviceDb == null)
  211. {
  212. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  213. }
  214. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  215. foreach (var userCode in userCodes)
  216. {
  217. var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
  218. if (user != null)
  219. {
  220. if (user.BindDevices.Contains(deviceCode))
  221. {
  222. user.BindDevices.Remove(deviceCode);
  223. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  224. {
  225. Data = user.MappingTo<UserPasswordDTO>(),
  226. });
  227. }
  228. }
  229. }
  230. if (updateUsers.Count > 0)
  231. {
  232. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  233. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  234. }
  235. return true;
  236. }
  237. /// <summary>
  238. /// 机构设备移除-根据机构code和设备code解除其绑定关系
  239. /// </summary>
  240. /// <param name="request">移除设备请求实体</param>
  241. /// <returns>移除是否成功:true-成功;false-失败</returns>
  242. public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
  243. {
  244. //验证
  245. if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
  246. {
  247. ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
  248. }
  249. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  250. if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
  251. {
  252. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
  253. }
  254. //根据设备code和机构code查询相关数据,查到则删除关联
  255. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  256. {
  257. deviceDb.DepartmentCode = "";
  258. deviceDb.OrganizationCode = "";
  259. }
  260. else
  261. {
  262. deviceDb.OrganizationCode = "";
  263. }
  264. bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  265. return removeDeviceResult;
  266. }
  267. private async Task<string> GetClientIdByTokenAsync(string token)
  268. {
  269. var request = new TokenRequest() { Token = token };
  270. var result = await _authenticationService.GetTokenAsync(request);
  271. return result.ClientId; //return User code
  272. }
  273. /// <summary>
  274. /// 查询个人名下所有设备列表接口
  275. /// </summary>
  276. /// <param name="request">查询个人名下所有设备列表请求实体</param>
  277. /// <returns>返回设备信息列表</returns>
  278. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
  279. {
  280. //验证
  281. var userCode = await GetClientIdByTokenAsync(request.Token);
  282. //查询用户是否存在
  283. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  284. if (userInfoDO == null)
  285. {
  286. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  287. }
  288. //查询用户的医院是否存在
  289. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  290. {
  291. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  292. }
  293. var deviceInfoDOList = new List<DeviceInfoDTO>();
  294. if (!userInfoDO.IsDirector)
  295. {
  296. //普通用户,查询用户绑定的设备
  297. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
  298. {
  299. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  300. }
  301. }
  302. else
  303. {
  304. //机构负责人
  305. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  306. }
  307. if (!deviceInfoDOList.Any())
  308. {
  309. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  310. }
  311. var deviceList = await MapToExtendDTO(deviceInfoDOList);
  312. //条件筛选
  313. if (!string.IsNullOrWhiteSpace(request.DeviceType))
  314. {
  315. deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  316. }
  317. if (!string.IsNullOrWhiteSpace(request.DeviceModel))
  318. {
  319. deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  320. }
  321. if (!string.IsNullOrWhiteSpace(request.KeyWord))
  322. {
  323. var keyword = request.KeyWord.Trim().ToLower();
  324. deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List<DeviceExtendInfoDTO>();
  325. }
  326. if (request.IsOnline != null)
  327. {
  328. deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  329. }
  330. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  331. {
  332. CurrentPage = request.PageIndex,
  333. PageSize = request.PageSize,
  334. DataCount = deviceList.Count,
  335. PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
  336. };
  337. return pagedResult;
  338. }
  339. /// <summary>
  340. /// 绑定设备
  341. /// </summary>
  342. /// <param name="request"></param>
  343. /// <returns></returns>
  344. public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
  345. {
  346. //验证
  347. var userCode = await GetClientIdByTokenAsync(request.Token);
  348. //查询用户是否存在
  349. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  350. if (userInfoDO == null)
  351. {
  352. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  353. }
  354. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  355. if (deviceDb == null)
  356. {
  357. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  358. }
  359. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  360. {
  361. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  362. }
  363. try
  364. {
  365. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
  366. deviceDb.Name = request.Name;
  367. deviceDb.SerialNumber = request.SerialNumber;
  368. deviceDb.Description = request.Description;
  369. if (!string.IsNullOrEmpty(request.HeadPicUrl))
  370. {
  371. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  372. }
  373. deviceDb.DepartmentCode = request.DepartmentCode;
  374. deviceDb.IsAutoShared = request.IsAutoShared;
  375. deviceDb.OrganizationCode = request.OrganizationCode;
  376. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  377. if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
  378. {
  379. var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
  380. //迁移数据超声机上传检查记录
  381. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  382. //迁移数据超声机上传病人
  383. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  384. }
  385. if (deviceDb.IsAutoShared)
  386. {
  387. var users = new List<UserDTO>();
  388. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  389. {
  390. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  391. }
  392. else
  393. {
  394. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  395. }
  396. var userCodes = users.Select(f => f.UserCode).ToList();
  397. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  398. {
  399. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  400. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  401. });
  402. }
  403. return true;
  404. }
  405. catch (Exception ex)
  406. {
  407. Logger.WriteLineError($"BindDeviceAsync error {ex}");
  408. }
  409. return false;
  410. }
  411. /// <summary>
  412. /// 修改设备
  413. /// </summary>
  414. /// <param name="request"></param>
  415. /// <returns></returns>
  416. public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
  417. {
  418. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  419. if (deviceDb == null)
  420. {
  421. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  422. }
  423. if (string.IsNullOrWhiteSpace(request.Name))
  424. {
  425. ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
  426. }
  427. deviceDb.Name = request.Name;
  428. if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
  429. {
  430. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  431. }
  432. else
  433. {
  434. deviceDb.HeadPicUrl = string.Empty;
  435. }
  436. deviceDb.DepartmentCode = request.DepartmentCode;
  437. //修改自动分享
  438. deviceDb.IsAutoShared = request.IsAutoShared;
  439. if (deviceDb.IsAutoShared)
  440. {
  441. var users = new List<UserDTO>();
  442. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  443. {
  444. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  445. }
  446. else
  447. {
  448. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  449. }
  450. var userCodes = users.Select(f => f.UserCode).ToList();
  451. //先解绑,再绑定,避免绑定重复设备code
  452. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  453. foreach (var user in users)
  454. {
  455. var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
  456. user.BindDevices?.Remove(deviceDb.DeviceCode);
  457. await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
  458. }
  459. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  460. {
  461. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  462. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  463. });
  464. }
  465. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  466. }
  467. /// <summary>
  468. /// 创建字典
  469. /// </summary>
  470. /// <param name="request"></param>
  471. /// <returns></returns>
  472. public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
  473. {
  474. return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
  475. {
  476. Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
  477. ExtensionData = string.Empty
  478. });
  479. }
  480. /// <summary>
  481. /// 查找设备型号所有字典项
  482. /// </summary>
  483. /// <param name="request"></param>
  484. /// <returns></returns>
  485. public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
  486. {
  487. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  488. {
  489. DictionaryType = (int)request.DictionaryType,
  490. ParentCode = request.DeviceTypeCode
  491. });
  492. return dictionaryDOList;
  493. }
  494. /// <summary>
  495. /// 查找设备类型所有字典项
  496. /// </summary>
  497. /// <param name="request"></param>
  498. /// <returns></returns>
  499. public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
  500. {
  501. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  502. {
  503. DictionaryType = (int)request.DictionaryType
  504. });
  505. return dictionaryDOList;
  506. }
  507. /// <summary>
  508. /// 根据组织编码查询所属全部设备信息
  509. /// </summary>
  510. /// <param name="request"></param>
  511. /// <returns></returns>
  512. public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
  513. {
  514. var result = new List<DeviceExtendInfoDTO>();
  515. var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
  516. if (deviceInfoDOList?.Count > 0)
  517. {
  518. //根据机构编号查询机构名称
  519. var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
  520. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
  521. var organizationName = organization?.OrganizationName ?? string.Empty;
  522. //根据机构编号查询科室名称
  523. var organizationFilter = new Dictionary<string, string>();
  524. organizationFilter.Add("RootCode", organizationCode);
  525. var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
  526. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  527. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  528. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  529. foreach (var c in deviceInfoDOList)
  530. {
  531. var deviceTypeName = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType)?.Value;
  532. if (string.IsNullOrWhiteSpace(deviceTypeName))
  533. {
  534. deviceTypeName = c.DeviceType;
  535. }
  536. result.Add(new DeviceExtendInfoDTO
  537. {
  538. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  539. OrganizationName = organizationName,
  540. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  541. DeviceCode = c.DeviceCode,
  542. SerialNumber = c.SerialNumber,
  543. Name = c.Name,
  544. Description = c.Description,
  545. DeviceModel = c.DeviceModel,
  546. DeviceType = c.DeviceType,
  547. HeadPicUrl = c.HeadPicUrl,
  548. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  549. SDKSoftwareVersion = c.SDKSoftwareVersion,
  550. OrganizationCode = c.OrganizationCode,
  551. DepartmentCode = c.DepartmentCode,
  552. ShortCode = c.ShortCode,
  553. DeviceTypeName = deviceTypeName
  554. });
  555. }
  556. }
  557. return result;
  558. }
  559. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  560. {
  561. throw new NotImplementedException();
  562. }
  563. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  564. {
  565. //验证
  566. var userCode = await GetClientIdByTokenAsync(request.Token);
  567. //查询用户是否存在
  568. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  569. if (userInfoDO == null)
  570. {
  571. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  572. }
  573. var result = new List<SelectItemDTO>();
  574. //查询用户的医院是否存在
  575. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  576. {
  577. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  578. }
  579. var deviceInfoDOList = new List<DeviceInfoDTO>();
  580. if (userInfoDO.IsDirector)
  581. {
  582. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  583. }
  584. else
  585. {
  586. //查询用户绑定的设备
  587. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  588. {
  589. return result;
  590. }
  591. //根据用户名下的设备id查询所有的设备信息
  592. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  593. }
  594. if (deviceInfoDOList?.Count > 0)
  595. {
  596. result = deviceInfoDOList.Select(c => new SelectItemDTO()
  597. {
  598. Key = c.DeviceCode,
  599. Value = c.Name
  600. }).ToList();
  601. }
  602. return result;
  603. }
  604. /// <summary>
  605. /// 设备端调用,查询获取服务器配置信息接口
  606. /// </summary>
  607. /// <param name="request">Token验证</param>
  608. /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
  609. public async Task<Dictionary<string, string>> QueryServerConfigAsync(TokenRequest request)
  610. {
  611. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  612. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  613. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  614. {
  615. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  616. }
  617. var org = new OrganizationDTO();
  618. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  619. {
  620. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  621. }
  622. var dictionary = new Dictionary<string, string>();
  623. //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
  624. //TODO 配置信息: 直播配置、存储配置、
  625. //存储上传图像或者视频是 是否本地上传缩略图
  626. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  627. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  628. dictionary.Add("PatientType", org.PatientType.ToString());
  629. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  630. return dictionary;
  631. }
  632. /// <summary>
  633. /// 添加或迁移设备到医院请求
  634. /// </summary>
  635. /// <param name="request"></param>
  636. /// <returns></returns>
  637. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  638. {
  639. var shortCode = request.UniqueCode;
  640. #region Params Check
  641. var userCode = await GetClientIdByTokenAsync(request.Token);
  642. if (string.IsNullOrEmpty(shortCode))
  643. {
  644. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  645. }
  646. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  647. if (device == null)
  648. {
  649. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  650. }
  651. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  652. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  653. {
  654. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  655. }
  656. //用户
  657. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  658. if (userDTO == null)
  659. {
  660. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  661. }
  662. if (!userDTO.IsDirector)
  663. {
  664. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  665. }
  666. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  667. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  668. {
  669. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  670. }
  671. #endregion
  672. try
  673. {
  674. var newOrgode = org.OrganizationCode;
  675. //设备更新医院
  676. if (!string.IsNullOrEmpty(device.DepartmentCode))
  677. {
  678. device.DepartmentCode = "";
  679. }
  680. if (!string.IsNullOrEmpty(device.Name))
  681. {
  682. device.Name = "";
  683. }
  684. device.HeadPicUrl = "";
  685. device.Description = "";
  686. device.IsAutoShared = false;
  687. device.OrganizationCode = newOrgode;
  688. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  689. if (success)
  690. {
  691. // 删除已知绑定的用户
  692. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  693. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  694. foreach (var user in users)
  695. {
  696. user.BindDevices.Remove(device.DeviceCode);
  697. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  698. {
  699. Data = user.MappingTo<UserPasswordDTO>(),
  700. });
  701. }
  702. if (updateUsers.Count > 0)
  703. {
  704. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  705. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  706. }
  707. if (oldOrg.Isinvented) // 虚拟医院
  708. {
  709. //迁移数据超声机上传检查记录
  710. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  711. //迁移数据超声机上传病人
  712. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  713. }
  714. }
  715. return success;
  716. }
  717. catch (System.Exception ex)
  718. {
  719. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  720. }
  721. return false;
  722. }
  723. /// <summary>
  724. /// 补齐设备扩展信息
  725. /// </summary>
  726. /// <param name="deviceInfoDOList"></param>
  727. /// <returns></returns>
  728. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
  729. {
  730. var deviceList = new List<DeviceExtendInfoDTO>();
  731. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  732. {
  733. //查询机构
  734. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  735. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  736. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  737. //查询机构负责人
  738. var organizationDirectorCodes = new List<string>();
  739. foreach (var org in organizations)
  740. {
  741. if (org.Directors != null && org.Directors.Any())
  742. {
  743. organizationDirectorCodes.AddRange(org.Directors);
  744. }
  745. }
  746. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  747. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  748. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  749. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  750. foreach (var dto in deviceInfoDOList)
  751. {
  752. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  753. device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
  754. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  755. device.DeviceTypeName = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.Value;
  756. if (string.IsNullOrWhiteSpace(device.DeviceTypeName))
  757. {
  758. device.DeviceTypeName = device.DeviceType;
  759. }
  760. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  761. if (organization != null)
  762. {
  763. device.OrganizationName = organization.OrganizationName;
  764. if (organization.Directors != null && organization.Directors.Any())
  765. {
  766. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  767. device.OrganizationDirectorCode = director?.UserCode;
  768. device.OrganizationDirectorUserName = director?.UserName;
  769. device.OrganizationDirectorFullName = director?.FullName;
  770. }
  771. }
  772. deviceList.Add(device);
  773. }
  774. }
  775. return deviceList;
  776. }
  777. /// <summary>
  778. /// 补齐设备扩展信息
  779. /// </summary>
  780. /// <param name="deviceInfoDOList"></param>
  781. /// <returns></returns>
  782. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  783. {
  784. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  785. return deviceList.FirstOrDefault();
  786. }
  787. /// <summary>
  788. /// 获取设备绑定用户codes
  789. /// </summary>
  790. /// <param name="request">获取设备绑定用户codes请求实体</param>
  791. /// <returns>test01,test02</returns>
  792. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  793. {
  794. //检查设备编码不为空
  795. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  796. {
  797. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  798. }
  799. //查询设备对象
  800. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  801. if (deviceDb == null)
  802. {
  803. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  804. }
  805. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  806. if (userListResult != null && userListResult.Count > 0)
  807. {
  808. return userListResult.Select(u => u.UserCode).ToList();
  809. }
  810. return new List<string>();
  811. }
  812. /// <summary>
  813. /// 查询设备AI应用的状态
  814. /// </summary>
  815. /// <param name="request">请求参数</param>
  816. /// <returns>AI应用集合</returns>
  817. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  818. {
  819. //检查设备编码不为空
  820. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  821. {
  822. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  823. }
  824. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  825. }
  826. /// <summary>
  827. /// 修改设备AI应用启用状态
  828. /// </summary>
  829. /// <param name="request">修改设备AI应用启用状态请求实体</param>
  830. /// <returns>是否成功</returns>
  831. /// <para>DeviceErrorCodeEnum</para>
  832. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  833. {
  834. //检查设备编码不为空
  835. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  836. {
  837. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  838. }
  839. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  840. {
  841. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  842. }
  843. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  844. {
  845. DeviceCode = request.DeviceCode,
  846. DiagnosisModule = request.DiagnosisModule,
  847. Enabled = request.Enabled
  848. });
  849. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  850. return result;
  851. }
  852. /// <summary>
  853. /// 通用异常处理方法
  854. /// </summary>
  855. /// <param name="customerRpcCodeEnum">异常标识码</param>
  856. /// <param name="msg">异常信息</param>
  857. /// <param name="internalMessage">内部异常信息,非必填</param>
  858. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  859. {
  860. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  861. }
  862. }
  863. }