12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711 |
- 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
- {
- /// <summary>
- /// 设备管理服务
- /// </summary>
- public partial class DeviceService : JsonRpcService, IDeviceService, ISyncDeviceRemoteConnectService
- {
- //远程调参
- private ConcurrentDictionary<string, CacheControllingParameter> _controllingParameterDevices = new ConcurrentDictionary<string, CacheControllingParameter>();
- 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<IntParameter>("Device", "HeartRateSeconds").Value;
- private DeviceHeartRateManager _deviceHeartRateManager;
- private RemoteConnectManager _remoteConnectManager;
- private string _webSocketUrl => EnvironmentConfigManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
- private int _liveConsultationRateSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("LiveConsultation", "HeartRateSeconds").Value;
- // private int _remoteControlAskTimeoutSec => EnvironmentConfigManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
- private int _remoteControlHeartRateSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("Device", "RemoteControlHeartRateSeconds").Value;
- private int _reportStateIntervalSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("LiveConsultation", "ReportStateIntervalSeconds").Value;
- private int _reportStateTimeout = 0;
- private string _deviceShareUrl => EnvironmentConfigManager.GetParammeter<StringParameter>("Share", "DeviceLiveUrl").Value;
- private int _shareEffectiveSeconds => EnvironmentConfigManager.GetParammeter<IntParameter>("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<ModifyDeviceRequest> _modifyDeviceExecutor = new SequenceExecutor<ModifyDeviceRequest>("UpdateDeviceInvented");
- /// <summary>
- /// Init service
- /// </summary>
- public override void Load(JsonRpcClientPool jsonRpcClientPool)
- {
- base.Load(jsonRpcClientPool);
- _userServiceProxy = GetProxy<IUserDBService>();
- _authenticationService = GetProxy<IAuthenticationService>();
- _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
- _userDBService = GetProxy<IUserDBService>();
- _organizationDBService = GetProxy<IOrganizationDBService>();
- _notificationService = GetProxy<INotificationService>();
- _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
- _patientInfoDBService = GetProxy<IPatientInfoDBService>();
- _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
- _remedicalService = GetProxy<IRemedicalService>();
- _wingRtcService = GetProxy<IWingRtcService>();
- _rtcService = GetProxy<IRtcService>();
- _rtmpService = GetProxy<IRtmpService>();
- _liveConsultationService = GetProxy<ILiveConsultationService>();
- _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
- _remedicalDBService = GetProxy<IRemedicalDBService>();
- _shareDBService = GetProxy<IShareDBService>();
- _masterInteractionCenterService = GetProxy<IMasterInteractionCenterService>();
- _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState, CheckDeviceLiveStatus);
- _remoteConnectManager = new RemoteConnectManager(RemoteConnectOnlineState, DeviceRemoteConnectOnlineState, _authenticationService);
- _reportStateTimeout = _reportStateIntervalSeconds + 60;
- _serverID = ConfigurationManager.GetParammeter<StringParameter>("General", "ServerID").Value;
- }
- /// <summary>
- /// default server restart run
- /// </summary>
- public override void LoadAfterRegister()
- {
- try
- {
- _deviceForwardService = GetProxy<IDeviceForwardService>();
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"DeviceService LoadAfterRegister err, {ex}");
- }
- }
- /// <summary>
- /// 设备心跳
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> 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;
- }
- /// <summary>
- /// 添加分享设备关联用户请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> 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<string>() { deviceCode },
- OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
- UserCodes = userCodes.ToList()
- });
- return true;
- }
- /// <summary>
- /// 根据设备code获取设备信息
- /// </summary>
- /// <param name="request">设备code请求实体</param>
- /// <returns>返回查询到的设备对象信息</returns>
- public async Task<DeviceExtendInfoDTO> 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<DeviceExtendInfoDTO>();
- result.DepartmentName = departmentName;
- result.OrganizationName = organizationName;
- result.IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode);
- result.IsCanRemoteMaintenance = true;
- result.LanguageConfigs = deviceTypeModel?.LanguageConfigs ?? new List<DictionaryLanguageConfigDTO>();
- result.PatientType = patientType;
- return result;
- }
- /// <summary>
- /// 根据设备动态唯一码获取设备信��
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<DeviceExtendInfoDTO> 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<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
- {
- throw new System.NotImplementedException();
- }
- public async Task<bool> 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<TableDataItem<UserPasswordDTO>>();
- 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<UserPasswordDTO>()
- {
- Data = user.MappingTo<UserPasswordDTO>(),
- });
- }
- }
- }
- if (updateUsers.Count > 0)
- {
- var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
- await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
- }
- return true;
- }
- /// <summary>
- /// 机构设备移除-根据机构code和设备code解除其绑定关系
- /// </summary>
- /// <param name="request">移除设备请求实体</param>
- /// <returns>移除是否成功:true-成功;false-失败</returns>
- public async Task<bool> 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<TableDataItem<UserPasswordDTO>>();
- foreach (var user in users)
- {
- user.BindDevices.Remove(deviceDb.DeviceCode);
- updateUsers.Add(new TableDataItem<UserPasswordDTO>()
- {
- Data = user.MappingTo<UserPasswordDTO>(),
- });
- }
- if (updateUsers.Count > 0)
- {
- var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
- await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
- }
- return removeDeviceResult;
- }
- private async Task<string> GetClientIdByTokenAsync(string token)
- {
- var request = new TokenRequest() { Token = token };
- var result = await _authenticationService.GetTokenAsync(request);
- return result.ClientId; //return User code
- }
- /// <summary>
- /// 查询机构管理员机构名下所有设备列表接口
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns>返回设备信息列表</returns>
- public async Task<PageCollection<DeviceExtendInfoDTO>> 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<DeviceInfoDTO>();
- var dbPage = new PageResult<DeviceInfoDTO>();
- 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<ITokensManager>().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<string> { 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<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
- }
- var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
- foreach (var device in deviceList)
- {
- device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
- }
- var pagedResult = new PageCollection<DeviceExtendInfoDTO>
- {
- CurrentPage = request.PageIndex,
- PageSize = request.PageSize,
- DataCount = dbPage.TotalCount,
- PageData = deviceList
- };
- return pagedResult;
- }
- /// <summary>
- /// 查询个人名下本机构所有设备列表接口
- /// </summary>
- /// <param name="request"></param>
- /// <returns>返回设备信息列表</returns>
- /// <errorCodes>UserNotExistError,OrganizationNotExist</errorCodes>
- public async Task<PageCollection<DeviceExtendInfoDTO>> 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<DeviceInfoDTO>();
- var dbPage = new PageResult<DeviceInfoDTO>();
- 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<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
- }
- var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
- foreach (var device in deviceList)
- {
- device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
- }
- var pagedResult = new PageCollection<DeviceExtendInfoDTO>
- {
- CurrentPage = request.PageIndex,
- PageSize = request.PageSize,
- DataCount = dbPage.TotalCount,
- PageData = deviceList
- };
- return pagedResult;
- }
- /// <summary>
- /// 查询个人名下所有设备列表接口
- /// </summary>
- /// <param name="request">查询个人名下所有设备列表请求实体</param>
- /// <returns>返回设备信息列表</returns>
- public async Task<PageCollection<DeviceExtendInfoDTO>> 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<DeviceInfoDTO>();
- //普通用户,查询用户绑定的设备
- var dbPage = new PageResult<DeviceInfoDTO>();
- 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<ITokensManager>().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<string> { 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<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
- }
- var deviceList = await MapToExtendDTO(deviceInfoDTOList, userInfoDO);
- foreach (var device in deviceList)
- {
- device.IsEmergencyDevice = device.DeviceCode == userInfoDO.BindEmergencyDeviceCode;
- }
- var pagedResult = new PageCollection<DeviceExtendInfoDTO>
- {
- 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<DeviceExtendInfoDTO>()
- };
- return pagedResult;
- }
- /// <summary>
- /// 查询设备列表(助理查专家的如果没有专家则查机构的)
- /// </summary>
- /// <param name="request">查询设备列表请求实体</param>
- /// <returns>返回设备信息列表</returns>
- public async Task<PageCollection<DeviceInfoDTO>> 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<DeviceInfoDTO>();
- //普通用户,查询用户绑定的设备
- if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
- {
- deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
- }
- if (userInfoDO.IsDirector)
- {
- //机构负责人
- var orgCodes = new List<string> { 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<DeviceInfoDTO>();
- var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
- if (experts.Any())
- {
- var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).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<DeviceInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceInfoDTO>() };
- }
- //条件筛选
- if (!string.IsNullOrWhiteSpace(request.DeviceType))
- {
- deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceInfoDTO>();
- }
- if (!string.IsNullOrWhiteSpace(request.DeviceModel))
- {
- deviceInfoDTOList = deviceInfoDTOList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceInfoDTO>();
- }
- 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<DeviceInfoDTO>();
- }
- var pagedResult = new PageCollection<DeviceInfoDTO>
- {
- CurrentPage = request.PageIndex,
- PageSize = request.PageSize,
- DataCount = deviceInfoDTOList.Count,
- PageData = deviceInfoDTOList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceInfoDTO>()
- };
- return pagedResult;
- }
- /// <summary>
- /// 更新虚拟设备检查和病人信息
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns></returns>
- private bool OnUpdateInventedDeviceInfoAsync(ModifyDeviceRequest request)
- {
- try
- {
- //迁移数据超声机上传检查记录
- var orgResult = _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { request.DeviceCode }, request.DepartmentCode).Result;
- //迁移数据超声机上传病人
- var patientResult = _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { request.DeviceCode }, request.DepartmentCode).Result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"save admin statistic info failed, ex:{ex}");
- }
- return true;
- }
- /// <summary>
- /// 机构负责人,机构绑定设备
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> 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<string> { 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<string>() { deviceDb.DeviceCode }, newOrgCode);
- // //迁移数据超声机上传病人
- // await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
- _modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
- }
- var userCodes = new List<string>();
- if (deviceDb.IsAutoShared)
- {
- var users = new List<UserDTO>();
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { 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<string>() { deviceDb.DeviceCode },
- OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
- UserCodes = userCodes
- });
- return true;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"BindDeviceAsync error {ex}");
- }
- return false;
- }
- /// <summary>
- /// 修改设备全部信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateDeviceAsync(UpdateDeviceRequest request)
- {
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
- }
- //全部覆盖
- deviceDb = request.MappingTo<DeviceInfoDTO>();
- return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
- }
- /// <summary>
- /// 修改设备
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> 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<UserDTO>();
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { 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<TableDataItem<UserPasswordDTO>>();
- foreach (var user in users)
- {
- var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
- user.BindDevices?.Remove(deviceDb.DeviceCode);
- await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
- }
- await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
- {
- DeviceCodes = new List<string>() { deviceDb.DeviceCode },
- OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
- UserCodes = userCodes.Select(f => f.ToString()).ToList()
- });
- }
- return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
- }
- /// <summary>
- /// 创建字典
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
- {
- return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
- {
- Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
- ExtensionData = string.Empty
- });
- }
- /// <summary>
- /// 查找设备型号所有字典项
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
- {
- var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
- {
- DictionaryType = (int)request.DictionaryType,
- ParentCode = request.DeviceTypeCode
- });
- return dictionaryDOList;
- }
- /// <summary>
- /// 查找设备类型所有字典项
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
- {
- var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
- {
- DictionaryType = (int)request.DictionaryType
- });
- return dictionaryDOList;
- }
- /// <summary>
- /// 根据组织编码查询所属全部设备信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
- {
- var result = new List<DeviceExtendInfoDTO>();
- 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<string, string>();
- 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<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
- {
- throw new NotImplementedException();
- }
- public async Task<List<SelectItemDTO>> 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<SelectItemDTO>();
- //查询用户的医院是否存在
- if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
- }
- var deviceInfoDTOList = new List<DeviceInfoDTO>();
- if (userInfoDO.IsDirector)
- {
- //查询个人的设备数据
- deviceInfoDTOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
- //查询机构的设备数据
- var orgCodes = new List<string> { 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<string>()).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;
- }
- /// <summary>
- /// 设备端调用,查询获取服务器配置信息接口
- /// </summary>
- /// <param name="request">Token验证</param>
- /// <returns>服务器配置信息结果key:字段,value:数据值,复杂类型可为json</returns>
- public async Task<DeviceServerSettingResult> 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<string, string>();
- //定义配置字段 并扩充字段,返回数据可持续更新接口文�如果数据是复杂类型可以转成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<StringParameter>("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<TransactionStatusEnum>();
- }
- 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<StringParameter>("Gateway", "FISWebUrl").Value,
- IsResearchEditionService = GetIsResearchEditionService(),
- };
- return result;
- }
- private bool GetIsResearchEditionService()
- {
- var result = false;
- try
- {
- result = EnvironmentConfigManager.GetParammeter<BoolParameter>("General", "IsResearchEditionService").Value;
- }
- catch
- {
- }
- return result;
- }
- /// <summary>
- /// 添加或迁移设备到医院请求(废弃)
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> 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<TableDataItem<UserPasswordDTO>>();
- foreach (var user in users)
- {
- user.BindDevices.Remove(device.DeviceCode);
- updateUsers.Add(new TableDataItem<UserPasswordDTO>()
- {
- Data = user.MappingTo<UserPasswordDTO>(),
- });
- }
- if (updateUsers.Count > 0)
- {
- var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
- await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
- }
- if (oldOrg.Isinvented) // 虚拟医院
- {
- //迁移数据超声机上传检查记��
- await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
- //迁移数据超声机上传病��
- await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
- }
- }
- return success;
- }
- catch (System.Exception ex)
- {
- Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
- }
- return false;
- }
- /// <summary>
- /// 补齐设备扩展信息
- /// </summary>
- /// <param name="deviceInfoDOList"></param>
- /// <returns></returns>
- private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList, UserDTO userInfo = null)
- {
- var deviceList = new List<DeviceExtendInfoDTO>();
- 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<string>();
- 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<DeviceExtendInfoDTO>();
- 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;
- }
- /// <summary>
- /// 补齐设备扩展信息
- /// </summary>
- /// <param name="deviceInfoDOList"></param>
- /// <returns></returns>
- private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
- {
- var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
- return deviceList.FirstOrDefault();
- }
- /// <summary>
- /// 获取设备绑定用户codes
- /// </summary>
- /// <param name="request">获取设备绑定用户codes请求实体</param>
- /// <returns>test01,test02</returns>
- public async Task<List<string>> 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<string>();
- }
- /// <summary>
- /// 查询设备AI应用的状��
- /// </summary>
- /// <param name="request">请求参数</param>
- /// <returns>AI应用集合</returns>
- public async Task<List<DiagnosisModuleDTO>> 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 });
- }
- /// <summary>
- /// 修改设备AI应用启用状��
- /// </summary>
- /// <param name="request">修改设备AI应用启用状态请求实��/param>
- /// <returns>是否成功</returns>
- /// <para>DeviceErrorCodeEnum</para>
- public async Task<bool> 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<IDeviceInfosManager>().Remove(request.DeviceCode);
- return result;
- }
- /// <summary>
- /// 设备离开会诊房间
- /// </summary>
- /// <param name="request">设备离开会诊房间请求实体</param>
- /// <returns></returns>
- public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var result = new DeviceLeaveLiveConsultationResult
- {
- Success = false,
- };
- return result;
- }
- /// <summary>
- /// 通用异常处理方法
- /// </summary>
- /// <param name="customerRpcCodeEnum">异常标识码</param>
- /// <param name="msg">异常信息</param>
- /// <param name="internalMessage">内部异常信息,非必填</param>
- private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
- {
- ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
- }
- /// <summary>
- /// 上报设备画面尺寸相关信息
- /// </summary>
- /// <param name="request"></param>
- /// <docFirstDirectory>设备端API</docFirstDirectory>
- /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
- /// <docThirdDirectory>会诊</docThirdDirectory>
- /// <returns></returns>
- public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
- {
- var tokenInfo = await _authenticationService.GetTokenAsync(request);
- var result = new ReportVideoDeviceInfoResult();
- request.VideoDeviceInfos = request.VideoDeviceInfos?.ToList() ?? new List<VideoDeviceInfo>();
- 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<VideoDeviceDTO>();
- 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<IDeviceInfosManager>().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<VideoDeviceDTO> 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);
- }
- }
- }
- }
- /// <summary>
- /// 查找有效设备总数量
- /// </summary>
- /// <returns></returns>
- public async Task<long> GetActiveDeviceCount()
- {
- return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
- }
- /// <summary>
- /// 设备发送调参初始化数据
- /// </summary>
- /// <param name="request">调参数据请求</param>
- /// <returns></returns>
- public async Task<bool> 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);
- }
- }
- /// <summary>
- /// 获取探头和应用数据
- /// </summary>
- /// <param name="key">键</param>
- /// <returns></returns>
- private async Task<CacheControllingParameter> GetControllingParameter(string key)
- {
- _controllingParameterDevices.TryGetValue(key, out CacheControllingParameter value);
- return await Task.FromResult<CacheControllingParameter>(value);
- }
- /// <summary>
- /// 获取设备参数调节数据请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<DeviceControlParameterDataDTO> 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;
- }
- /// <summary>
- /// 上报直播状态
- /// </summary>
- /// <param name="request">上报直播状态请求实体</param>
- /// <returns></returns>
- public async Task<bool> 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<IDeviceInfosManager>().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);
- }
- /// <summary>
- /// 开始推流后,通知客户端
- /// </summary>
- /// <param name="liveRoom">房间信息</param>
- /// <param name="deviceCode">设备code</param>
- /// <returns></returns>
- private async Task<bool> 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<IDeviceInfosManager>().Get(deviceCode);
- Logger.WriteLineInfo($"RtcService PushHeartRateJoinMessage, roomId:{liveRoom.LiveRoomCode}, rtcRoomId:{liveRoom.RtcRoomId}, deviceCode:{deviceInfo.ShortCode}");
- var videoDeviceOutputInfos = new List<VideoDeviceOutputInfo>();
- 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<TransactionStatusEnum>(),
- };
- 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<ITokensManager>().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;
- }
- /// <summary>
- /// 获取实时音视频参数
- /// </summary>
- /// <param name="request">获取实时音视频参数请求实体</param>
- /// <returns></returns>
- public async Task<CreateLiveRoomInfoResult> 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<TransactionStatusEnum>();
- 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<StringParameter>("Rtc", "RTCType").Value;
- var _isRTCSelf = (rtcType == "VRTC" ? true : false);
- resultData.IsTrtc = _isRTCSelf;
- return resultData;
- }
- /// <summary>
- /// Get the trtc app id
- /// </summary>
- /// <returns>string</returns>
- private int GetAppId()
- {
- var appIdStr = EnvironmentConfigManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
- int.TryParse(appIdStr, out int appId);
- if (appId <= 0)
- {
- appId = 1400299969;
- }
- return appId;
- }
- private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> 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);
- }
- // /// <summary>
- // /// 拒绝远程控制
- // /// </summary>
- // /// <param name="request"></param>
- // /// <returns></returns>
- // public async Task<bool> 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;
- // }
- // /// <summary>
- // /// 断开远程控制
- // /// </summary>
- // /// <param name="request"></param>
- // /// <returns></returns>
- // public async Task<bool> 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<bool> 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<ConsultationFileDTO>();
- }
- 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);
- }
- /// <summary>
- /// 手机个人添加超声机,PC个人短码添加设备
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns>是否成功</returns>
- /// <value>true</value>
- /// <errorCodes></errorCodes>
- public async Task<bool> 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<string> { 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<string>() { 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<string>() { deviceDb.DeviceCode }, newOrgCode);
- // //迁移数据超声机上传病人
- // await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
- _modifyDeviceExecutor.Add(OnUpdateInventedDeviceInfoAsync, new ModifyDeviceRequest() { DeviceCode = deviceDb.DeviceCode, DepartmentCode = newOrgCode });
- }
- //查询机构信息,以及机构管理员
- var organizationCacheDTO = CacheMaintenance.Instance.Get<IOrganizationsManager>().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<string>() { deviceDb.DeviceCode },
- OrganizationCodes = new List<string>() { deviceDb.OrganizationCode },
- UserCodes = userCodes
- });
- var result = updateResult > 0 ? true : false;
- return result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"ScanBindDeviceAsync error {ex}");
- return false;
- }
- }
- /// <summary>
- /// 新增设备画面尺寸
- /// </summary>
- /// <returns>是否操作成功</returns>
- public async Task<bool> ReportBrandModelOutputConfigAsync(ReportBrandModelOutputConfigRequest request)
- {
- return await _deviceInfoDBServiceProxy.AddBrandModelOutputConfigAsync(new AddBrandModelOutputConfigDBRequest
- {
- Brand = request.Brand,
- Model = request.Model,
- ShortCode = request.ShortCode,
- VideoWidth = request.VideoWidth,
- VideoHeight = request.VideoHeight
- });
- }
- /// <summary>
- /// 获取设备画面尺寸
- /// </summary>
- /// <returns>是否操作成功</returns>
- public async Task<List<BrandModelOutputConfigDTO>> SyncBrandModelOutputConfigAsync(SyncBrandModelOutputConfigRequest request)
- {
- var configs = await _deviceInfoDBServiceProxy.GetBrandModelOutputConfigAsync(new GetBrandModelOutputConfigDBRequest
- {
- Brand = request.Brand,
- Model = request.Model,
- ShortCode = request.ShortCode,
- });
- var newBrandModelList = new List<BrandModelOutputConfigDTO>();
- 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;
- }
- /// <summary>
- /// 获取品牌列表
- /// </summary>
- /// <returns></returns>
- public Task<List<string>> GetBrandsAsync(GetBrandsRequest request)
- {
- return _deviceInfoDBServiceProxy.GetBrandsAsync();
- }
- /// <summary>
- /// 获取品牌型号列表
- /// </summary>
- /// <returns></returns>
- public Task<List<string>> GetModelsAsync(GetModelsRequest request)
- {
- return _deviceInfoDBServiceProxy.GetModelsAsync(new GetModelsDBRequest
- {
- Brand = request.Brand
- });
- }
- /// <summary>
- /// 修改用户急诊设备
- /// </summary>
- /// <param name="request">修改用户急诊设备请求</param>
- /// <returns></returns>
- public async Task<bool> ModifyEmergencyDeviceCodeAsync(ModifyEmergencyDeviceCodeRequest request)
- {
- var userCode = await GetClientIdByTokenAsync(request.Token);
- return await _userServiceProxy.UpdateEmergencyDeviceCodeDBAsync(new UpdateEmergencyDeviceCodeDBRequest
- {
- UserCode = userCode,
- EmergencyDeviceCode = request.EmergencyDeviceCode,
- });
- }
- /// <summary>
- /// 批量新增打印机驱动
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns>是否成功</returns>
- public async Task<bool> BatchInsertDevicePrintersDataAsync(MigrateDevicePrinterRequest request)
- {
- return await _deviceInfoDBServiceProxy.BatchInsertDevicePrintersDataAsync(request);
- }
- /// <summary>
- /// 批量新增补丁包
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns>是否成功</returns>
- public async Task<bool> BatchInsertDevicePatchsDataAsync(MigrateDevicePatchRequest request)
- {
- return await _deviceInfoDBServiceProxy.BatchInsertDevicePatchsDataAsync(request);
- }
- /// <summary>
- /// 获取个人绑定设备分页
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<PageCollection<SelectItemDTO>> 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<SelectItemDTO>();
- //普通用户,查询用户绑定的设备
- var dbPage = new PageResult<DeviceInfoDTO>();
- 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<SelectItemDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<SelectItemDTO>() };
- }
- var pagedResult = new PageCollection<SelectItemDTO>
- {
- CurrentPage = request.PageIndex,
- PageSize = request.PageSize,
- DataCount = dbPage.TotalCount,
- PageData = selectItemDTOList
- };
- return pagedResult;
- }
- /// <summary>
- /// 根据名称查询设备信息
- /// </summary>
- /// <param name="request">请求实体</param>
- /// <returns>设备信息</returns>
- public async Task<DeviceInfoDTO> FindDeviceInfoByNameAsync(FindDeviceInfoByNameRequest request)
- {
- var result = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.Name);
- return result;
- }
- /// <summary>
- /// 新增老版本设备
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<DeviceInfoDTO> 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<TableDataItem<OrganizationDTO>>();
- dbRequest.Infos.Add(new TableDataItem<OrganizationDTO> { 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;
- }
- /// <summary>
- /// 获取license信息列表
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<IList<LicenseInfoBasicDTO>> GetLicenseInfoListAsync(TokenRequest request)
- {
- var dataResult = await _deviceInfoDBServiceProxy.GetLicenseInfoListDBAsync(request);
- return dataResult;
- }
- /// <summary>
- /// 保存License信息数据
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> SaveLicenseInfoListAsync(SaveLicenseInfoRequest request)
- {
- var dataResult = await _deviceInfoDBServiceProxy.SaveLicenseInfoListDBAsync(request);
- return dataResult;
- }
- /// <summary>
- /// 保存Dongle信息数据
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> SaveDongleInfoListAsync(SaveDongleInfoRequest request)
- {
- var dataResult = await _deviceInfoDBServiceProxy.SaveDongleInfoListDBAsync(request);
- return dataResult;
- }
- }
- }
|