DeviceService.cs 43 KB

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