using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JsonRpcLite.Services;
using WingInterfaceLibrary.DTO.Device;
using WingInterfaceLibrary.Interface;
using WingInterfaceLibrary.Request.Device;
using WingInterfaceLibrary.DTO.Dictionary;
using WingServerCommon.Log;
using WingServerCommon.Service;
using WingInterfaceLibrary.Interface.DBInterface;
using WingInterfaceLibrary.DB.Request;
using WingServerCommon.Mapper;
using WingInterfaceLibrary.Request;
using WingInterfaceLibrary.Request.Authentication;
using WingInterfaceLibrary.DTO.User;
using WingInterfaceLibrary.DTO.Management;
using WingServerCommon.Config;
using WingDeviceService.Common;
using WingInterfaceLibrary.Request.User;
using WingInterfaceLibrary.Enum;
using WingInterfaceLibrary.DTO.Organization;
using WingInterfaceLibrary.DTO.DiagnosisModule;
using WingServerCommon.Config.Parameters;
using WingServerCommon.Interfaces.Cache;
using WingInterfaceLibrary.LiveConsultation;
namespace WingDeviceService.Service
{
///
/// 设备管理服务
///
public partial class DeviceService : JsonRpcService, IDeviceService
{
private IUserDBService _userServiceProxy;
private IDeviceInfoDBService _deviceInfoDBServiceProxy;
private IAuthenticationService _authenticationService;
private IOrganizationDBService _organizationDBService;
private INotificationService _notificationService;
private IRecordsInfoDBService _recordsInfoDBService;
private IPatientInfoDBService _patientInfoDBService;
private IDiagnosisModuleDBService _diagnosisModuleService;
private IRemedicalService _remedicalService;
private int _heartRateSeconds;
private DeviceHeartRateManager _deviceHeartRateManager;
///
/// Init service
///
public override void Load(JsonRpcClientPool jsonRpcClientPool)
{
base.Load(jsonRpcClientPool);
_userServiceProxy = GetProxy();
_authenticationService = GetProxy();
_deviceInfoDBServiceProxy = GetProxy();
_organizationDBService = GetProxy();
_notificationService = GetProxy();
_recordsInfoDBService = GetProxy();
_patientInfoDBService = GetProxy();
_diagnosisModuleService = GetProxy();
_remedicalService = GetProxy();
_heartRateSeconds = ConfigurationManager.GetParammeter("Device", "HeartRateSeconds").Value;
_deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
}
///
/// 设备心跳
///
///
///
public async Task HeartRateAsync(TokenRequest request)
{
_deviceHeartRateManager.AddOrUpdate(request.Token);
var result = SetOnlineState(request.Token, true);
return result;
}
private bool SetOnlineState(string token, bool isOnline)
{
return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
}
///
/// 添加分享设备关联用户请求
///
///
///
public async Task CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
{
var userCodes = request.UserCodes;
var deviceCode = request.DeviceCode;
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
if (userCodes == null || userCodes.Count <= 0)
{
ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
}
//查询设备对象
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
foreach (var userCode in userCodes)
{
var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (existUser == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
}
await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
{
DeviceCodes = new List { deviceCode },
UserCodes = userCodes.ToList()
});
return true;
}
///
/// 根据设备code获取设备信息
///
/// 设备code请求实体
/// 返回查询到的设备对象信息
public async Task GetDeviceInfoAsync(GetDeviceRequest request)
{
//验证
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
}
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
//根据机构编号查询机构名称
var organizationName = "";
if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
{
var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
organizationName = organization?.OrganizationName ?? string.Empty;
}
//根据机构编号查询科室名称
var departmentName = "";
if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
{
var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
departmentName = department?.OrganizationName ?? string.Empty;
}
//是否在线 todo
var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
var result = new DeviceExtendInfoDTO()
{
DepartmentName = departmentName,
OrganizationName = organizationName,
IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
DeviceCode = deviceDb.DeviceCode,
SerialNumber = deviceDb.SerialNumber,
Name = deviceDb.Name,
Description = deviceDb.Description,
DeviceModel = deviceDb.DeviceModel,
DeviceType = deviceDb.DeviceType,
HeadPicUrl = deviceDb.HeadPicUrl,
DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
OrganizationCode = deviceDb.OrganizationCode,
DepartmentCode = deviceDb.DepartmentCode,
ShortCode = deviceDb.ShortCode,
LanguageConfigs = deviceTypeModel.LanguageConfigs
};
return result;
}
///
/// 根据设备动态唯一码获取设备信息
///
///
///
public async Task GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
{
//验证
if (string.IsNullOrWhiteSpace(request.ShortCode))
{
ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
}
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
return await MapToExtendDTO(deviceDb);
}
public async Task> GetDeviceInfoPageAsync(PageFilterRequest request)
{
throw new System.NotImplementedException();
}
public async Task DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
{
var userCodes = request.UserCodes;
var deviceCode = request.DeviceCode;
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
//用户编码集合检查
if (userCodes == null || userCodes.Count <= 0)
{
ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
}
//查询设备对象
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
var updateUsers = new List>();
foreach (var userCode in userCodes)
{
var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (user != null)
{
if (user.BindDevices.Contains(deviceCode))
{
user.BindDevices.Remove(deviceCode);
updateUsers.Add(new TableDataItem()
{
Data = user.MappingTo(),
});
}
}
}
if (updateUsers.Count > 0)
{
var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
}
return true;
}
///
/// 机构设备移除-根据机构code和设备code解除其绑定关系
///
/// 移除设备请求实体
/// 移除是否成功:true-成功;false-失败
public async Task RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
{
//验证
if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
}
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
{
ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
}
//根据设备code和机构code查询相关数据,查到则删除关联
if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
{
deviceDb.DepartmentCode = "";
deviceDb.OrganizationCode = "";
}
else
{
deviceDb.OrganizationCode = "";
}
bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
return removeDeviceResult;
}
private async Task GetClientIdByTokenAsync(string token)
{
var request = new TokenRequest() { Token = token };
var result = await _authenticationService.GetTokenAsync(request);
return result.ClientId; //return User code
}
///
/// 查询个人名下所有设备列表接口
///
/// 查询个人名下所有设备列表请求实体
/// 返回设备信息列表
public async Task> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
{
//验证
var userCode = await GetClientIdByTokenAsync(request.Token);
//查询用户是否存在
var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (userInfoDO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
//查询用户的医院是否存在
if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
{
ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
}
var deviceInfoDOList = new List();
if (!userInfoDO.IsDirector)
{
//普通用户,查询用户绑定的设备
if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
{
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
}
}
else
{
//机构负责人
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
}
if (!deviceInfoDOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
var deviceList = await MapToExtendDTO(deviceInfoDOList);
//条件筛选
if (!string.IsNullOrWhiteSpace(request.DeviceType))
{
deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List();
}
if (!string.IsNullOrWhiteSpace(request.DeviceModel))
{
deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List();
}
if (!string.IsNullOrWhiteSpace(request.KeyWord))
{
var keyword = request.KeyWord.Trim().ToLower();
deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List();
}
if (request.IsOnline != null)
{
deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List();
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = deviceList.Count,
PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List()
};
return pagedResult;
}
///
/// 绑定设备
///
///
///
public async Task BindDeviceAsync(BindDeviceRequest request)
{
//验证
var userCode = await GetClientIdByTokenAsync(request.Token);
//查询用户是否存在
var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (userInfoDO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
}
if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
}
try
{
var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
deviceDb.Name = request.Name;
deviceDb.SerialNumber = request.SerialNumber;
deviceDb.Description = request.Description;
if (!string.IsNullOrEmpty(request.HeadPicUrl))
{
deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
}
deviceDb.DepartmentCode = request.DepartmentCode;
deviceDb.IsAutoShared = request.IsAutoShared;
deviceDb.OrganizationCode = request.OrganizationCode;
await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
{
var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
//迁移数据超声机上传检查记录
await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
//迁移数据超声机上传病人
await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
}
if (deviceDb.IsAutoShared)
{
var users = new List();
if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
{
users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List { deviceDb.DepartmentCode });
}
else
{
users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
}
var userCodes = users.Select(f => f.UserCode).ToList();
await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
{
DeviceCodes = new List { deviceDb.DeviceCode.ToString() },
UserCodes = userCodes.Select(f => f.ToString()).ToList()
});
}
return true;
}
catch (Exception ex)
{
Logger.WriteLineError($"BindDeviceAsync error {ex}");
}
return false;
}
///
/// 修改设备
///
///
///
public async Task ModifyDeviceAsync(ModifyDeviceRequest request)
{
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
}
if (string.IsNullOrWhiteSpace(request.Name))
{
ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
}
deviceDb.Name = request.Name;
if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
{
deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
}
else
{
deviceDb.HeadPicUrl = string.Empty;
}
deviceDb.DepartmentCode = request.DepartmentCode;
//修改自动分享
deviceDb.IsAutoShared = request.IsAutoShared;
if (deviceDb.IsAutoShared)
{
var users = new List();
if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
{
users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List { deviceDb.DepartmentCode });
}
else
{
users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
}
var userCodes = users.Select(f => f.UserCode).ToList();
//先解绑,再绑定,避免绑定重复设备code
var updateUsers = new List>();
foreach (var user in users)
{
var userPasswordDTO = user.MappingTo();
user.BindDevices?.Remove(deviceDb.DeviceCode);
await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
}
await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
{
DeviceCodes = new List { deviceDb.DeviceCode.ToString() },
UserCodes = userCodes.Select(f => f.ToString()).ToList()
});
}
return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
}
///
/// 创建字典
///
///
///
public async Task CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
{
return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
{
Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
ExtensionData = string.Empty
});
}
///
/// 查找设备型号所有字典项
///
///
///
public async Task> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
{
var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
{
DictionaryType = (int)request.DictionaryType,
ParentCode = request.DeviceTypeCode
});
return dictionaryDOList;
}
///
/// 查找设备类型所有字典项
///
///
///
public async Task> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
{
var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
{
DictionaryType = (int)request.DictionaryType
});
return dictionaryDOList;
}
///
/// 根据组织编码查询所属全部设备信息
///
///
///
public async Task> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
{
var result = new List();
var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
if (deviceInfoDOList?.Count > 0)
{
//根据机构编号查询机构名称
var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
var organizationName = organization?.OrganizationName ?? string.Empty;
//根据机构编号查询科室名称
var organizationFilter = new Dictionary();
organizationFilter.Add("RootCode", organizationCode);
var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
foreach (var c in deviceInfoDOList)
{
var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
result.Add(new DeviceExtendInfoDTO
{
DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
OrganizationName = organizationName,
IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
DeviceCode = c.DeviceCode,
SerialNumber = c.SerialNumber,
Name = c.Name,
Description = c.Description,
DeviceModel = c.DeviceModel,
DeviceType = c.DeviceType,
HeadPicUrl = c.HeadPicUrl,
DeviceSoftwareVersion = c.DeviceSoftwareVersion,
SDKSoftwareVersion = c.SDKSoftwareVersion,
OrganizationCode = c.OrganizationCode,
DepartmentCode = c.DepartmentCode,
ShortCode = c.ShortCode,
LanguageConfigs = deviceTypeModel?.LanguageConfigs
});
}
}
return result;
}
public Task CreateDeviceInfoAsync(CreateDeviceRequest request)
{
throw new NotImplementedException();
}
public async Task> GetPersonDeviceDropdownListAsync(TokenRequest request)
{
//验证
var userCode = await GetClientIdByTokenAsync(request.Token);
//查询用户是否存在
var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (userInfoDO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
var result = new List();
//查询用户的医院是否存在
if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
{
ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
}
var deviceInfoDOList = new List();
if (userInfoDO.IsDirector)
{
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
}
else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
{
//查询用户绑定的设备
if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
{
return result;
}
//根据用户名下的设备id查询所有的设备信息
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
}
else
{
var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
if (experts.Any())
{
var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List()).Distinct().ToList();
if (bindDeviceCodes.Any())
{
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
}
}
else
{
deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
}
}
if (deviceInfoDOList?.Count > 0)
{
result = deviceInfoDOList.Select(c => new SelectItemDTO()
{
Key = c.DeviceCode,
Value = c.Name
}).ToList();
}
return result;
}
///
/// 设备端调用,查询获取服务器配置信息接口
///
/// Token验证
/// 服务器配置信息结果:key:字段,value:数据值,复杂类型可为json
public async Task> QueryServerConfigAsync(TokenRequest request)
{
var deviceCode = await GetClientIdByTokenAsync(request.Token);
var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
var org = new OrganizationDTO();
if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
{
org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
}
var dictionary = new Dictionary();
//定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
//TODO 配置信息: 直播配置、存储配置、
//存储上传图像或者视频是 是否本地上传缩略图
var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
dictionary.Add("PatientType", org.PatientType.ToString());
dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
return dictionary;
}
///
/// 添加或迁移设备到医院请求
///
///
///
public async Task AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
{
var shortCode = request.UniqueCode;
#region Params Check
var userCode = await GetClientIdByTokenAsync(request.Token);
if (string.IsNullOrEmpty(shortCode))
{
ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
}
var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
if (device == null)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
{
ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
}
//用户
var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (userDTO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
if (!userDTO.IsDirector)
{
ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
}
var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
{
ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
}
#endregion
try
{
var newOrgode = org.OrganizationCode;
//设备更新医院
if (!string.IsNullOrEmpty(device.DepartmentCode))
{
device.DepartmentCode = "";
}
if (!string.IsNullOrEmpty(device.Name))
{
device.Name = "";
}
device.HeadPicUrl = "";
device.Description = "";
device.IsAutoShared = false;
device.OrganizationCode = newOrgode;
bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
if (success)
{
// 删除已知绑定的用户
var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
var updateUsers = new List>();
foreach (var user in users)
{
user.BindDevices.Remove(device.DeviceCode);
updateUsers.Add(new TableDataItem()
{
Data = user.MappingTo(),
});
}
if (updateUsers.Count > 0)
{
var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
}
if (oldOrg.Isinvented) // 虚拟医院
{
//迁移数据超声机上传检查记录
await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List() { device.DeviceCode }, newOrgode);
//迁移数据超声机上传病人
await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List() { device.DeviceCode }, newOrgode);
}
}
return success;
}
catch (System.Exception ex)
{
Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
}
return false;
}
///
/// 补齐设备扩展信息
///
///
///
private async Task> MapToExtendDTO(List deviceInfoDOList)
{
var deviceList = new List();
if (deviceInfoDOList != null && deviceInfoDOList.Any())
{
//查询机构
var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
//查询机构负责人
var organizationDirectorCodes = new List();
foreach (var org in organizations)
{
if (org.Directors != null && org.Directors.Any())
{
organizationDirectorCodes.AddRange(org.Directors);
}
}
var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
foreach (var dto in deviceInfoDOList)
{
var device = dto.MappingTo();
device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
if (organization != null)
{
device.OrganizationName = organization.OrganizationName;
if (organization.Directors != null && organization.Directors.Any())
{
var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
device.OrganizationDirectorCode = director?.UserCode;
device.OrganizationDirectorUserName = director?.UserName;
device.OrganizationDirectorFullName = director?.FullName;
}
}
deviceList.Add(device);
}
}
return deviceList;
}
///
/// 补齐设备扩展信息
///
///
///
private async Task MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
{
var deviceList = await MapToExtendDTO(new List { deviceInfoDO });
return deviceList.FirstOrDefault();
}
///
/// 获取设备绑定用户codes
///
/// 获取设备绑定用户codes请求实体
/// test01,test02
public async Task> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
{
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
//查询设备对象
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
}
var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
if (userListResult != null && userListResult.Count > 0)
{
return userListResult.Select(u => u.UserCode).ToList();
}
return new List();
}
///
/// 查询设备AI应用的状态
///
/// 请求参数
/// AI应用集合
public async Task> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
{
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
}
///
/// 修改设备AI应用启用状态
///
/// 修改设备AI应用启用状态请求实体
/// 是否成功
/// DeviceErrorCodeEnum
public async Task ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
{
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(request.DeviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
{
ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
}
var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
{
DeviceCode = request.DeviceCode,
DiagnosisModule = request.DiagnosisModule,
Enabled = request.Enabled
});
CacheMaintenance.Instance.Get().Remove(request.DeviceCode);
return result;
}
///
/// 设备离开会诊房间
///
/// 设备离开会诊房间请求实体
///
public async Task DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
{
var deviceCode = await GetClientIdByTokenAsync(request.Token);
var result = new DeviceLeaveLiveConsultationResult
{
Success = false,
};
return result;
}
///
/// 通用异常处理方法
///
/// 异常标识码
/// 异常信息
/// 内部异常信息,非必填
private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
{
ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
}
///
/// 上报设备画面尺寸相关信息
///
///
/// 设备端API
/// 实时会诊服务接口
/// 会诊
///
public async Task ReportVideoDeviceInfo(ReportVideoDeviceInfoRequest request)
{
var result = new ReportVideoDeviceInfoResult();
var deviceCode = await GetClientIdByTokenAsync(request.Token);
var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
deviceDTO.VideoDeviceInfos = request.VideoDeviceInfos;
await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDTO.DeviceCode, deviceDTO, null);
CacheMaintenance.Instance.Get().Remove(deviceDTO.DeviceCode);
result.Success = true;
return result;
}
}
}