DeviceService.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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. LanguageConfigs = deviceTypeModel.LanguageConfigs
  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 deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
  532. result.Add(new DeviceExtendInfoDTO
  533. {
  534. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  535. OrganizationName = organizationName,
  536. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  537. DeviceCode = c.DeviceCode,
  538. SerialNumber = c.SerialNumber,
  539. Name = c.Name,
  540. Description = c.Description,
  541. DeviceModel = c.DeviceModel,
  542. DeviceType = c.DeviceType,
  543. HeadPicUrl = c.HeadPicUrl,
  544. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  545. SDKSoftwareVersion = c.SDKSoftwareVersion,
  546. OrganizationCode = c.OrganizationCode,
  547. DepartmentCode = c.DepartmentCode,
  548. ShortCode = c.ShortCode,
  549. LanguageConfigs = deviceTypeModel?.LanguageConfigs
  550. });
  551. }
  552. }
  553. return result;
  554. }
  555. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  556. {
  557. throw new NotImplementedException();
  558. }
  559. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  560. {
  561. //验证
  562. var userCode = await GetClientIdByTokenAsync(request.Token);
  563. //查询用户是否存在
  564. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  565. if (userInfoDO == null)
  566. {
  567. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  568. }
  569. var result = new List<SelectItemDTO>();
  570. //查询用户的医院是否存在
  571. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  572. {
  573. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  574. }
  575. var deviceInfoDOList = new List<DeviceInfoDTO>();
  576. if (userInfoDO.IsDirector)
  577. {
  578. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  579. }
  580. else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  581. {
  582. //查询用户绑定的设备
  583. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  584. {
  585. return result;
  586. }
  587. //根据用户名下的设备id查询所有的设备信息
  588. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  589. }
  590. else
  591. {
  592. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  593. if (experts.Any())
  594. {
  595. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  596. if (bindDeviceCodes.Any())
  597. {
  598. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  599. }
  600. }
  601. else
  602. {
  603. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  604. }
  605. }
  606. if (deviceInfoDOList?.Count > 0)
  607. {
  608. result = deviceInfoDOList.Select(c => new SelectItemDTO()
  609. {
  610. Key = c.DeviceCode,
  611. Value = c.Name
  612. }).ToList();
  613. }
  614. return result;
  615. }
  616. /// <summary>
  617. /// 设备端调用,查询获取服务器配置信息接口
  618. /// </summary>
  619. /// <param name="request">Token验证</param>
  620. /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
  621. public async Task<Dictionary<string, string>> QueryServerConfigAsync(TokenRequest request)
  622. {
  623. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  624. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  625. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  626. {
  627. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  628. }
  629. var org = new OrganizationDTO();
  630. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  631. {
  632. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  633. }
  634. var dictionary = new Dictionary<string, string>();
  635. //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
  636. //TODO 配置信息: 直播配置、存储配置、
  637. //存储上传图像或者视频是 是否本地上传缩略图
  638. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  639. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  640. dictionary.Add("PatientType", org.PatientType.ToString());
  641. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  642. return dictionary;
  643. }
  644. /// <summary>
  645. /// 添加或迁移设备到医院请求
  646. /// </summary>
  647. /// <param name="request"></param>
  648. /// <returns></returns>
  649. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  650. {
  651. var shortCode = request.UniqueCode;
  652. #region Params Check
  653. var userCode = await GetClientIdByTokenAsync(request.Token);
  654. if (string.IsNullOrEmpty(shortCode))
  655. {
  656. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  657. }
  658. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  659. if (device == null)
  660. {
  661. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  662. }
  663. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  664. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  665. {
  666. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  667. }
  668. //用户
  669. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  670. if (userDTO == null)
  671. {
  672. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  673. }
  674. if (!userDTO.IsDirector)
  675. {
  676. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  677. }
  678. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  679. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  680. {
  681. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  682. }
  683. #endregion
  684. try
  685. {
  686. var newOrgode = org.OrganizationCode;
  687. //设备更新医院
  688. if (!string.IsNullOrEmpty(device.DepartmentCode))
  689. {
  690. device.DepartmentCode = "";
  691. }
  692. if (!string.IsNullOrEmpty(device.Name))
  693. {
  694. device.Name = "";
  695. }
  696. device.HeadPicUrl = "";
  697. device.Description = "";
  698. device.IsAutoShared = false;
  699. device.OrganizationCode = newOrgode;
  700. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  701. if (success)
  702. {
  703. // 删除已知绑定的用户
  704. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  705. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  706. foreach (var user in users)
  707. {
  708. user.BindDevices.Remove(device.DeviceCode);
  709. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  710. {
  711. Data = user.MappingTo<UserPasswordDTO>(),
  712. });
  713. }
  714. if (updateUsers.Count > 0)
  715. {
  716. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  717. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  718. }
  719. if (oldOrg.Isinvented) // 虚拟医院
  720. {
  721. //迁移数据超声机上传检查记录
  722. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  723. //迁移数据超声机上传病人
  724. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  725. }
  726. }
  727. return success;
  728. }
  729. catch (System.Exception ex)
  730. {
  731. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  732. }
  733. return false;
  734. }
  735. /// <summary>
  736. /// 补齐设备扩展信息
  737. /// </summary>
  738. /// <param name="deviceInfoDOList"></param>
  739. /// <returns></returns>
  740. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
  741. {
  742. var deviceList = new List<DeviceExtendInfoDTO>();
  743. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  744. {
  745. //查询机构
  746. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  747. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  748. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  749. //查询机构负责人
  750. var organizationDirectorCodes = new List<string>();
  751. foreach (var org in organizations)
  752. {
  753. if (org.Directors != null && org.Directors.Any())
  754. {
  755. organizationDirectorCodes.AddRange(org.Directors);
  756. }
  757. }
  758. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  759. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  760. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  761. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  762. foreach (var dto in deviceInfoDOList)
  763. {
  764. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  765. device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
  766. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  767. device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
  768. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  769. if (organization != null)
  770. {
  771. device.OrganizationName = organization.OrganizationName;
  772. if (organization.Directors != null && organization.Directors.Any())
  773. {
  774. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  775. device.OrganizationDirectorCode = director?.UserCode;
  776. device.OrganizationDirectorUserName = director?.UserName;
  777. device.OrganizationDirectorFullName = director?.FullName;
  778. }
  779. }
  780. deviceList.Add(device);
  781. }
  782. }
  783. return deviceList;
  784. }
  785. /// <summary>
  786. /// 补齐设备扩展信息
  787. /// </summary>
  788. /// <param name="deviceInfoDOList"></param>
  789. /// <returns></returns>
  790. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  791. {
  792. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  793. return deviceList.FirstOrDefault();
  794. }
  795. /// <summary>
  796. /// 获取设备绑定用户codes
  797. /// </summary>
  798. /// <param name="request">获取设备绑定用户codes请求实体</param>
  799. /// <returns>test01,test02</returns>
  800. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  801. {
  802. //检查设备编码不为空
  803. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  804. {
  805. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  806. }
  807. //查询设备对象
  808. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  809. if (deviceDb == null)
  810. {
  811. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  812. }
  813. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  814. if (userListResult != null && userListResult.Count > 0)
  815. {
  816. return userListResult.Select(u => u.UserCode).ToList();
  817. }
  818. return new List<string>();
  819. }
  820. /// <summary>
  821. /// 查询设备AI应用的状态
  822. /// </summary>
  823. /// <param name="request">请求参数</param>
  824. /// <returns>AI应用集合</returns>
  825. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  826. {
  827. //检查设备编码不为空
  828. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  829. {
  830. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  831. }
  832. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  833. }
  834. /// <summary>
  835. /// 修改设备AI应用启用状态
  836. /// </summary>
  837. /// <param name="request">修改设备AI应用启用状态请求实体</param>
  838. /// <returns>是否成功</returns>
  839. /// <para>DeviceErrorCodeEnum</para>
  840. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  841. {
  842. //检查设备编码不为空
  843. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  844. {
  845. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  846. }
  847. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  848. {
  849. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  850. }
  851. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  852. {
  853. DeviceCode = request.DeviceCode,
  854. DiagnosisModule = request.DiagnosisModule,
  855. Enabled = request.Enabled
  856. });
  857. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  858. return result;
  859. }
  860. /// <summary>
  861. /// 通用异常处理方法
  862. /// </summary>
  863. /// <param name="customerRpcCodeEnum">异常标识码</param>
  864. /// <param name="msg">异常信息</param>
  865. /// <param name="internalMessage">内部异常信息,非必填</param>
  866. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  867. {
  868. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  869. }
  870. }
  871. }