using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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;
using WingInterfaceLibrary.Result.Languge;
using WingInterfaceLibrary.Internal.Interface;
using WingInterfaceLibrary.Notifications;
using WingInterfaceLibrary.Internal.Request;
using WingInterfaceLibrary.Rtc;
using WingInterfaceLibrary.Notifications.Live;
using WingInterfaceLibrary.Enum.NotificationEnum;
using WingInterfaceLibrary.Request.DBRequest;
using WingInterfaceLibrary.DTO.Record;
using WingInterfaceLibrary.DTO.Consultation;
using System.Collections.Concurrent;
using WingInterfaceLibrary.DTO.LiveRoom;
using WingInterfaceLibrary.Result;
using System.Threading.Tasks.Dataflow;
using WingServerCommon.Utilities.Executors;
using WingInterfaceLibrary.Request.Comment;
using WingInterfaceLibrary.DTO.Common;
namespace WingDeviceService.Service
{
///
/// 设备管理服务
///
public partial class DeviceService : JsonRpcService, IDeviceService, ISyncDeviceRemoteConnectService
{
//远程调参
private ConcurrentDictionary _controllingParameterDevices = new ConcurrentDictionary();
private IUserDBService _userServiceProxy;
private IDeviceInfoDBService _deviceInfoDBServiceProxy;
private IAuthenticationService _authenticationService;
private IOrganizationDBService _organizationDBService;
private IUserDBService _userDBService;
private INotificationService _notificationService;
private IRecordsInfoDBService _recordsInfoDBService;
private IPatientInfoDBService _patientInfoDBService;
private IDiagnosisModuleDBService _diagnosisModuleService;
private IRemedicalService _remedicalService;
private IWingRtcService _wingRtcService;
private IRtcService _rtcService;
private IRtmpService _rtmpService;
private int _heartRateSeconds => EnvironmentConfigManager.GetParammeter("Device", "HeartRateSeconds").Value;
private DeviceHeartRateManager _deviceHeartRateManager;
private RemoteConnectManager _remoteConnectManager;
private string _webSocketUrl => EnvironmentConfigManager.GetParammeter("Notification", "WebSocketUrl").Value;
private int _liveConsultationRateSeconds => EnvironmentConfigManager.GetParammeter("LiveConsultation", "HeartRateSeconds").Value;
// private int _remoteControlAskTimeoutSec => EnvironmentConfigManager.GetParammeter("Device", "RemoteControlAskTimeoutSec").Value;
private int _remoteControlHeartRateSeconds => EnvironmentConfigManager.GetParammeter("Device", "RemoteControlHeartRateSeconds").Value;
private int _reportStateIntervalSeconds => EnvironmentConfigManager.GetParammeter("LiveConsultation", "ReportStateIntervalSeconds").Value;
private int _reportStateTimeout = 0;
private string _deviceShareUrl => EnvironmentConfigManager.GetParammeter("Share", "DeviceLiveUrl").Value;
private int _shareEffectiveSeconds => EnvironmentConfigManager.GetParammeter("Share", "DeviceLiveEffectiveSeconds").Value;
private ILiveConsultationService _liveConsultationService;
private IConsultationRecordDBService _consultationRecordDBService;
private IRemedicalDBService _remedicalDBService;
private IShareDBService _shareDBService;
private IMasterInteractionCenterService _masterInteractionCenterService;
private string _serverID;
private IDeviceForwardService _deviceForwardService;
private readonly SequenceExecutor _modifyDeviceExecutor = new SequenceExecutor("UpdateDeviceInvented");
///
/// Init service
///
public override void Load(JsonRpcClientPool jsonRpcClientPool)
{
base.Load(jsonRpcClientPool);
_userServiceProxy = GetProxy();
_authenticationService = GetProxy();
_deviceInfoDBServiceProxy = GetProxy();
_userDBService = GetProxy();
_organizationDBService = GetProxy();
_notificationService = GetProxy();
_recordsInfoDBService = GetProxy();
_patientInfoDBService = GetProxy();
_diagnosisModuleService = GetProxy();
_remedicalService = GetProxy();
_wingRtcService = GetProxy();
_rtcService = GetProxy();
_rtmpService = GetProxy();
_liveConsultationService = GetProxy();
_consultationRecordDBService = GetProxy();
_remedicalDBService = GetProxy();
_shareDBService = GetProxy();
_masterInteractionCenterService = GetProxy();
_deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState, CheckDeviceLiveStatus);
_remoteConnectManager = new RemoteConnectManager(RemoteConnectOnlineState, DeviceRemoteConnectOnlineState, _authenticationService);
_reportStateTimeout = _reportStateIntervalSeconds + 60;
_serverID = ConfigurationManager.GetParammeter("General", "ServerID").Value;
}
///
/// default server restart run
///
public override void LoadAfterRegister()
{
try
{
_deviceForwardService = GetProxy();
}
catch (Exception ex)
{
Logger.WriteLineWarn($"DeviceService LoadAfterRegister err, {ex}");
}
}
///
/// 设备心跳
///
///
///
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;
}
private bool CheckDeviceLiveStatus()
{
try
{
_rtcService.CheckDeviceLiveRoomAsync(new TokenRequest { });
}
catch (Exception ex)
{
Logger.WriteLineWarn($"DeviceService CheckDeviceLiveStatus err, ex:{ex}");
}
return true;
}
///
/// 添加分享设备关联用户请求
///
///
///
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 },
OrganizationCodes = new List() { deviceDb.OrganizationCode },
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 = "";
var patientType = OrganizationPatientTypeEnum.Person;
if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
{
var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
organizationName = organization?.OrganizationName ?? string.Empty;
patientType = organization?.PatientType ?? OrganizationPatientTypeEnum.Person;
}
//根据机构编号查询科室名称
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 = deviceDb.MappingTo();
result.DepartmentName = departmentName;
result.OrganizationName = organizationName;
result.IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode);
result.IsCanRemoteMaintenance = true;
result.LanguageConfigs = deviceTypeModel?.LanguageConfigs ?? new List();
result.PatientType = patientType;
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.ToLower() != request.ShortCode.ToLower())
{
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);
// 删除已知绑定的用户
var users = await _userServiceProxy.GetUsersByDeviceAsync(deviceDb.DeviceCode);
var updateUsers = new List>();
foreach (var user in users)
{
user.BindDevices.Remove(deviceDb.DeviceCode);
updateUsers.Add(new TableDataItem()
{
Data = user.MappingTo(),
});
}
if (updateUsers.Count > 0)
{
var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
}
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> GetOrganizationDeviceListAsync(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");
}
//判断是否机构管理员
if (!userInfoDO.IsDirector)
{
ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "Not organization administrator");
}
var deviceInfoDTOList = new List();
var dbPage = new PageResult();
var dbRequest = new FindDeviceInfoPageRequest()
{
PageIndex = request.PageIndex,
PageSize = request.PageSize,
DeviceType = request.DeviceType,
DeviceModel = request.DeviceModel,
KeyWord = request.KeyWord,
IsOnline = request.IsOnline,
OrganizationCodes = request.OrganizationCodes
};
var tokenList = CacheMaintenance.Instance.Get().Where(c => (c.AccountType == 2 || c.AccountType == 3) && c.IsOnline == true)?.ToList();
if (tokenList?.Count > 0)
{
dbRequest.IsOnlineCodes = tokenList.Select(c => c.ClientId).Distinct().ToList();
}
//机构负责人
var orgCodes = new List { userInfoDO.RootOrganizationCode };
var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
{
orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
}
dbRequest.OrgCodes = orgCodes;
dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
if (dbPage?.PageData?.Count > 0)
{
deviceInfoDTOList = dbPage.PageData;
}
if (!deviceInfoDTOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
foreach (var device in deviceList)
{
device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = dbPage.TotalCount,
PageData = deviceList
};
return pagedResult;
}
///
/// 查询个人名下本机构所有设备列表接口
///
///
/// 返回设备信息列表
/// UserNotExistError,OrganizationNotExist
public async Task> GetPersonOrgDeviceListAsync(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 deviceInfoDTOList = new List();
var dbPage = new PageResult();
var dbRequest = new FindDeviceInfoPageRequest()
{
UserCode = userCode,
PageIndex = request.PageIndex,
PageSize = request.PageSize,
DeviceType = request.DeviceType,
DeviceModel = request.DeviceModel,
KeyWord = request.KeyWord,
IsOnline = request.IsOnline,
OrganizationCodes = request.OrganizationCodes
};
dbPage = await _deviceInfoDBServiceProxy.FindMyOrgDeviceInfoListPageDBAsync(dbRequest);
if (dbPage?.PageData?.Count > 0)
{
deviceInfoDTOList = dbPage.PageData;
}
if (!deviceInfoDTOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
foreach (var device in deviceList)
{
device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = dbPage.TotalCount,
PageData = deviceList
};
return pagedResult;
}
///
/// 查询个人名下所有设备列表接口
///
/// 查询个人名下所有设备列表请求实体
/// 返回设备信息列表
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 deviceInfoDTOList = new List();
//普通用户,查询用户绑定的设备
var dbPage = new PageResult();
var dbRequest = new FindDeviceInfoPageRequest()
{
PageIndex = request.PageIndex,
PageSize = request.PageSize,
DeviceType = request.DeviceType,
DeviceModel = request.DeviceModel,
KeyWord = request.KeyWord,
IsOnline = request.IsOnline,
OrganizationCodes = request.OrganizationCodes
};
var tokenList = CacheMaintenance.Instance.Get().Where(c => (c.AccountType == 2 || c.AccountType == 3) && c.IsOnline == true)?.ToList();
if (tokenList?.Count > 0)
{
dbRequest.IsOnlineCodes = tokenList.Select(c => c.ClientId).Distinct().ToList();
}
if (userInfoDO.IsDirector)
{
//机构负责人
var orgCodes = new List { userInfoDO.RootOrganizationCode };
var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
{
orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
}
dbRequest.OrgCodes = orgCodes;
}
dbRequest.DeviceCodes = userInfoDO.BindDevices;
dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
if (dbPage?.PageData?.Count > 0)
{
deviceInfoDTOList = dbPage.PageData;
}
if (!deviceInfoDTOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
foreach (var device in deviceList)
{
device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = dbPage.TotalCount,
PageData = deviceList
//PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List()
};
return pagedResult;
}
///
/// 查询设备列表(助理查专家的如果没有专家则查机构的)
///
/// 查询设备列表请求实体
/// 返回设备信息列表
public async Task> GetDeviceListByPersonRoleAsync(GetPersonRoleDeviceRequest 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 deviceInfoDTOList = new List();
//普通用户,查询用户绑定的设备
if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
{
deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
}
if (userInfoDO.IsDirector)
{
//机构负责人
var orgCodes = new List { userInfoDO.RootOrganizationCode };
var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
{
orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
}
var orgDeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodesAsync(orgCodes);
if (orgDeviceInfoDTOList != null && orgDeviceInfoDTOList.Count > 0)
{
var devinceInfoCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
foreach (var item in orgDeviceInfoDTOList)
{
if (!devinceInfoCodes.Contains(item.DeviceCode))
{
deviceInfoDTOList.Add(item);
}
}
}
}
//助理
if (userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
{
var basedeviceInfoDTOList = new List();
var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
if (experts.Any())
{
var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List()).Distinct().ToList();
if (bindDeviceCodes.Any())
{
basedeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
}
}
else
{
basedeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
}
if (deviceInfoDTOList.Count > 0)
{
var deviceCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
foreach (var item in basedeviceInfoDTOList)
{
if (!deviceCodes.Contains(item.DeviceCode))
{
deviceInfoDTOList.Add(item);
}
}
}
else
{
deviceInfoDTOList.AddRange(basedeviceInfoDTOList);
}
}
if (!deviceInfoDTOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
//条件筛选
if (!string.IsNullOrWhiteSpace(request.DeviceType))
{
deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List();
}
if (!string.IsNullOrWhiteSpace(request.DeviceModel))
{
deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List();
}
if (!string.IsNullOrWhiteSpace(request.KeyWord))
{
string keyword = request.KeyWord.Trim().ToLower();
deviceInfoDTOList = deviceInfoDTOList.Where(d => (!string.IsNullOrWhiteSpace(d.Description) && d.Description.ToLower().Contains(keyword)) || (!string.IsNullOrWhiteSpace(d.Name) && d.Name.ToLower().Contains(keyword)) || ((!string.IsNullOrWhiteSpace(d.ShortCode) && d.ShortCode.ToLower().Contains(keyword))))?.ToList() ?? new List();
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = deviceInfoDTOList.Count,
PageData = deviceInfoDTOList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List()
};
return pagedResult;
}
///
/// 更新虚拟设备检查和病人信息
///
/// 请求实体
///
private bool OnUpdateInventedDeviceInfoAsync(ModifyDeviceRequest request)
{
try
{
//迁移数据超声机上传检查记录
var orgResult = _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List() { request.DeviceCode }, request.DepartmentCode).Result;
//迁移数据超声机上传病人
var patientResult = _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List() { request.DeviceCode }, request.DepartmentCode).Result;
}
catch (Exception ex)
{
Logger.WriteLineWarn($"save admin statistic info failed, ex:{ex}");
}
return true;
}
///
/// 机构负责人,机构绑定设备
///
///
///
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");
}
if (string.IsNullOrEmpty(request.ShortCode))
{
ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCodeEmpty");
}
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");
}
// //判断设备绑定机构是否跟用户的机构一致
// //判断父子级,父级可以绑定子集机构的设备 杏聆荟平台可以绑定任何设备
// var orgCodes = new List { userInfoDO.RootOrganizationCode };
// var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
// if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
// {
// orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
// }
// if (userInfoDO.RootOrganizationCode != "VINNO_FIS" && !string.IsNullOrEmpty(deviceDb.OrganizationCode) && !orgCodes.Contains(deviceDb.OrganizationCode))
// {
// ThrowCustomerException(CustomerRpcCode.OrganizationCodeInconformity, "Organization code inconformity");
// }
if (string.IsNullOrEmpty(request.Description))
{
ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "DeviceNameEmpty");
}
if (request.Name.Length > 50)
{
ThrowCustomerException(CustomerRpcCode.TooLongCharacter, "TooLongCharacter");
}
try
{
var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == "VINNO_FIS") ? true : false;
if (!string.IsNullOrEmpty(request.Description))
{
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) //虚拟机构改为正常机构
{
if (string.IsNullOrWhiteSpace(request.OrganizationCode) && string.IsNullOrWhiteSpace(request.DepartmentCode))
{
ThrowCustomerException(CustomerRpcCode.OrganizationCodeEmpty, "OrganizationCodeEmpty");
}
var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
var orgInfo = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = newOrgCode });
if (orgInfo == null)
{
ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "OrganizationNotExist");
}
// //迁移数据超声机上传检查记录
// await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
// //迁移数据超声机上传病人
// await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
_modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
}
var userCodes = new List();
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 });
}
userCodes = users.Select(f => f.UserCode).ToList();
}
else
{
userCodes.Add(userCode);
}
await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
{
DeviceCodes = new List() { deviceDb.DeviceCode },
OrganizationCodes = new List() { deviceDb.OrganizationCode },
UserCodes = userCodes
});
return true;
}
catch (Exception ex)
{
Logger.WriteLineError($"BindDeviceAsync error {ex}");
}
return false;
}
///
/// 修改设备全部信息
///
///
///
public async Task UpdateDeviceAsync(UpdateDeviceRequest request)
{
var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
if (deviceDb == null)
{
ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
}
//全部覆盖
deviceDb = request.MappingTo();
return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
}
///
/// 修改设备
///
///
///
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.Description))
{
ThrowCustomerException(CustomerRpcCode.DeviceDescriptionEmpty, "Device description cannot be empty");
}
//当设备描述为空或者设备描述与设备名称一致的情况下,所有用户都有编辑描述和封面的功能
if (string.IsNullOrEmpty(deviceDb.Description) || deviceDb.Description == deviceDb.Name)
{
if (!string.IsNullOrWhiteSpace(request.Description))
{
deviceDb.Description = request.Description;
}
}
deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
if (!string.IsNullOrEmpty(deviceDb.Description) && !string.IsNullOrEmpty(request.Description) && deviceDb.Description != request.Description)
{
ThrowCustomerException(CustomerRpcCode.DeviceDescriptionNotModify, "Device description not modify");
}
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 },
OrganizationCodes = new List() { deviceDb.OrganizationCode },
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 deviceInfoDTOList = new List();
if (userInfoDO.IsDirector)
{
//查询个人的设备数据
deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
//查询机构的设备数据
var orgCodes = new List { userInfoDO.RootOrganizationCode };
var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
{
orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
}
var orgDeviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodesAsync(orgCodes);
if (orgDeviceInfoDTOList != null && orgDeviceInfoDTOList.Count > 0)
{
var devinceInfoCodes = deviceInfoDTOList.Select(x => x.DeviceCode);
foreach (var item in orgDeviceInfoDTOList)
{
if (!devinceInfoCodes.Contains(item.DeviceCode))
{
deviceInfoDTOList.Add(item);
}
}
}
}
else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
{
//查询用户绑定的设备
if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
{
return result;
}
//根据用户名下的设备id查询所有的设备信息
deviceInfoDTOList = 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())
{
deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
}
}
else
{
deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
}
}
if (deviceInfoDTOList?.Count > 0)
{
result = deviceInfoDTOList.Select(c => new SelectItemDTO()
{
Key = c.DeviceCode,
Value = c.Description ?? 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 });
if (org == null)
{
org = new OrganizationDTO();
}
}
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());
dictionary.Add("NotificationUrl", _webSocketUrl);
dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
var liveProtocol = string.Empty;
var _isRTCSelf = false;
var liveProtocolType = TransactionStatusEnum.Common;
try
{
var rtcType = EnvironmentConfigManager.GetParammeter("Rtc", "RTCType").Value;
_isRTCSelf = rtcType == "VRTC";
if (EnvironmentConfigs.General.LiveProtocol.ToLower() == "rtmp")
{
liveProtocol = EnvironmentConfigs.Rtmp.RTMPType;
}
else
{
liveProtocol = EnvironmentConfigs.Rtc.RTCType;
}
liveProtocolType = EnvironmentConfigs.General.LiveProtocolDetail();
}
catch (Exception ex)
{
Logger.WriteLineWarn($"DeviceService liveProtocol not config");
}
var result = new DeviceServerSettingResult()
{
ServerConfigList = dictionary,
IsUploadThumbnail = isUploadThumbnail,
PatientType = org.PatientType,
HeartRateSeconds = _heartRateSeconds,
NotificationUrl = _webSocketUrl,
LiveConsultationRateSeconds = _liveConsultationRateSeconds,
MergedChannel = deviceInfo.MergedChannel,
MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
IsSelfRtcService = _isRTCSelf,
// RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec,
RemoteControlHeartRateSeconds = _remoteControlHeartRateSeconds,
LiveProtocol = liveProtocol,
LiveProtocolType = liveProtocolType,
FISWebUrl = EnvironmentConfigManager.GetParammeter("Gateway", "FISWebUrl").Value,
IsResearchEditionService = GetIsResearchEditionService(),
};
return result;
}
private bool GetIsResearchEditionService()
{
var result = false;
try
{
result = EnvironmentConfigManager.GetParammeter("General", "IsResearchEditionService").Value;
}
catch
{
}
return result;
}
///
/// 添加或迁移设备到医院请求(废弃)
///
///
///
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, UserDTO userInfo = null)
{
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();
var deviceTokenInfo = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode);
device.IsOnline = deviceTokenInfo?.IsOnline ?? false;
var curOrgInfo = organizations.FirstOrDefault(c => c.OrganizationCode == dto.OrganizationCode) ?? new OrganizationDTO();
device.PatientType = curOrgInfo?.PatientType ?? OrganizationPatientTypeEnum.Person;
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;
}
}
if (device.DeviceType.ToLower() == "sonopost")
{
device.IsCanRestart = true;
if (deviceTokenInfo != null && deviceTokenInfo.IsOldPlatform)
{
device.IsCanRestart = false;
}
}
if (userInfo != null)
{
//调整逻辑,只有远程维护权限的,才能开启远程维护功能,机构管理员如果没有远程维护菜单,则不能开启远程控制,自己机构的设备也不行;
if (userInfo.UserFeatureCodes != null && userInfo.UserFeatureCodes.Exists(c => c == "RemoteMaintain" || c == "RemoteManager"))
{
//远程维护管理员,那么权限全开
device.IsCanRemoteMaintenance = true;
}
// else if (userInfo.IsDirector)
// {
// //如果是机构管理员,本机构的设备才可以有权限,非本机构的无远程维护权限
// if (!string.IsNullOrEmpty(userInfo.OrganizationCode) && !string.IsNullOrEmpty(device.OrganizationCode) && userInfo.OrganizationCode == device.OrganizationCode)
// {
// device.IsCanRemoteMaintenance = true;
// }
// else
// {
// device.IsCanRemoteMaintenance = false;
// }
// }
else
{
device.IsCanRemoteMaintenance = false;
}
}
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应用启用状态请求实��/param>
/// 是否成功
/// 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 ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
{
var tokenInfo = await _authenticationService.GetTokenAsync(request);
var result = new ReportVideoDeviceInfoResult();
request.VideoDeviceInfos = request.VideoDeviceInfos?.ToList() ?? new List();
if (request.VideoDeviceInfos.Any())
{
if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
{
//视屏设备ID为空
ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
}
var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
{
//视屏设备ID重复
ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
}
}
var deviceCode = tokenInfo.ClientId;
var isOldPlatform = tokenInfo != null && tokenInfo.IsOnline && tokenInfo.IsOldPlatform;
var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
var screenAndCamera = request.VideoDeviceInfos.Any(x => x.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Camera);
var outputWidth = deviceDTO.MergedVideoOutputWidth;
var outputHeight = deviceDTO.MergedVideoOutputHeight;
if (outputWidth <= 0 || outputHeight <= 0)
{
outputWidth = 1280;
outputHeight = 720;
}
if (!deviceDTO.MergedChannel)
{
var highCpu = _highCpuLevels?.Split(',');
if (deviceDTO.DeviceModel.ToUpper().StartsWith("SP002"))
{
outputWidth = _highMergedVideoOutputWidth;
outputHeight = _highMergedVideoOutputHeight;
}
else if (highCpu != null && highCpu.Contains(deviceDTO.CPUModel))
{
outputWidth = _highMergedVideoOutputWidth;
outputHeight = _highMergedVideoOutputHeight;
}
else if (deviceDTO.CPUModel.StartsWith("I"))
{
int.TryParse(deviceDTO.CPUModel.Substring(1, deviceDTO.CPUModel.IndexOf('-') - 1), out int cpuLevel);
if (cpuLevel >= 5)
{
outputWidth = _highMergedVideoOutputWidth;
outputHeight = _highMergedVideoOutputHeight;
}
else
{
outputWidth = _lowMergedVideoOutputWidth;
outputHeight = _lowMergedVideoOutputHeight;
}
}
else
{
outputWidth = _lowMergedVideoOutputWidth;
outputHeight = _lowMergedVideoOutputHeight;
}
}
var videoDeviceInfos = new List();
foreach (var video in request.VideoDeviceInfos)
{
var videoDeviceInfo = InitOutputInfo(video, deviceDTO.MergedChannel, screenAndCamera, outputWidth, outputHeight);
if (isOldPlatform)
{
videoDeviceInfo.OutputWidth = videoDeviceInfo.Width;
videoDeviceInfo.OutputHeight = videoDeviceInfo.Height;
}
videoDeviceInfos.Add(videoDeviceInfo);
}
var deviceVideoChanged = DeviceVideoInfoHasChange(request.LiveOpened, videoDeviceInfos, deviceDTO);
deviceDTO.VideoDeviceInfos = videoDeviceInfos;
var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
{
DeviceCode = deviceDTO.DeviceCode,
LiveOpened = request.LiveOpened,
VideoDeviceInfos = videoDeviceInfos,
IsSync = request.IsSync
};
await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
CacheMaintenance.Instance.Get().Remove(deviceDTO.DeviceCode);
if (deviceVideoChanged && !string.IsNullOrWhiteSpace(deviceDTO.ShortCode))
{
_rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
{
DeviceShortCode = deviceDTO.ShortCode,
CloseDevicePush = true,
});
}
result.Success = true;
result.VideoDeviceOutputInfos = videoDeviceInfos;
return result;
}
private bool DeviceVideoInfoHasChange(bool liveOpened, List videoDeviceInfos, DeviceInfoDTO oldDeviceInfo)
{
if (liveOpened != oldDeviceInfo.LiveOpened)
{
return true;
}
if (oldDeviceInfo.VideoDeviceInfos == null || !oldDeviceInfo.VideoDeviceInfos.Any())
{
if (videoDeviceInfos.Any())
{
return true;
}
}
else if (oldDeviceInfo.VideoDeviceInfos.Count != videoDeviceInfos.Count)
{
return true;
}
else
{
foreach (var videoInfo in videoDeviceInfos)
{
var oldVideoInfo = oldDeviceInfo.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == videoInfo.VideoDeviceId);
if (oldVideoInfo == null)
{
return true;
}
if (oldVideoInfo.VideoDeviceSourceType != videoInfo.VideoDeviceSourceType
|| oldVideoInfo.Width != videoInfo.Width
|| oldVideoInfo.Height != videoInfo.Height)
{
return true;
}
}
}
return false;
}
private VideoDeviceDTO InitOutputInfo(VideoDeviceInfo videoDeviceInfo, bool mergedChannel, bool screenAndCamera, int maxWidth, int maxHeight)
{
// 给到设备端的输出尺寸,一定需要保持上报设备分辨率的宽高比
// CPU好的输出尺寸不能超过1080P,CPU较差的输出尺寸不能超过720P
// 单路情况,主频画面小于推荐尺寸,保持不变;主屏画面大于推荐尺寸,保持上报设备分辨率宽高比缩小
// (CPU好的情况帧率20,码率3000,最小帧率设为0(SDK自由设置)
// (CPU较差的情况)帧率15,码率2000,最小帧率设为0(SDK自由设置)
// 多路情况:1080P降到1280*720,720P降到1280*540
// 多路分流,保持上报设备分辨率宽高比缩小
// 多路合流(摄像头):640*480(CPU好的情况);640*360(CPU较差的情况)
// (CPU好的情况帧率20,码率3000,最小帧率设为2000
// (CPU较差的情况)帧率15,码率2000,最小帧率设为1000
var bestCpu = maxWidth == 1920;
var outputInfo = new VideoDeviceDTO
{
VideoDeviceId = videoDeviceInfo.VideoDeviceId,
VideoDeviceSourceType = videoDeviceInfo.VideoDeviceSourceType,
Width = videoDeviceInfo.Width,
Height = videoDeviceInfo.Height,
OutputWidth = videoDeviceInfo.Width,
OutputHeight = videoDeviceInfo.Height,
};
//输出分辨率
var width = videoDeviceInfo.Width;
var height = Math.Max(videoDeviceInfo.Height, 1);
if (!screenAndCamera)
{
//单路
if (bestCpu)
{
InitFpsAndBitrate(outputInfo, 20, 3000, 0);
InitDesktopOutputSize(outputInfo, 1920, 1080);
}
else
{
InitFpsAndBitrate(outputInfo, 15, 2000, 0);
InitDesktopOutputSize(outputInfo, 1280, 720);
}
}
else
{
if (mergedChannel)
{
//多路合流
if (bestCpu)
{
InitFpsAndBitrate(outputInfo, 20, 3000, 2000);
InitDesktopOutputSize(outputInfo, 1280, 720);
InitCameraOutputSize(outputInfo, 640, 480, true);
}
else
{
InitFpsAndBitrate(outputInfo, 15, 2000, 1000);
InitDesktopOutputSize(outputInfo, 1280, 540);
InitCameraOutputSize(outputInfo, 640, 360, true);
}
}
else
{
//多路分流
if (bestCpu)
{
InitFpsAndBitrate(outputInfo, 20, 3000, 2000);
InitDesktopOutputSize(outputInfo, 1280, 720);
InitCameraOutputSize(outputInfo, 1280, 720);
}
else
{
InitFpsAndBitrate(outputInfo, 15, 2000, 1000);
InitDesktopOutputSize(outputInfo, 1280, 540);
InitCameraOutputSize(outputInfo, 1280, 540);
}
}
}
return outputInfo;
}
private void InitFpsAndBitrate(VideoDeviceDTO outputInfo, int videoFps, int videoBitrate, int minVideoBitrate)
{
outputInfo.VideoFps = videoFps;
outputInfo.VideoBitrate = videoBitrate;
outputInfo.MinVideoBitrate = minVideoBitrate;
}
private void InitDesktopOutputSize(VideoDeviceDTO outputInfo, int maxWidth, int maxHeight)
{
if (outputInfo.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Desktop)
{
if (outputInfo.Width <= maxWidth && outputInfo.Height <= maxHeight)
{
outputInfo.OutputWidth = outputInfo.Width;
outputInfo.OutputHeight = outputInfo.Height;
}
else
{
var radio = (double)outputInfo.Width / Math.Max(outputInfo.Height, 1);
if (outputInfo.Height > maxHeight)
{
outputInfo.OutputHeight = maxHeight;
outputInfo.OutputWidth = (int)(maxHeight * radio);
}
if (outputInfo.OutputWidth > maxWidth)
{
outputInfo.OutputWidth = maxWidth;
outputInfo.OutputHeight = (int)(maxWidth / radio);
}
}
}
}
private void InitCameraOutputSize(VideoDeviceDTO outputInfo, int maxWidth, int maxHeight, bool fixedSize = false)
{
if (outputInfo.VideoDeviceSourceType == VideoDeviceSourceTypeEnum.Camera)
{
if (fixedSize)
{
outputInfo.OutputWidth = maxWidth;
outputInfo.OutputHeight = maxHeight;
}
else if (outputInfo.Width <= maxWidth && outputInfo.Height <= maxHeight)
{
outputInfo.OutputWidth = outputInfo.Width;
outputInfo.OutputHeight = outputInfo.Height;
}
else
{
var radio = (double)outputInfo.Width / Math.Max(outputInfo.Height, 1);
if (outputInfo.Height > maxHeight)
{
outputInfo.OutputHeight = maxHeight;
outputInfo.OutputWidth = (int)(maxHeight * radio);
}
if (outputInfo.OutputWidth > maxWidth)
{
outputInfo.OutputWidth = maxWidth;
outputInfo.OutputHeight = (int)(maxWidth / radio);
}
}
}
}
///
/// 查找有效设备总数量
///
///
public async Task GetActiveDeviceCount()
{
return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
}
///
/// 设备发送调参初始化数据
///
/// 调参数据请求
///
public async Task SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
{
var deviceCode = await GetClientIdByTokenAsync(request.Token);
var userCode = request.ControlUserCode;
//发送控制人通知
if (string.IsNullOrWhiteSpace(userCode))
{
ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
}
var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
if (userDTO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
var notify = new DeviceParametersNotification()
{
DeviceCode = deviceCode,
IsResponse = true
};
var key = deviceCode;
var cacheControllingParameter = new CacheControllingParameter()
{
Code = userCode + "_" + deviceCode,
ProbeApplication = Newtonsoft.Json.JsonConvert.SerializeObject(request.ProbeApplication),
Parameter = Newtonsoft.Json.JsonConvert.SerializeObject(request.Parameter),
};
AddControllingParameter(key, cacheControllingParameter);
var notificationRequest = new SendNotificationRequest()
{
ClientId = userCode,
Message = notify,
JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
NotificationType = notify.NotificationType,
TransactionType = TransactionTypeEnum.ControlParameter,
RelevanceCode = userCode,
ReceiverType = ApplicantTypeEnum.Client,
WSConnectType = WSConnectTypeEnum.ConsultationSecondWindow,
IsNeedSyn = true,
};
await _notificationService.PostMessageAsync(notificationRequest);
return true;
}
private async Task AddControllingParameter(string key, CacheControllingParameter value)
{
_controllingParameterDevices.AddOrUpdate(key, value, (a, b) => value);
if (ConfigurationManager.IsDistributed)
{
await SyncControllingParameterToMasterAsync(0, key, value);
}
}
///
/// 获取探头和应用数据
///
/// 键
///
private async Task GetControllingParameter(string key)
{
_controllingParameterDevices.TryGetValue(key, out CacheControllingParameter value);
return await Task.FromResult(value);
}
///
/// 获取设备参数调节数据请求
///
///
///
public async Task GetControlParametersAsync(GetControlParametersRequest request)
{
var deviceCode = request.DeviceCode;
//检查设备编码不为空
if (string.IsNullOrWhiteSpace(deviceCode))
{
ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
}
_controllingParameterDevices.TryGetValue(deviceCode, out var controlParameterData);
if (controlParameterData != null)
{
return new DeviceControlParameterDataDTO()
{
DeviceCode = controlParameterData.Code,
ProbeApplication = controlParameterData.ProbeApplication,
Parameter = controlParameterData.Parameter
};
}
return null;
}
///
/// 上报直播状态
///
/// 上报直播状态请求实体
///
public async Task ReportLiveStateAsync(ReportLiveStateRequest request)
{
var tokenInfo = await _authenticationService.GetTokenAsync(request);
var deviceCode = tokenInfo.ClientId;
switch (request.LiveState)
{
case DeviceLiveStateEnum.Error:
case DeviceLiveStateEnum.Warning:
Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
break;
default:
Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
break;
}
if (request.LiveState == DeviceLiveStateEnum.Closed)
{
var deviceCache = CacheMaintenance.Instance.Get().Get(deviceCode);
if (deviceCache != null && !string.IsNullOrWhiteSpace(deviceCache.Code))
{
await _rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
{
DeviceShortCode = deviceCache.ShortCode,
CloseDevicePush = true,
});
}
}
else if (request.LiveState == DeviceLiveStateEnum.Pushing)
{
//开始推流,调用会诊信息,通知客户端
var r = await NoticeClientBeginPushLive(deviceCode, true);
}
return await Task.FromResult(true);
}
///
/// 开始推流后,通知客户端
///
/// 房间信息
/// 设备code
///
private async Task NoticeClientBeginPushLive(string deviceCode, bool isNeedSyn = false)
{
var result = false;
var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
{
DeviceCode = deviceCode
});
if (liveRoom != null)
{
var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = liveRoom.LiveRoomCode };
var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode) || liveRoom.Status != LiveRoomStatus.Initiating)
{
//会诊不存在,或不在会诊中,不需要发送通知
return result;
}
if (isNeedSyn)
{
var syncInfo = new JoinInConsultationJson
{
ConsultationRecordCode = liveRoom.LiveRoomCode,
RoomCode = liveRoom.LiveRoomCode,
InitatorCode = liveRoom.InitiatorCode,
OperatorCode = deviceCode
};
await SyncToMasterAsync(SyncTypeEnum.DeviceReStartPusing, liveRoom.LiveRoomCode, syncInfo);
}
var joiner = liveRoom.DeviceInfos.FirstOrDefault(c => c.Code == deviceCode);
if (!string.IsNullOrEmpty(joiner?.Code))
{
var userInfos = liveRoom.UserInfos.Where(x => x.Code != joiner.Code && x.Status == LiveMemberStatus.Joined);
if (userInfos?.Any() == true)
{
var sortUsers = liveRoom.UserInfos.OrderByDescending(x => x.FirstJoinTime).ThenByDescending(x => x.Code).ToList();
var sortNumber = sortUsers.IndexOf(joiner);
var joinerInfo = new LiveConsultationJoinerInfo
{
Id = joiner.Code,
Name = joiner.Name,
HeadImageUrl = joiner.HeadImageToken,
//IsOnline = joiner.IsOnline,
Mute = joiner.MuteOpened,
VideoOpend = joiner.VideoOpened,
SortLevel = joiner.SortLevel,
SortNumber = sortNumber,
LiveData = new LiveData
{
RtmpPushUrl = joiner.LiveData?.RtmpPushUrl,
RtmpPullUrl = joiner.LiveData?.RtmpPullUrl,
HlsPullUrl = joiner.LiveData?.HlsPullUrl,
HttpPullUrl = joiner.LiveData?.HttpPullUrl
},
};
if (joiner.MemberType == LiveMemberEnum.Device)
{
var deviceInfo = CacheMaintenance.Instance.Get().Get(deviceCode);
Logger.WriteLineInfo($"RtcService PushHeartRateJoinMessage, roomId:{liveRoom.LiveRoomCode}, rtcRoomId:{liveRoom.RtcRoomId}, deviceCode:{deviceInfo.ShortCode}");
var videoDeviceOutputInfos = new List();
if (deviceInfo.VideoDeviceInfos?.Any() == true)
{
foreach (var video in deviceInfo.VideoDeviceInfos)
{
var deviceVideoId = video.VideoDeviceId == deviceCode ? video.VideoDeviceId : $"{deviceInfo.ShortCode}_{video.VideoDeviceId}";
if (deviceInfo.VideoDeviceInfos.Count == 1 && !deviceInfo.VideoDeviceInfos.Any(x => x.VideoDeviceSourceType == (int)VideoDeviceSourceTypeEnum.Desktop))
{
deviceVideoId = deviceCode;
}
var videoInfo = joiner.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == deviceVideoId);
if (videoInfo != null)
{
var deviceVideoIdSignRequest = new GetUserSignRequest { UserId = deviceVideoId };
var videoSign = await _wingRtcService.GetUserSignAsync(deviceVideoIdSignRequest);
videoDeviceOutputInfos.Add(new VideoDeviceOutputInfo
{
VideoDeviceId = deviceVideoId,
VideoDeviceSourceType = (VideoDeviceSourceTypeEnum)video.VideoDeviceSourceType,
OutputWidth = video.OutputWidth,
OutputHeight = video.OutputHeight,
VideoFps = video.VideoFps,
VideoBitrate = video.VideoBitrate,
MinVideoBitrate = video.MinVideoBitrate,
VideoDeviceSign = videoSign?.UserSign ?? string.Empty,
LiveData = new LiveData
{
RtmpPushUrl = videoInfo.LiveData?.RtmpPushUrl,
RtmpPullUrl = videoInfo.LiveData?.RtmpPullUrl,
HlsPullUrl = videoInfo.LiveData?.HlsPullUrl,
HttpPullUrl = videoInfo.LiveData?.HttpPullUrl
},
});
}
}
}
var deviceSignRequest = new GetUserSignRequest { UserId = deviceCode };
var deviceSign = await _wingRtcService.GetUserSignAsync(deviceSignRequest);
var consultationDeviceInfo = new LiveConsultationJoinDeviceInfo()
{
MergedChannel = deviceInfo.MergedChannel,
MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
VideoDeviceOutputList = videoDeviceOutputInfos,
AppId = liveRoom.SdkAppId,
DeviceCode = deviceCode,
DeviceSign = deviceSign?.UserSign ?? string.Empty,
LiveProtocol = EnvironmentConfigs.General.LiveProtocolDetail(),
};
joinerInfo.ConsultationDeviceInfo = consultationDeviceInfo;
}
Logger.WriteLineInfo($"RTCService PushHeartRateJoinMessage roomId:{liveRoom.LiveRoomCode}, joiner:{Newtonsoft.Json.JsonConvert.SerializeObject(joinerInfo)}");
var message = new HeartRateJoinConsultationNotification
{
ConsultationCode = liveRoom.LiveRoomCode,
Joiner = joinerInfo
};
//PushMessage(userInfos, message);
if (userInfos?.Any() == true)
{
//开启独立队列
var openNotifyQueueRequest = new WingInterfaceLibrary.Request.Notification.OpenNotifyQueueRequest { Module = liveRoom.LiveRoomCode };
var msgQueueId = await _notificationService.OpenNotifyQueueAsync(openNotifyQueueRequest);
var clientIds = userInfos.Select(x => x.Code).ToList();
var tokenInfos = CacheMaintenance.Instance.Get().Where(x => clientIds.Contains(x.ClientId));
if (tokenInfos != null && tokenInfos.Any())
{
Logger.WriteLineInfo($"RtcService PushMessage, roomId:{liveRoom.LiveRoomCode}, type:{message.NotificationType.ToString()}, receivers:{string.Join(";", tokenInfos.Select(x => x.AccountName).Distinct())}");
}
var notificationRequest = new BroadcastNotificationRequest
{
MsgQueueId = msgQueueId,
ClientIds = clientIds,
Message = message,
JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message),
NotificationType = message.NotificationType,
TransactionType = TransactionTypeEnum.Consultion,
RelevanceCode = liveRoom.LiveRoomCode,
ReceiverType = ApplicantTypeEnum.Client,
WSConnectType = WSConnectTypeEnum.ConsultationSecondWindow,
IsNeedSyn = true
};
var res = await _notificationService.BroadcastMessageAsync(notificationRequest);
}
}
}
result = true;
}
return result;
}
///
/// 获取实时音视频参数
///
/// 获取实时音视频参数请求实体
///
public async Task CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
{
Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
var userCode = Guid.NewGuid().ToString("N");
var liveProtocol = EnvironmentConfigs.General.LiveProtocolDetail();
var resultData = new CreateLiveRoomInfoResult
{
UserCode = userCode,
AppId = GetAppId(),
LiveProtocol = liveProtocol,
};
if (liveProtocol == TransactionStatusEnum.TRTC || liveProtocol == TransactionStatusEnum.VRTC)
{
var getUserSignRequest = new GetUserSignRequest
{
UserId = userCode,
};
var getUserSignResult = await _wingRtcService.GetUserSignAsync(getUserSignRequest);
var userSign = getUserSignResult.UserSign;
var getRoomIdRequest = new GetRoomIdRequest
{
UniqueId = userCode,
};
var getRoomIdResult = await _wingRtcService.GetRoomIdAsync(getRoomIdRequest);
var intRoomNo = (int)getRoomIdResult.RoomId;
resultData.UserSign = userSign;
resultData.RoomNo = intRoomNo;
Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
}
else
{
var rtmpResult = await _rtmpService.GetChannelAsync(new GetChannelRequest { });
if (rtmpResult != null)
{
resultData.LiveData = new LiveDataDTO
{
RtmpPushUrl = rtmpResult.PushUrl,
RtmpPullUrl = rtmpResult.RtmpPullUrl,
HlsPullUrl = rtmpResult.HlsPullUrl,
HttpPullUrl = rtmpResult.HttpPullUrl,
};
}
}
var rtcType = EnvironmentConfigManager.GetParammeter("Rtc", "RTCType").Value;
var _isRTCSelf = (rtcType == "VRTC" ? true : false);
resultData.IsTrtc = _isRTCSelf;
return resultData;
}
///
/// Get the trtc app id
///
/// string
private int GetAppId()
{
var appIdStr = EnvironmentConfigManager.GetParammeter("Rtc", "RTCAppId").Value;
int.TryParse(appIdStr, out int appId);
if (appId <= 0)
{
appId = 1400299969;
}
return appId;
}
private async Task BroadcastNotificationAsync(string roomId, IList clientIds, NotificationDTO message)
{
var broadcastNotificationRequest = new BroadcastNotificationRequest
{
ClientIds = clientIds,
Message = message,
TransactionType = TransactionTypeEnum.Live,
RelevanceCode = roomId,
ReceiverType = ApplicantTypeEnum.Client,
WSConnectType = WSConnectTypeEnum.Default
};
return await _notificationService.BroadcastMessageAsync(broadcastNotificationRequest);
}
// ///
// /// 拒绝远程控制
// ///
// ///
// ///
// public async Task RejectRemoteControl(RemoteControlRequest request)
// {
// string deviceCode = await GetClientIdByTokenAsync(request.Token);
// string userCode = request.ControlUserCode;
// //发送控制人通知
// if (string.IsNullOrWhiteSpace(userCode))
// {
// ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
// }
// var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
// if (userDTO == null)
// {
// ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
// }
// var notify = new DeviceRejectRemoteControlNotification()
// {
// DeviceCode = deviceCode,
// };
// var notificationRequest = new SendNotificationRequest()
// {
// ClientId = userCode,
// Message = notify,
// JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
// NotificationType = notify.NotificationType,
// TransactionType = TransactionTypeEnum.RemoteControl,
// RelevanceCode = userCode,
// ReceiverType = ApplicantTypeEnum.Client
// };
// await _notificationService.PostMessageAsync(notificationRequest);
// //更改房间调参状态
// // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
// // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
// // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
// // {
// // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
// // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
// // }
// // var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
// // await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
// return true;
// }
// ///
// /// 断开远程控制
// ///
// ///
// ///
// public async Task DisconnectRemoteControl(RemoteControlRequest request)
// {
// string deviceCode = await GetClientIdByTokenAsync(request.Token);
// string userCode = request.ControlUserCode;
// //发送控制人通知
// if (string.IsNullOrWhiteSpace(userCode))
// {
// ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
// }
// var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
// if (userDTO == null)
// {
// ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
// }
// var notify = new DeviceDisconnectRemoteControlNotification()
// {
// DeviceCode = deviceCode,
// };
// var notificationRequest = new SendNotificationRequest()
// {
// ClientId = userCode,
// Message = notify,
// JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
// NotificationType = notify.NotificationType,
// TransactionType = TransactionTypeEnum.RemoteControl,
// RelevanceCode = userCode,
// ReceiverType = ApplicantTypeEnum.Client
// };
// await _notificationService.PostMessageAsync(notificationRequest);
// // var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
// // await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
// return true;
// }
public async Task UploadConsultationDataAsync(UploadConsultationDataRequest request)
{
var deviceInfo = await GetDeviceByTokenAsync(request);
var consultationCode = request.ConsultationCode;
if (string.IsNullOrWhiteSpace(consultationCode))
{
ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
}
if (string.IsNullOrWhiteSpace(request.FileToken))
{
ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
}
var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
{
ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
}
var dataDTO = new RemedicalInfoDTO();
dataDTO.DeviceCode = deviceInfo.DeviceCode;
dataDTO.RecordCode = consultationRecord.ConsultationCode;
dataDTO.ApplicationCategory = request.ApplicationCategory;
dataDTO.Application = request.Application;
dataDTO.TerminalImages = new TerminalImageDTO();
var originImageUrl = request.FileToken;
dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
dataDTO.TerminalImages.ImageSize = request.FileSize;
dataDTO.FileDataType = request.FileDataType;
dataDTO.MeasuredResult = request.MeasuredResult;
dataDTO.CommentResult = request.CommentResult;
dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
//更新会诊记录
if (consultationRecord.ConsultationFileList == null)
{
consultationRecord.ConsultationFileList = new List();
}
var consultationFileDTO = new ConsultationFileDTO
{
SourceUrl = originImageUrl,
CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
FileDataType = request.FileDataType,
CreateTime = DateTime.UtcNow,
ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
RemedicalCode = dataDTO.RemedicalCode
};
consultationRecord.ConsultationFileList.Add(consultationFileDTO);
var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
}
///
/// 手机个人添加超声机,PC个人短码添加设备
///
/// 请求实体
/// 是否成功
/// true
///
public async Task ScanBindDeviceAsync(ScanBindDeviceRequest request)
{
//验证
var userCode = await GetClientIdByTokenAsync(request.Token);
//查询用户是否存在
var userInfoDO = await _userServiceProxy.FindUserAsync(new FindUserRequest() { Code = userCode });
if (userInfoDO == null)
{
ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
}
// if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
// {
// ThrowCustomerException(CustomerRpcCode.UserHaveNoOrg, "UserHaveNoOrg");
// }
// //只给非机构负责人用
// if (userInfoDO.IsDirector)
// {
// ThrowCustomerException(CustomerRpcCode.OnlyCommonUserUsed, "Only common user used");
// }
//获取用户机构和所属部门
var organizationCode = userInfoDO.RootOrganizationCode;
var departmentCode = userInfoDO.OrganizationCode;
if (userInfoDO.RootOrganizationCode == userInfoDO.OrganizationCode)
{
//相同表示没有部门
departmentCode = "";
}
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");
}
if (string.IsNullOrEmpty(deviceDb.Description) || deviceDb.Description == deviceDb.Name)
{
if (!string.IsNullOrWhiteSpace(request.Description))
{
deviceDb.Description = request.Description;
}
}
deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
if (!string.IsNullOrEmpty(deviceDb.Description) && !string.IsNullOrEmpty(request.Description) && deviceDb.Description != request.Description)
{
ThrowCustomerException(CustomerRpcCode.DeviceDescriptionNotModify, "Device description not modify");
}
// //判断设备绑定机构是否跟用户的机构一致
// //判断父子级,父级可以绑定子集机构的设备 杏聆荟平台可以绑定任何设备
// var orgCodes = new List { userInfoDO.RootOrganizationCode };
// var allChildOrganizations = await _organizationDBService.GetAllChildOrganizations(userInfoDO.RootOrganizationCode);
// if (allChildOrganizations != null && allChildOrganizations.Count() > 0)
// {
// orgCodes.AddRange(allChildOrganizations.Select(x => x.OrganizationCode));
// }
// if (userInfoDO.RootOrganizationCode != "VINNO_FIS" && !string.IsNullOrEmpty(deviceDb.OrganizationCode) && !orgCodes.Contains(deviceDb.OrganizationCode))
// {
// ThrowCustomerException(CustomerRpcCode.OrganizationCodeInconformity, "Organization code inconformity");
// }
//用户和设备分属不同组织架构,用户扫描二维码提示“该设备归属其他部门,暂时无法添加”
// if (!string.IsNullOrEmpty(deviceDb.DepartmentCode) && !string.IsNullOrEmpty(departmentCode) && departmentCode != deviceDb.DepartmentCode)
// {
// ThrowCustomerException(CustomerRpcCode.DeviceBelongOtherDepartment, "Device belong other department");
// }
// //设备有组织架构,用户无组织架构时,用户扫描二维码提示“该设备归属其他部门,暂时无法添加”
// if (!string.IsNullOrEmpty(deviceDb.DepartmentCode) && string.IsNullOrEmpty(departmentCode))
// {
// ThrowCustomerException(CustomerRpcCode.DeviceBelongOtherDepartment, "Device belong other department");
// }
try
{
var userCodes = new List() { userCode };
//新设备,绑定机构,且绑定到机构管理员名下
if (string.IsNullOrEmpty(deviceDb.OrganizationCode))
{
if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
{
deviceDb.OrganizationCode = "VINNO_FIS";
if (string.IsNullOrEmpty(deviceDb.Name))
{
deviceDb.Name = userInfoDO.OrganizationName + "_" + deviceDb.ShortCode;
}
await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
}
else
{
//添加机构管理员绑定设备信息
var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == "VINNO_FIS") ? true : false;
if (string.IsNullOrEmpty(deviceDb.Name))
{
deviceDb.Name = userInfoDO.OrganizationName + "_" + deviceDb.ShortCode;
}
deviceDb.DepartmentCode = departmentCode;
deviceDb.OrganizationCode = organizationCode;
await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
if (isInvented && !string.IsNullOrWhiteSpace(organizationCode)) //虚拟机构改为正常机构
{
var newOrgCode = string.IsNullOrWhiteSpace(departmentCode) ? organizationCode : departmentCode;
// //迁移数据超声机上传检查记录
// await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
// //迁移数据超声机上传病人
// await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List() { deviceDb.DeviceCode }, newOrgCode);
_modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
}
//查询机构信息,以及机构管理员
var organizationCacheDTO = CacheMaintenance.Instance.Get().Get(organizationCode) ?? new CacheOrganizationDTO();
if (organizationCacheDTO.Directors?.Count > 0)
{
userCodes.AddRange(organizationCacheDTO.Directors);
userCodes = userCodes.Distinct().ToList();
}
}
}
else
{
await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
}
var updateResult = await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
{
DeviceCodes = new List() { deviceDb.DeviceCode },
OrganizationCodes = new List() { deviceDb.OrganizationCode },
UserCodes = userCodes
});
var result = updateResult > 0 ? true : false;
return result;
}
catch (Exception ex)
{
Logger.WriteLineError($"ScanBindDeviceAsync error {ex}");
return false;
}
}
///
/// 新增设备画面尺寸
///
/// 是否操作成功
public async Task ReportBrandModelOutputConfigAsync(ReportBrandModelOutputConfigRequest request)
{
return await _deviceInfoDBServiceProxy.AddBrandModelOutputConfigAsync(new AddBrandModelOutputConfigDBRequest
{
Brand = request.Brand,
Model = request.Model,
ShortCode = request.ShortCode,
VideoWidth = request.VideoWidth,
VideoHeight = request.VideoHeight
});
}
///
/// 获取设备画面尺寸
///
/// 是否操作成功
public async Task> SyncBrandModelOutputConfigAsync(SyncBrandModelOutputConfigRequest request)
{
var configs = await _deviceInfoDBServiceProxy.GetBrandModelOutputConfigAsync(new GetBrandModelOutputConfigDBRequest
{
Brand = request.Brand,
Model = request.Model,
ShortCode = request.ShortCode,
});
var newBrandModelList = new List();
var first = configs.FirstOrDefault(w => w.IsSelect);
if (first != null)
{
newBrandModelList.Add(first);
}
foreach (var config in configs)
{
if (!newBrandModelList.Any(a => a.VideoWidth == config.VideoWidth && a.VideoHeight == config.VideoHeight))
{
newBrandModelList.Add(new BrandModelOutputConfigDTO
{
VideoWidth = config.VideoWidth,
VideoHeight = config.VideoHeight
});
}
}
return newBrandModelList;
}
///
/// 获取品牌列表
///
///
public Task> GetBrandsAsync(GetBrandsRequest request)
{
return _deviceInfoDBServiceProxy.GetBrandsAsync();
}
///
/// 获取品牌型号列表
///
///
public Task> GetModelsAsync(GetModelsRequest request)
{
return _deviceInfoDBServiceProxy.GetModelsAsync(new GetModelsDBRequest
{
Brand = request.Brand
});
}
///
/// 修改用户急诊设备
///
/// 修改用户急诊设备请求
///
public async Task ModifyEmergencyDeviceCodeAsync(ModifyEmergencyDeviceCodeRequest request)
{
var userCode = await GetClientIdByTokenAsync(request.Token);
return await _userServiceProxy.UpdateEmergencyDeviceCodeDBAsync(new UpdateEmergencyDeviceCodeDBRequest
{
UserCode = userCode,
EmergencyDeviceCode = request.EmergencyDeviceCode,
});
}
///
/// 批量新增打印机驱动
///
/// 请求实体
/// 是否成功
public async Task BatchInsertDevicePrintersDataAsync(MigrateDevicePrinterRequest request)
{
return await _deviceInfoDBServiceProxy.BatchInsertDevicePrintersDataAsync(request);
}
///
/// 批量新增补丁包
///
/// 请求实体
/// 是否成功
public async Task BatchInsertDevicePatchsDataAsync(MigrateDevicePatchRequest request)
{
return await _deviceInfoDBServiceProxy.BatchInsertDevicePatchsDataAsync(request);
}
///
/// 获取个人绑定设备分页
///
///
///
public async Task> GetPersonDeviceDropdownPageAsync(GetPersonDeviceDropdownPageRequest 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 selectItemDTOList = new List();
//普通用户,查询用户绑定的设备
var dbPage = new PageResult();
var dbRequest = new FindDeviceInfoPageRequest()
{
PageIndex = request.PageIndex,
PageSize = request.PageSize,
KeyWord = request.KeyWord,
UserCode = userCode,
IsIncloudReferral = request.IsIncloudReferral
};
dbRequest.DeviceCodes = userInfoDO.BindDevices;
dbRequest.RestrictOrgCodes = request.RestrictOrgCodes;
dbPage = await _deviceInfoDBServiceProxy.FindDeviceInfoListPageDBAsync(dbRequest);
if (dbPage?.PageData?.Count > 0)
{
selectItemDTOList = dbPage.PageData.Select(c => new SelectItemDTO()
{
Key = c.DeviceCode,
Value = string.IsNullOrWhiteSpace(c.Description) ? c.Name : c.Description
}).ToList();
}
if (!selectItemDTOList.Any())
{
return new PageCollection() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List() };
}
var pagedResult = new PageCollection
{
CurrentPage = request.PageIndex,
PageSize = request.PageSize,
DataCount = dbPage.TotalCount,
PageData = selectItemDTOList
};
return pagedResult;
}
///
/// 根据名称查询设备信息
///
/// 请求实体
/// 设备信息
public async Task FindDeviceInfoByNameAsync(FindDeviceInfoByNameRequest request)
{
var result = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.Name);
return result;
}
///
/// 新增老版本设备
///
///
///
public async Task AddOldVersionDeviceAsync(AddOldVersionDeviceRequest request)
{
var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.TerminalName);
if (deviceInfo != null && !string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
{
return deviceInfo;
}
var organizationName = request.OrganizationName;
var organizationCode = "";
//查询医院是否存在 不存在则新增医院
var orgRequest = new GetOrganizationByNameDBRequest { OrganizationName = request.OrganizationName };
var organizationDetail = await _organizationDBService.GetOrganizationDetailByNameAsync(orgRequest);
if (organizationDetail == null || string.IsNullOrWhiteSpace(organizationDetail.OrganizationCode))
{
//创建机构
organizationCode = CodeCreator.CreateCode("Organization");
var organizationDB = new OrganizationDTO();
organizationDB.OrganizationCode = organizationCode;
organizationDB.RootCode = organizationCode;
organizationDB.State = OrganizationStateEnum.Audited;
organizationDB.ReferralOrganizationCodes = null;
organizationDB.OrganizationName = organizationName;
if (organizationName.Contains("动物") || organizationName.Contains("宠物") || organizationName.ToLower().Contains("animal") || organizationName.ToLower().Contains("pet"))
{
organizationDB.PatientType = OrganizationPatientTypeEnum.Animals;
}
var dbRequest = new CreateOrganizationsDBRequest();
dbRequest.Infos = new List>();
dbRequest.Infos.Add(new TableDataItem { Data = organizationDB });
await _organizationDBService.CreateOrganizationsAsync(dbRequest);
}
else
{
organizationCode = organizationDetail.OrganizationCode;
}
var deviceDto = new DeviceInfoDTO()
{
SerialNumber = "",
Name = request.TerminalName,
Password = request.TerminalPassword,
OrganizationCode = organizationCode,
DeviceModel = request.TerminalModel,
IsEncryptedShow = false,
MergedChannel = _isMergedChannel,
DeviceType = "US",
};
var shortCode = deviceDto.ShortCode;
for (var i = 0; i < 5; i++)
{
shortCode = GenerateShortCode();
if (!string.IsNullOrWhiteSpace(shortCode))
{
var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
{
break;
}
}
shortCode = string.Empty;
}
deviceDto.ShortCode = shortCode;
if (string.IsNullOrWhiteSpace(deviceDto.OrganizationCode))
{
deviceDto.OrganizationCode = "VINNO_FIS";
}
deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
{
Data = deviceDto
});
return deviceDto;
}
///
/// 获取license信息列表
///
///
///
public async Task> GetLicenseInfoListAsync(TokenRequest request)
{
var dataResult = await _deviceInfoDBServiceProxy.GetLicenseInfoListDBAsync(request);
return dataResult;
}
///
/// 保存License信息数据
///
///
///
public async Task SaveLicenseInfoListAsync(SaveLicenseInfoRequest request)
{
var dataResult = await _deviceInfoDBServiceProxy.SaveLicenseInfoListDBAsync(request);
return dataResult;
}
///
/// 保存Dongle信息数据
///
///
///
public async Task SaveDongleInfoListAsync(SaveDongleInfoRequest request)
{
var dataResult = await _deviceInfoDBServiceProxy.SaveDongleInfoListDBAsync(request);
return dataResult;
}
}
}