From c73c93250d36fbfbb520810185d51386ab1f09b4 Mon Sep 17 00:00:00 2001 From: chencaixia Date: Mon, 11 Aug 2025 11:09:01 +0800 Subject: [PATCH 1/2] .netcore --- .../AliYunSms/ISmsHelperService.cs | 12 + .../AliYunSms/SmsHelperService.cs | 227 ++ .../WeiCloud.Core/BaseCore/ClusterClient.cs | 24 + .../WeiCloud.Core/BaseCore/Grain.cs | 19 + .../WeiCloud.Core/BaseCore/GrainFactory.cs | 24 + .../BaseCore/IGrainWithIntegerKey.cs | 13 + .../BaseCore/ReentrantAttribute.cs | 19 + .../Calculation/CalculationformulaEnum.cs | 14 + .../Calculation/DateTimeComponetUtil.cs | 95 + .../Calculation/EngeryCalculation.cs | 180 ++ .../Calculation/ExpressionFunc.cs | 120 + .../Calculation/UnitConvertUtil.cs | 126 ++ .../WeiCloud.Core/Common/AppConstant.cs | 52 + .../WeiCloud.Core/Common/AxHelper.cs | 28 + .../WeiCloud.Core/Common/BaseDataCodeRule.cs | 36 + .../WeiCloud.Core/Common/CertStatus.cs | 15 + .../WeiCloud.Core/Common/ComComparer.cs | 142 ++ .../WeiCloud.Core/Common/ConfigHelper.cs | 39 + .../WeiCloud.Core/Common/CurrentContext.cs | 93 + .../Common/DataSetGroup/DataSetGroupMeta.cs | 45 + .../Common/DataStream/ParamConfigConst.cs | 29 + .../DataStream/QualityMethodTypeConst.cs | 30 + .../WeiCloud.Core/Common/DataTableHelper.cs | 48 + .../WeiCloud.Core/Common/DateNowSession.cs | 49 + .../WeiCloud.Core/Common/DateTimeTools.cs | 351 +++ .../Common/DatetimeJsonConverter.cs | 27 + .../EnergyConsumPlan/EnergyConsumPlanConst.cs | 18 + .../WeiCloud.Core/Common/EnthalpyBase.cs | 32 + .../Common/EquipGroup/EquipGroupConst.cs | 21 + .../Common/EquipPart/EquipPartConst.cs | 26 + .../WeiCloud.Core/Common/ExceptionHelp.cs | 27 + .../WeiCloud.Core/Common/ExpandClass.cs | 677 ++++++ .../WeiCloud.Core/Common/FanCmdContextVo.cs | 17 + .../WeiCloud.Core/Common/HealthLevel.cs | 166 ++ .../WeiCloud.Core/Common/HolidayUtil.cs | 43 + .../WeiCloud.Core/Common/HttpClientHelper.cs | 162 ++ .../StaticHttpContextExtensions.cs | 27 + .../Common/HttpContext/WEIHttpContext.cs | 19 + .../WeiCloud.Core/Common/HttpContextHelper.cs | 63 + .../WeiCloud.Core/Common/HttpHelper.cs | 875 ++++++++ .../WeiCloud.Core/Common/HttpUtils.cs | 99 + .../WeiCloud.Core/Common/IPUtil.cs | 10 + .../Interceptor/SlowQueryInterceptor.cs | 58 + .../WeiCloud.Core/Common/LocalCache.cs | 10 + .../WeiCloud.Core/Common/MathExpandClass.cs | 21 + .../WeiCloud.Core/Common/MyAllowAnonymous.cs | 87 + .../WeiCloud.Core/Common/NumberCharConvert.cs | 10 + .../Common/PolicyContextModel.cs | 28 + .../Common/PostUniClientModel.cs | 34 + .../WeiCloud.Core/Common/QueryConst.cs | 350 +++ .../Common/RandomNumberCreate.cs | 138 ++ .../WeiCloud.Core/Common/RealValueMean.cs | 43 + .../Common/SteamHeatCalculate.cs | 15 + .../WeiCloud.Core/Common/Tasks/TaskManager.cs | 44 + .../EnumTools/AirQuantityEnum.cs | 33 + .../WeiCloud.Core/EnumTools/AssetTypeEnum.cs | 11 + .../WeiCloud.Core/EnumTools/CarbonEnum.cs | 33 + .../WeiCloud.Core/EnumTools/ClimNum.cs | 15 + .../WeiCloud.Core/EnumTools/ConModelEnum.cs | 30 + .../WeiCloud.Core/EnumTools/ConstTypeEnum.cs | 49 + .../EnumTools/DataSetGroupEnum.cs | 27 + .../WeiCloud.Core/EnumTools/EnergyItemEnum.cs | 43 + .../EnumTools/EngeryBillingType.cs | 47 + .../WeiCloud.Core/EnumTools/EngeryTypeEnum.cs | 46 + .../WeiCloud.Core/EnumTools/EnumHelper.cs | 40 + .../EnumTools/EnumSystemModel.cs | 34 + .../WeiCloud.Core/EnumTools/Enumeration.cs | 111 + .../WeiCloud.Core/EnumTools/Enumeration2.cs | 131 ++ .../EnumTools/EqGroupTypeEnum.cs | 99 + .../EnumTools/EquipRuningStatus.cs | 28 + .../WeiCloud.Core/EnumTools/EquipTypeEnum.cs | 220 ++ .../EnumTools/FamilyDecorationEnum.cs | 85 + .../EnumTools/FauabnormalEnum.cs | 38 + .../EnumTools/FaultHandleEnum.cs | 31 + .../EnumTools/FaultStatusEnum.cs | 34 + .../EnumTools/FunPermissionEnum.cs | 13 + .../WeiCloud.Core/EnumTools/GearEnum.cs | 31 + .../EnumTools/HandWritetenEnum.cs | 13 + .../WeiCloud.Core/EnumTools/InfoApiEnum.cs | 239 ++ .../WeiCloud.Core/EnumTools/IotDsEnum.cs | 29 + .../WeiCloud.Core/EnumTools/KBEnum.cs | 34 + .../WeiCloud.Core/EnumTools/MenuTypeEnum.cs | 22 + .../WeiCloud.Core/EnumTools/MsgServiceEnum.cs | 74 + .../WeiCloud.Core/EnumTools/NlogTypeNum.cs | 16 + .../WeiCloud.Core/EnumTools/NormUnitNum.cs | 18 + .../WeiCloud.Core/EnumTools/PayEnum.cs | 45 + .../WeiCloud.Core/EnumTools/ProAlarm.cs | 66 + .../EnumTools/RealDataValueTypeEnum.cs | 20 + .../EnumTools/RequestBackStatuEnum.cs | 94 + .../EnumTools/STTargetCategoryEnum.cs | 29 + .../WeiCloud.Core/EnumTools/SafetyEnum.cs | 619 ++++++ .../EnumTools/StandardCoalEnum.cs | 103 + .../EnumTools/SyaConfigNameEnum.cs | 47 + .../EnumTools/SysBaseCodeMeta.cs | 111 + .../WeiCloud.Core/EnumTools/SysModuleEnum.cs | 11 + .../WeiCloud.Core/EnumTools/TaskApiEnum.cs | 16 + .../WeiCloud.Core/EnumTools/TenantPayEnum.cs | 32 + .../WeiCloud.Core/EnumTools/TimeSpanEnum.cs | 26 + .../EnumTools/UserCenterApiEnum.cs | 116 + .../EnumTools/WorkOrderProConfig.cs | 44 + .../WeiCloud.Core/EnumTools/说明.txt | 26 + .../EventBus/CapPublisherService.cs | 69 + .../WeiCloud.Core/EventBus/FaultMsgModel.cs | 51 + .../IBusinessMessageSubscriberEventBus.cs | 10 + .../EventBus/IMessageSubscriberEventBus.cs | 9 + .../EventBus/IPublisherService.cs | 22 + .../EventBus/MessageSubscriberEventBus.cs | 134 ++ .../EventBus/MsgTempateEventDto.cs | 32 + .../WeiCloud.Core/EventBus/SendTypeMeta.cs | 17 + .../Extension/ExceptionExtension.cs | 36 + .../Extension/FriendlyException.cs | 18 + .../Extension/IQueryableExtensions.cs | 84 + .../Extension/TryConvertExtension.cs | 198 ++ .../Filters/ApiIgnoreAttribute.cs | 14 + .../WeiCloud.Core/Filters/ApiResultFilter.cs | 75 + .../WeiCloud.Core/Filters/AuthActionFilter.cs | 175 ++ .../Filters/FunctionAttribute.cs | 23 + .../Filters/GlobalExceptionsFilter.cs | 90 + .../Filters/SkipMyGlobalActionFilter.cs | 15 + .../Filters/TenantAccessCheckFilter.cs | 88 + .../Filters/ValidateFieldsMiddleware.cs | 89 + .../HostService/LogHostedService.cs | 36 + .../WeiCloud.Core/HostService/MonitorLog.cs | 56 + .../HostService/MonitorLogTaskHost.cs | 37 + .../WeiCloud.Core/LocalCache/LocalData.cs | 402 ++++ .../WeiCloud.Core/ML/RegressionUtil.cs | 161 ++ .../WeiCloud.Core/ML/TrainModel.cs | 18 + .../Middleware/ImgResponseMiddleware.cs | 265 +++ .../WeiCloud.Core/Middleware/LogMiddleware.cs | 65 + .../MsgSocket/MsgWebSocketClientInstance.cs | 191 ++ .../MsgSocket/MsgWebSocketMessageHandler.cs | 76 + .../NlogTools/INlogMessageHelper.cs | 13 + .../WeiCloud.Core/NlogTools/LoggerHelper.cs | 187 ++ .../NlogTools/NlogMessageHelper.cs | 300 +++ .../WeiCloud.Core/PayTool/HttpMethods.cs | 159 ++ .../WeiCloud.Core/PayTool/PayRequesEntity.cs | 34 + .../WeiCloud.Core/PayTool/WeChatPayHelper.cs | 180 ++ .../WeiCloud.Core/Report/ReportEnum.cs | 68 + .../RulesEngine/CronExpressionHelper.cs | 169 ++ .../RulesEngine/ExecuterRepository.cs | 99 + .../RulesEngine/IExecuterContainer.cs | 12 + .../RulesEngine/IExecuterRepository.cs | 31 + .../RulesEngine/IExecuterSession.cs | 28 + .../WeiCloud.Core/RulesEngine/NRulesHelper.cs | 33 + .../RulesEngine/NulesExecuterContainer.cs | 26 + .../RulesEngine/NulesExecuterSession.cs | 30 + .../RulesEngine/RuleDefinition.cs | 23 + .../RulesEngine/RulesModels/Arithmetic.cs | 7 + .../RulesEngine/RulesModels/Energy.cs | 41 + .../RulesEngine/RulesModels/EnergyTypeEnum.cs | 25 + .../RulesEngine/RulesModels/IEntity.cs | 7 + .../RulesEngine/RulesModels/RuleConditions.cs | 54 + .../RulesEngine/RulesModels/RuleInfos.cs | 166 ++ .../RulesEngine/RulesModels/RuleTypes.cs | 19 + .../Schedule/ScheduleItemConvert.cs | 82 + .../CarbonEmission/CarbonEmissionService.cs | 135 ++ .../CarbonEmission/ICarbonEmissionService.cs | 14 + .../Services/ConstrInfoGainCoreService.cs | 213 ++ .../IProjectParamMethodRuleCoreService.cs | 13 + .../DataStream/ISubscribePointCoreService.cs | 21 + .../Services/DataStream/ITimeSeqService.cs | 19 + .../ProjectParamMethodRuleCoreService.cs | 202 ++ .../DataStream/SubscribePointCoreService.cs | 175 ++ .../Services/DataStream/TimeSeqService.cs | 607 +++++ .../Services/EnergySaveDwService.cs | 51 + .../Services/EquipInfoCoreService.cs | 32 + .../EquipPart/EquipPartCoreService.cs | 207 ++ .../EquipPart/IEquipPartCoreService.cs | 11 + .../EquipReport/EquipStatisticsService.cs | 1961 +++++++++++++++++ .../EquipReport/IEquipStatisticsService.cs | 29 + .../Services/IConstrInfoGainCoreService.cs | 18 + .../Services/IEnergySaveDwCoreService.cs | 18 + .../Services/IEquipInfoCoreService.cs | 11 + .../Services/INlogCoreService.cs | 20 + .../Services/IPermissionsGainCoreService.cs | 11 + .../Services/IProjectDWCoreService.cs | 12 + .../Services/IProjectInfoGainCoreService.cs | 15 + .../Services/IPublicFunctionService.cs | 26 + .../Services/IRealDataAnalyzeCoreService.cs | 14 + .../Services/IStandarParamsCoreService.cs | 14 + .../Services/ISteamHeatCalculateService.cs | 12 + .../Services/IUserGroupsGainCoreService.cs | 14 + .../IUserProjectPermissionsCoreService.cs | 17 + .../IUserProjectPressRedisTreeService.cs | 15 + .../Services/IUsersCoreService.cs | 20 + .../Services/IUsersGainCoreService.cs | 11 + .../Services/IWorkflowService.cs | 13 + .../WeiCloud.Core/Services/Iot/IIotService.cs | 12 + .../WeiCloud.Core/Services/Iot/IotService.cs | 73 + .../Services/Job/IJobManagerCoreService.cs | 10 + .../Services/Job/JobManagerCoreService.cs | 58 + .../Services/Message/IMessageService.cs | 12 + .../Services/Message/IMsgCenterCoreService.cs | 14 + .../Services/Message/MessageService.cs | 459 ++++ .../Services/Message/MsgCenterCoreService.cs | 476 ++++ .../Services/Message/UniPushInstance.cs | 41 + .../Module/IModuleManagerCoreService.cs | 13 + .../Services/Module/IModuleMenuCoreService.cs | 11 + .../Module/ModuleManagerCoreService.cs | 52 + .../Services/Module/ModuleMenuCoreService.cs | 44 + .../WeiCloud.Core/Services/Msg/IMsgService.cs | 15 + .../WeiCloud.Core/Services/Msg/MsgService.cs | 163 ++ .../WeiCloud.Core/Services/NlogCoreService.cs | 299 +++ .../Permission/FunPermissionCoreService.cs | 100 + .../Permission/IFunPermissionCoreService.cs | 14 + .../Services/PermissionsGainCoreService.cs | 30 + .../Services/PredicateBuilder.cs | 33 + .../Services/ProAlarm/IProAlarmService.cs | 21 + .../Services/ProAlarm/ProAlarmService.cs | 418 ++++ .../Services/ProjectDWCoreService.cs | 55 + .../Services/ProjectInfoGainCoreService.cs | 46 + .../Services/PublicFunctionService.cs | 625 ++++++ .../Services/RealData/IRealDataCoreService.cs | 29 + .../Services/RealData/RealDataCoreService.cs | 1761 +++++++++++++++ .../Services/RealDataAnalyzeCoreService.cs | 110 + .../Services/Report/DataSourceService.cs | 284 +++ .../Services/Report/DataSourceV02Service.cs | 1086 +++++++++ .../Services/Report/DataSourceV03Service.cs | 787 +++++++ .../Services/Report/EnergyConsumService.cs | 380 ++++ .../Services/Report/IDataSourceService.cs | 16 + .../Services/Report/IDataSourceV02Service.cs | 14 + .../Services/Report/IDataSourceV03Service.cs | 21 + .../Services/Report/IEnergyConsumService.cs | 15 + .../Services/StandarParamsCoreService.cs | 76 + .../Services/SteamHeatCalculateService.cs | 41 + .../Services/Tenement/ITenantEMSService.cs | 11 + .../Services/Tenement/TenantEMSService.cs | 73 + .../Services/UserGroupsGainCoreService.cs | 73 + .../UserProjectPermissionsCoreService.cs | 88 + .../UserProjectPressRedisTreeCoreService.cs | 639 ++++++ .../Services/UsersCoreService.cs | 247 +++ .../Services/UsersGainCoreService.cs | 37 + .../WeiCloud.Core/Services/WorkflowService.cs | 63 + .../StartUp/ShardingCoreExtend.cs | 166 ++ .../TenantDb/MultipleTenancyExtension.cs | 65 + .../TenantDb/SqlConnectionResolver.cs | 75 + .../WeiCloud.Core/TenantDb/TenantInfo.cs | 22 + .../TenantDb/TenantInfoMiddleware.cs | 38 + .../WeiCloud.Core/WeiCloud.Core.csproj | 65 + 239 files changed, 25732 insertions(+) create mode 100644 WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/RequestBackStatuEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/说明.txt create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs create mode 100644 WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj diff --git a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs new file mode 100644 index 0000000..49525fc --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.BaseModels; +namespace WeiCloud.Core.AliYunSms +{ + public interface ISmsHelperService + { + SmsResposeModel SendSms(string phoneNumber, string templateParams, int type); + SmsResposeModel SendSms(string phoneNumber, string signName, string templateCode, string templateParams, string accessKeyId, string accessSecret, string host); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs new file mode 100644 index 0000000..bc02d06 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections.Generic; +using Aliyun.Acs.Core; +using Aliyun.Acs.Core.Profile; +using Aliyun.Acs.Core.Exceptions; +using Aliyun.Acs.Core.Http; +using Newtonsoft.Json; +using WeiCloud.Entity.LogicModels.BaseModels; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using AlibabaCloud.SDK.Dysmsapi20170525.Models; + +namespace WeiCloud.Core.AliYunSms +{ + public class SmsHelperService : ISmsHelperService + { + private readonly string _accessKeyId; + private readonly string _accessSecret; + private readonly string _regionId; + + /// + /// 发送单条短信 + /// + private readonly string _sendSms_signName; + private readonly string _sendSms_templateCode; + private readonly string _sendOrderSms_signName; + private readonly string _sendOrderSms_templateCode; + private readonly string _sendKnowledgeSms_signName; + private readonly string _sendKnowledgeSms_templateCode; + private readonly string _sendFaultSms_signName; + private readonly string _sendFaultSms_templateCode; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + /// + /// 发送多条短信 待扩充 + /// + private readonly string _sendBatchSms_signName; + private readonly string _sendBatchSms_templateCode; + + public SmsHelperService(IConfiguration configuration, ILogger logger) + { + _logger = logger; + _configuration = configuration; + _accessKeyId = _configuration["AliYunSms:API_KEY"]; + _accessSecret = _configuration["AliYunSms:SECRET_KEY"]; + _regionId = _configuration["AliYunSms:REGION_ID"]; + _sendSms_signName = _configuration["AliYunSms:SendSms:SIGN_NAME"]; + _sendSms_templateCode = _configuration["AliYunSms:SendSms:TEMPLATE_CODE"]; + + + _sendOrderSms_signName = _configuration["AliYunSms:SendOrderSms:SIGN_NAME"]; + _sendOrderSms_templateCode = _configuration["AliYunSms:SendOrderSms:TEMPLATE_CODE"]; + _sendKnowledgeSms_signName = _configuration["AliYunSms:SendKnowledgeSms:SIGN_NAME"]; + _sendKnowledgeSms_templateCode = _configuration["AliYunSms:SendKnowledgeSms:TEMPLATE_CODE"]; + _sendFaultSms_signName = _configuration["AliYunSms:SendFaultSms:SIGN_NAME"]; + _sendFaultSms_templateCode = _configuration["AliYunSms:SendFaultSms:TEMPLATE_CODE"]; + + //_sendBatchSms_signName = _configuration["AliYunSms:SendBatchSms:SIGN_NAME"]; + //_sendBatchSms_templateCode = _configuration["AliYunSms:SendBatchSms:TEMPLATE_CODE"]; + } + /// + /// 发送单条短信 + /// + /// 手机号 + /// 模板内容JsonString + /// 0验证码 1工单2知识库 3报警 + /// SmsResponse 实体 Code=OK为成功 其他为失败 + public SmsResposeModel SendSms(string phoneNumber, string templateParams, int type) + { + try + { + AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config + { + // 您的AccessKey ID + AccessKeyId = _accessKeyId, + // 您的AccessKey Secret + AccessKeySecret = _accessSecret, + }; + // 访问的域名 + config.Endpoint = "dysmsapi.aliyuncs.com"; + var client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config); + + string tempcode = ""; + string param = ""; + string signname = ""; + switch (type) + { + case 0: + tempcode = _sendSms_templateCode; + signname = _sendSms_signName; + param = templateParams; + + break; + case 1: //工单 + tempcode = _sendOrderSms_templateCode; + signname = _sendOrderSms_signName; + param = templateParams; + + break; + case 2://知识库 + tempcode = _sendKnowledgeSms_templateCode; + signname = _sendKnowledgeSms_signName; + param = templateParams; + break; + case 3://报警 + tempcode = _sendFaultSms_templateCode; + signname = _sendFaultSms_signName; + param = templateParams; + + break; + case 4://计划管理 待扩充 + + break; + case 5: //智能诊断 + tempcode = _sendFaultSms_templateCode; + signname = _sendFaultSms_signName; + param = templateParams; + break; + default: + tempcode = _sendSms_templateCode; + signname = _sendSms_signName; + param = templateParams; + break; + } + _logger.LogWarning($"发送短信参数为{phoneNumber} {signname} {tempcode} {templateParams}"); + var sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest + { + PhoneNumbers = phoneNumber, + SignName = signname, + TemplateCode = tempcode, + TemplateParam = templateParams, + }; + + SendSmsResponse sendSms = client.SendSms(sendSmsRequest); + if (sendSms.Body.Code.ToLower() == "ok") + { + return new SmsResposeModel + { + Message = sendSms.Body.Message, + Code = "OK" + }; + } + else + { + return new SmsResposeModel + { + Message = "Http错误," + sendSms.Body.Message, + Code = "HTTP_ERROR" + }; + } + } + catch (Exception ex) + { + + return new SmsResposeModel + { + Message = "Http错误," + ex.Message, + Code = "HTTP_EXCEPT" + }; + } + } + /// + /// 发送短信 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public SmsResposeModel SendSms(string phoneNumber, string signName, string templateCode, string templateParams, string accessKeyId, string accessSecret, string host) + { + try + { + AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config + { + // 您的AccessKey ID + AccessKeyId = accessKeyId, + // 您的AccessKey Secret + AccessKeySecret = accessSecret, + }; + // 访问的域名 + config.Endpoint = host; + var client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config); + + + _logger.LogWarning($"发送短信参数为{phoneNumber} {signName} {templateCode} {templateParams}"); + var sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest + { + PhoneNumbers = phoneNumber, + SignName = signName, + TemplateCode = templateCode, + TemplateParam = templateParams, + }; + + SendSmsResponse sendSms = client.SendSms(sendSmsRequest); + if (sendSms.Body.Code.ToLower() == "ok") + { + return new SmsResposeModel + { + Message = sendSms.Body.Message, + Code = "OK" + }; + } + else + { + return new SmsResposeModel + { + Message = "Http错误," + sendSms.Body.Message, + Code = "HTTP_ERROR" + }; + } + } + catch (Exception ex) + { + + return new SmsResposeModel + { + Message = "Http错误," + ex.Message, + Code = "HTTP_EXCEPT" + }; + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs new file mode 100644 index 0000000..68255ba --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.BaseCore +{ + public interface IClusterClient + { + T GetGrain(long guiId) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey; + } + public class ClusterClient: IClusterClient + { + private readonly IServiceProvider _serviceProvider; + public ClusterClient(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + public T GetGrain(long guiId) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + var serviceInstence = _serviceProvider.GetService(typeof(T)); + return (T)serviceInstence; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs new file mode 100644 index 0000000..7973b8d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Core.Common; + +namespace WeiCloud.Core.BaseCore +{ + public class Grain + { + public GrainFactory GrainFactory { get; set; } + public CurrentContext CurrentContext { get; set; } + public Grain() { } + //public Grain(GrainFactory GrainFactory, CurrentContext CurrentContext) + //{ + // this.GrainFactory = GrainFactory; + // this.CurrentContext = CurrentContext; + //} + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs new file mode 100644 index 0000000..5b5101c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Core.Common; + +namespace WeiCloud.Core.BaseCore +{ + //public interface GrainFactory + //{ + // T GetGrain(long guid) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey; + //} + public class GrainFactory //: GrainFactory + { + private readonly IServiceProvider _serviceProvider; + public GrainFactory(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + } + public T GetGrain(long guid) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + return (T)_serviceProvider.GetService(typeof(T)); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs new file mode 100644 index 0000000..49ebe58 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs @@ -0,0 +1,13 @@ +using Autofac.Extras.DynamicProxy; +using MonitorAopLog.Util; +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.BaseCore +{ + [Intercept(typeof(FunctionInterceptor))] + public interface IGrainWithIntegerKey + { + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs new file mode 100644 index 0000000..7bb0c79 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.BaseCore +{ + + public class ReentrantAttribute: Attribute + { + } + public class AlwaysInterleave : Attribute + { + + } + [AttributeUsage(AttributeTargets.Property)] + public class AutowiredAttribute : Attribute + { + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs new file mode 100644 index 0000000..689ef94 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Calculation +{ + public enum CalculationformulaEnum + { + COP = 1, + WTF = 5, + WTFcw = 6, + η = 7 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs new file mode 100644 index 0000000..2ebb2a9 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.DataAnalysis; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Calculation +{ + public class DateTimeComponetUtil + { + static List<(DateTime, DateTime)> SplitTimePeriod(DateTime start, DateTime end, IntervalType intervalType) + { + List<(DateTime, DateTime)> result = new List<(DateTime, DateTime)>(); + DateTime currentStart = start; + + while (currentStart < end) + { + DateTime currentEnd; + + switch (intervalType) + { + case IntervalType.Hour: + currentEnd = currentStart.AddHours(1).AddSeconds(-1); + break; + case IntervalType.Day: + currentEnd = currentStart.AddDays(1).AddSeconds(-1); + break; + case IntervalType.Month: + currentEnd = currentStart.AddMonths(1).AddSeconds(-1); + break; + case IntervalType.Year: + currentEnd = new DateTime(currentStart.Year, 12, 31).AddDays(1).AddSeconds(-1); + break; + default: + throw new ArgumentException("Invalid interval type"); + } + + if (currentEnd > end) + { + currentEnd = end; + } + + result.Add((currentStart, currentEnd)); + currentStart = currentEnd.AddSeconds(1); + } + + return result; + } + public static (DateTime, DateTime, List<(DateTime, DateTime)>, IntervalType) GetStartAndEndTime(TimeDimenEnum timeDimen, QueryTimeModel queryTime, IntervalType intervalType = IntervalType.Hour) + { + DateTime startTime = DateTime.MinValue; + DateTime endTime = DateTime.MaxValue; + List<(DateTime, DateTime)> timePeriods = new List<(DateTime, DateTime)>(); + switch (timeDimen) + { + case TimeDimenEnum.Day: + startTime = queryTime.StartTime; + endTime = queryTime.StartTime.AddHours(24).AddTicks(-1); + break; + case TimeDimenEnum.Month: + startTime = new DateTime(queryTime.StartTime.Year, queryTime.StartTime.Month, 1); + endTime = startTime.AddMonths(1).AddTicks(-1); + break; + case TimeDimenEnum.Year: + startTime = new DateTime(queryTime.StartTime.Year, 1, 1); + endTime = startTime.AddYears(1).AddTicks(-1); + break; + case TimeDimenEnum.CustomRange: + startTime = queryTime.StartTime; + endTime = queryTime.EndTime.AddDays(1).AddTicks(-1); + var timeDiff = (endTime - startTime).TotalHours; + if (0 < timeDiff && timeDiff <= 24 * 7)//按小时统计 + { + intervalType = IntervalType.Hour; + } + else if (24 * 7 < timeDiff && timeDiff <= 24 * 30)//按天统计 + { + intervalType = IntervalType.Day; + } + else if (24 * 30 < timeDiff && timeDiff <= 24 * 365)//按月统计 + { + intervalType = IntervalType.Month; + } + else + { + intervalType = IntervalType.Year; + } + break; + } + + timePeriods = SplitTimePeriod(startTime, endTime, intervalType); + return (startTime, endTime, timePeriods, intervalType); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs new file mode 100644 index 0000000..69facfa --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Eventing.Reader; +using System.Text; + +namespace WeiCloud.Core.Calculation +{ + public static class EngeryCalculation + { + private static readonly float q = (float)34.9 * 1000; //天然气热值,单位为:kJ/m3 + + /// + /// 直燃机能效计算 + /// + /// 热量表取值 + /// 燃气消耗量 + /// 耗电量 + /// 能效值 + public static double DirectFireEngeryCalcu(double? heat, double? gas, double? elect) + { + double engValue = 0; + //单位:无量纲(kW/kW),供热时取%,供冷时取实际值,如1.23(取小数点后两位)其中为热量表取值,单位应为kW(瞬时量)/ kWh(累计量),首页取值可以取1小时的累计量;其中V为天燃气消耗量(m3 / h),q为天然气热值,单位为kJ / m3,暂取34.9×103 kJ / m3;Wp为直燃机耗电量, 单位应为kW(瞬时量)/ kWh(累计量)。 + var qg = gas * q / 3600; + if ((qg + elect) > 0) + { + var data = heat / (qg + elect); + if (data > 0) + { + engValue = (double)data; + } + } + return engValue; + } + /// + /// 冷热泵、冷却泵、冷却塔能效 + /// + /// 热量表取值 + /// 电耗 + /// 能效值 + public static double CoolHotPumpEngeryCalu(double? heat, double? elect) + { + double coolhotEng = 0; + if (elect > 0 && heat > 0) + { + coolhotEng = (double)heat / (double)elect; + } + return coolhotEng; + } + /// + /// 系统能效 + /// + /// + /// + /// + /// + public static double SysEnergyEfficiency(double heat, double gas, double elect) + { + double eer = 0; + var denominator = gas * q / 3600 + elect; + if (denominator != 0) + { + eer = heat / denominator; + } + return eer; + } + + /// + /// 气-等价电 + /// + /// + /// + public static double GasConvertEquivalentElectricity(double gas) + { + return 3.355 * gas; + } + + public static double kwhToCO2 = 0.0009970; + + + /// + /// 获取温湿度焓值计算公式 + /// + /// 温度 + /// 湿度 + /// 返回的焓值结果 + /// 比较值 当大于值返回flalse 小于值返回true + /// + public static bool GetTemHumiEnthalpy(double temperature, double humidity, out double enthalpy, double equalVal = 58.46) + { + //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 + //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) + + //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; + double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; + //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) + double b = humidity / 100 * a * 100; + double c = 101300 - humidity / 100 * a * 100; + //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) + enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); + return !(enthalpy > equalVal); + } + + /// + /// 获取温湿度焓值计算公式 + /// + /// 温度 + /// 湿度 + /// 返回的焓值结果 + /// 比较值 当大于值返回flalse 小于值返回true + /// 浮动值 在浮动值区间内都是正常 + /// 1 制热 2制冷 其他 + /// + public static bool GetTemHumiEnthalpyEx(double temperature, double humidity, out double enthalpy, double equalVal = 58.46, double floatingVal = 2, int? condition = null) + { + //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 + //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) + + //夏季舒适条件(如24℃、50 % 湿度)对应的焓值约为 48 - 50 kJ / kg ; 47.9 + //冬季舒适条件(如20℃、40 % 湿度)对应的焓值约为 35 - 38 kJ / kg 。 34.91 + + + //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; + double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; + //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) + double b = humidity / 100 * a * 100; + double c = 101300 - humidity / 100 * a * 100; + //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) + enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); + if (condition == 1) //冬天是 > 焓值是舒适 否则是不舒适 + { + if (enthalpy >= (equalVal - floatingVal)) + { + return true; + } + return false; + } + else if (condition == 2)//夏天是 < 焓值是舒适 否则是不舒适 + { + if (enthalpy <= (equalVal + floatingVal)) + { + return true; + } + return false; + } + else //其他情况就是在波动区间是舒适的 非波动区间是不舒适的 + { + if (enthalpy >= (equalVal - floatingVal) && enthalpy <= (equalVal + floatingVal)) + { + return true; + } + return false; + } + + } + + + /// + /// 获取湿球温度 + /// + /// + /// + /// + public static double GetWetBulbTemp(double temperature, double humitity) + { + if (temperature == 0 && humitity == 0) + { + return 0; + } + // 湿球温度 = ((温度 + 21.82 - ((100 - 湿度) / 8.842) ^ (1 / 0.8718)) ^ 2 - (温度 - 21.82) ^ 2) / 86.88 + double d = (Math.Pow(temperature + 21.82 - Math.Pow(((100 - humitity) / 8.842), (1 / 0.8718)), 2) - Math.Pow((temperature - 21.82), 2)) / 86.88; + //湿球温度=((温度+21.82-((100-湿度)/8.842)^(1/0.8718))^2-(温度-21.82)^2)/86.88 + //(d)/86.88 + //d = (b)^2-c + // b = 温度+21.82-((100-湿度)/8.842)^(1/0.8718) + //c= (温度-21.82)^2 + //(Math.Pow(S1 + 21.82 - Math.Pow(((100 - S2) / 8.842), (1 / 0.8718)), 2) - Math.Pow((S1 - 21.82), 2)) / 86.88; + return d; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs new file mode 100644 index 0000000..6cca599 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels; + +namespace WeiCloud.Core.Calculation +{ + public class QueryExpressionFunc + { + private List GetCSharp(GetExpressionFuncVo input) + { + var items = new List(); + if (input.FuncTypes.Contains(2)) + { + var mathFunc = new ExpressionFuncVo + { + FuncTypeName = "数学", + Functions = new List + { + new ExpressionFuncViewModel { Func="Math.Abs",Desc="获取指定数值(number)的绝对值",Syntax="Abs(number)"}, + new ExpressionFuncViewModel { Func="Math.Floor",Desc="返回小于或等于number的最大整数",Syntax="Floor(number)"}, + new ExpressionFuncViewModel { Func="Math.Ceiling",Desc="返回大于或等于number的最小整数值",Syntax="Ceiling(number)"}, + new ExpressionFuncViewModel { Func="Math.Round",Desc="将值舍入到最接近的整数或指定的小数位数",Syntax="Round(number)"}, + new ExpressionFuncViewModel { Func="Math.Sqrt",Desc="返回指定数字的平方根",Syntax="Sqrt(number)"}, + new ExpressionFuncViewModel { Func="Math.Pow",Desc="返回指定数字的指定次幂",Syntax="Pow(number)"} + } + }; + items.Add(mathFunc); + } + if (input.FuncTypes.Contains(1)) + { + var statisticsFunc = new ExpressionFuncVo + { + FuncTypeName = "统计", + Functions = new List + { + new ExpressionFuncViewModel { Func="Math.Max",Desc="返回字段(number)中的最大值",Syntax="Max(number1,number2)"}, + new ExpressionFuncViewModel { Func="Math.Min",Desc="返回字段(number)中的最小值",Syntax="Min(number1,number2)"} + } + }; + items.Add(statisticsFunc); + } + if (input.FuncTypes.Contains(3)) + { + var dateFun = new ExpressionFuncVo + { + FuncTypeName = "日期", + Functions = new List + { + new ExpressionFuncViewModel { Func="ADDDATE",Desc="计算起始日期 d 加上 n 天的日期",Syntax="ADDDATE(d,n)"}, + new ExpressionFuncViewModel { Func="ADDTIME",Desc="n 是一个时间表达式,时间 t 加上时间表达式 n",Syntax="ADDTIME(t,n)"}, + new ExpressionFuncViewModel { Func="DATE_ADD",Desc="计算起始日期 d 加上一个时间段后的日期",Syntax="DATE_ADD(d,INTERVAL expr type)"}, + new ExpressionFuncViewModel { Func="DATEDIFF",Desc="计算日期 d1->d2 之间相隔的天数",Syntax="DATEDIFF(d1,d2)"}, + new ExpressionFuncViewModel { Func="DATE_FORMAT",Desc="按表达式 f的要求显示日期 d",Syntax="DATE_FORMAT(d,f)"}, + new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, + new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, + new ExpressionFuncViewModel { Func="HOUR",Desc="返回 t 中的小时值",Syntax="HOUR(t)"}, + new ExpressionFuncViewModel { Func="MONTH",Desc="返回日期d中的月份值,1 到 12",Syntax="MONTH(t)"}, + new ExpressionFuncViewModel { Func="YEAR",Desc="返回年份,1 到 12",Syntax="YEAR(t)"} + } + }; + items.Add(dateFun); + } + return items; + } + private List GetSql(GetExpressionFuncVo input) + { + var items = new List(); + if (input.FuncTypes.Contains(1)) + { + var statisticsFunc = new ExpressionFuncVo + { + FuncTypeName = "数字", + Functions = new List + { + new ExpressionFuncViewModel { Func="FLOOR",Desc="返回小于或等于 x 的最大整数",Syntax="FLOOR(1.5)"}, + new ExpressionFuncViewModel { Func="CEIL",Desc="返回大于或等于 x 的最小整数",Syntax="CEIL(1.5)"}, + new ExpressionFuncViewModel { Func="ROUND",Desc="返回离 x 最近的整数,可选参数 y 表示要四舍五入的小数位数,如果省略,则返回整数",Syntax="ROUND(345.156, 2)"}, + new ExpressionFuncViewModel { Func="SUM",Desc="返回指定字段的总和",Syntax="SUM(Quantity)"}, + new ExpressionFuncViewModel { Func="MAX",Desc="返回字段 expression 中的最大值",Syntax="MAX(expression)"}, + new ExpressionFuncViewModel { Func="MIN",Desc="返回字段 expression 中的最小值",Syntax="MIN(expression)"}, + } + }; + items.Add(statisticsFunc); + } + if (input.FuncTypes.Contains(2)) + { + var statisticsFunc = new ExpressionFuncVo + { + FuncTypeName = "日期", + Functions = new List + { + new ExpressionFuncViewModel { Func="ADDDATE",Desc="计算起始日期 d 加上 n 天的日期",Syntax="ADDDATE(d,n)"}, + new ExpressionFuncViewModel { Func="DATE",Desc="从日期或日期时间表达式中提取日期值",Syntax="DATE()"}, + new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, + new ExpressionFuncViewModel { Func="HOUR",Desc="返回 t 中的小时值",Syntax="HOUR(t)"}, + new ExpressionFuncViewModel { Func="MINUTE",Desc="返回 t 中的分钟值",Syntax="MINUTE(t)"}, + new ExpressionFuncViewModel { Func="YEAR",Desc="返回年份",Syntax="YEAR(d)"}, + new ExpressionFuncViewModel { Func="MONTH",Desc="返回日期d中的月份值,1 到 12",Syntax="MONTH(d)"}, + new ExpressionFuncViewModel { Func="SECOND",Desc="返回 t 中的秒钟值,1 到 12",Syntax="SECOND(t)"}, + } + }; + items.Add(statisticsFunc); + } + return items; + } + public List GetExpressions(GetExpressionFuncVo input) + { + if (input.ProgramLanguage == 1) + { + return GetCSharp(input); + } + else if (input.ProgramLanguage == 3) + { + return GetSql(input); + } + return new List { }; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs new file mode 100644 index 0000000..997491d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Calculation +{ + public class UnitConvertUtil + { + /// + /// 单位转换 + /// + /// 原单位 + /// 原值 + /// 目标单位 + /// 目标值 + public static double ParamConvert(string sUnit, double sValue, string dUnit) + { + float sValue_F = Convert.ToSingle(sValue); + var r = ParamConvert(sUnit, sValue_F, dUnit); + return Convert.ToDouble(r); + } + /// + /// 单位转换 + /// + /// 原单位 + /// 原值 + /// 目标单位 + /// 目标值 + public static float ParamConvert(string sUnit, float sValue, string dUnit) + { + float realvalue = 0; + if (dUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("L/s", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue * 1000 / 3600; + } + else if (dUnit.Equals("L/s", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue * 3600 / 1000; + } + else if (dUnit.Equals("kwh", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kj", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 3600; + } + else if (dUnit.Equals("kj", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kwh", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue * 3600; + } + else if (dUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/s", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 3600; + } + else if (dUnit.Equals("m³/s", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue * 3600; + } + else if (dUnit.Equals("MWh", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kWh", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + else if (dUnit.Equals("kt", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + else if (dUnit.Equals("km³", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + else if (dUnit.Equals("KJ", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("J", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + else if (dUnit.Equals("GJ", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("MJ", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + //标煤千克换算吨 + else if (dUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kg", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + //标煤吨换算千吨 + else if (dUnit.Equals("kt", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + //标煤千吨换算兆吨 + else if (dUnit.ToLower().Equals("mt", StringComparison.InvariantCultureIgnoreCase) && sUnit.ToLower().Equals("kt", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000; + } + //标煤吨换算兆吨 + else if (dUnit.ToLower().Equals("mt", StringComparison.InvariantCultureIgnoreCase) && sUnit.ToLower().Equals("t", StringComparison.InvariantCultureIgnoreCase)) + { + realvalue = sValue / 1000000; + } + else + { + realvalue = sValue; + } + return realvalue; + } + + + + /// + /// 计算比率 + /// + /// 分子 + /// 分母 + /// 是否乘以100 + /// 保留小数位 + /// + public static decimal CalRate(decimal fenzi, decimal fenmu, bool x100 = true, int decimalPlace = 2) + { + if (x100) + { + return decimal.Round((fenmu > 0 ? fenzi / fenmu : 0) * 100, decimalPlace); + } + else + { + return decimal.Round((fenmu > 0 ? fenzi / fenmu : 0), decimalPlace); + } + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs new file mode 100644 index 0000000..eb5d77d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core +{ + public class AppConstant + { + public static string TIMESTAMP { get => "TIMESTAMP"; private set { } } + /// + /// 采集时间和服务器时间间隔 + /// + /// + private static int alarmInterval = 15; + public static int AlarmInterval { get => GetAlarmInterval("AlarmInterval"); private set { } } + /// + /// 是否生成报警 + /// + public static bool IsGeneAlarm { get => true; private set { } } + + public static int RDHInterval { get => -5; private set { } } + + public static int GetAlarmInterval(string key) + { + if (int.TryParse(ConfigHelper.GetSectionValue(key), out alarmInterval)) + { + return alarmInterval; + } + else + { + return alarmInterval; + } + } + public static readonly Dictionary DicTimeMapId = new Dictionary(); + + #region 补漏数据 0-缺失,99-正常 + /// + /// 正常 + /// + public static readonly short EquipData_State_Normal = 99; + /// + /// 缺失 + /// + public static readonly short EquipData_State_Abnormal = 0; + /// + /// 原始数据丢失 + /// + + public static readonly short EquipData_State_LoseOriginal = 1; + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs new file mode 100644 index 0000000..8539798 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public static class AxHelper + { + public static string RemoveHost(string fullFile) + { + if (string.IsNullOrEmpty(fullFile)) + { + return null; + } + + string keyword = "upload"; + int index = fullFile.ToLower().IndexOf(keyword); + + // 如果找到了关键字,则截取关键字及其后面的内容 + string result = index >= 0 ? fullFile.Substring(index) : fullFile; + return result; + } + + + + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs new file mode 100644 index 0000000..c473627 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + /// + /// 元数据code生成规则 + /// + public static class BaseDataCodeRule + { + /// + /// 根据类型,id以及parentid获取数据的code + /// + /// 标识类型 + /// 标识数据的id + /// 标识数据的父id + /// 生成规则的code + public static string GetBaseDataCode(string type,long? id,long? parentId) + { + string returnStr = string.Empty; + string parentCode = string.Empty; + string code = string.Empty; + if (id > 0&&!string.IsNullOrEmpty(type)) + { + if (parentId > 0) + { + parentCode = String.Format("{0:D3}", parentId); + } + code= String.Format("{0:D3}", id); + returnStr = type + parentCode + code; + } + return returnStr; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs new file mode 100644 index 0000000..068fbb6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + /// + /// 运行状态 + /// + public static class CertStatus + { + public static bool Status { get; set; } + } + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs new file mode 100644 index 0000000..eacb804 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +namespace WeiCloud.Core.Common +{ + public class ComComparer : IEqualityComparer + { + public bool Equals(T x, T y) + { + if (x == null || y == null) + { + return false; + } + //if (Newtonsoft.Json.JsonConvert.SerializeObject(x)?.Length== Newtonsoft.Json.JsonConvert.SerializeObject(y)?.Length) + //{ + // return true; + //} + var result = CompareType(x, y); + if (result == false) + { + var d = x; + var u = y; + } + return result; + } + + public int GetHashCode(T obj) + { + if (Object.ReferenceEquals(obj, null)) + { + return 0; + } + return HashCode(obj); + + } + + private int HashCode(T t) + { + if (Object.ReferenceEquals(t, null)) + { + return 0; + } + Type typeOne = t.GetType(); + PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) + var list = new List(); + for (int i = 0; i < pisOne.Length; i++) + { + string oneName = pisOne[i].Name; + object oneValue = pisOne[i].GetValue(t, null); + int hashvalue = oneName == null ? 0 : oneName.GetHashCode(); + list.Add(hashvalue); + } + return AllTypeValueHash(list); + + } + + private int AllTypeValueHash(List list) + { + var result = 0; + foreach (var item in list) + { + result = result ^ item; + } + return result; + } + + private bool CompareType(T oneT, T twoT) + { + if (oneT == null || twoT == null) + { + return false; + } + bool result = true;//两个类型作比较时使用,如果有不一样的就false + Type typeOne = oneT.GetType(); + Type typeTwo = twoT.GetType(); + //如果两个T类型不一样 就不作比较 + if (!typeOne.Equals(typeTwo)) { return false; } + PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) + PropertyInfo[] pisTwo = typeTwo.GetProperties(); + //如果长度为0返回false + if (pisOne.Length <= 0 || pisTwo.Length <= 0) + { + return false; + } + //如果长度不一样,返回false + if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; } + //遍历两个T类型,遍历属性,并作比较 + for (int i = 0; i < pisOne.Length; i++) + { + //获取属性名 + string oneName = pisOne[i].Name; + string twoName = pisTwo[i].Name; + //获取属性的值 + object oneValue = pisOne[i].GetValue(oneT, null); + object twoValue = pisTwo[i].GetValue(twoT, null); + //比较,只比较值类型 + if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String"))) + { + if (oneName.Equals(twoName)) + { + if (oneValue == null) + { + if (twoValue != null) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + else if (oneValue != null) + { + if (twoValue != null) + { + if (!oneValue.Equals(twoValue)) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + else if (twoValue == null) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + } + else + { + result = false; + break; + } + } + else + { + //如果对象中的属性是实体类对象,递归遍历比较 + bool b = CompareType(oneValue, twoValue); + if (!b) { result = b; break; } + } + } + return result; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs new file mode 100644 index 0000000..e630f68 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs @@ -0,0 +1,39 @@ +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace WeiCloud.Core +{ + public static class ConfigHelper + { + private static IConfiguration _configuration; + + static ConfigHelper() + { + //在当前目录或者根目录中寻找appsettings.json文件 + var fileName = "appsettings.json"; + + var directory = AppContext.BaseDirectory; + directory = directory.Replace("\\", "/"); + + var filePath = $"{directory}/{fileName}"; + if (!File.Exists(filePath)) + { + var length = directory.IndexOf("/bin"); + filePath = $"{directory.Substring(0, length)}/{fileName}"; + } + + var builder = new ConfigurationBuilder() + .AddJsonFile(filePath, false, false); + + _configuration = builder.Build(); + } + + public static string GetSectionValue(string key) + { + return _configuration.GetSection(key).Value; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs new file mode 100644 index 0000000..05c889e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs @@ -0,0 +1,93 @@ +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels; + +namespace WeiCloud.Core.Common +{ + //public interface CurrentContext + //{ + // CurrentUser GetContext(); + // void SetContext(CurrentUser currentUser); + //} + public class CurrentContext + { + private readonly IHttpContextAccessor httpContext; + public CurrentContext(IHttpContextAccessor httpContext) + { + this.httpContext = httpContext; + } + public CurrentUser GetContext() + { + CurrentUser result = null; + try + { + //var httpContext = ServiceLocator.ServiceProvider.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor; + //object currentUserStr = Orleans.Runtime.RequestContext.Get("CurrentUser"); + result = httpContext?.HttpContext?.Items["CurrentUser"] == null ? null : httpContext.HttpContext.Items["CurrentUser"] as CurrentUser; + //if (currentUserStr != null) + //{ + // return JsonConvert.DeserializeObject(currentUserStr.ToString()); + //} + } + catch (Exception ex) + { + + } + finally + { + if (result == null) + { + result = new CurrentUser { }; + } + } + + return result; + } + public void SetContext(CurrentUser currentUser) + { + try + { + if (currentUser != null) + { + //var httpContext = ServiceLocator.ServiceProvider.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor; + httpContext.HttpContext.Items["CurrentUser"] = currentUser; + //string currentUserStr = JsonConvert.SerializeObject(currentUser); + + //Orleans.Runtime.RequestContext.Set("CurrentUser", currentUserStr); + } + } + catch (Exception ex) + { + throw ex; + } + } + } + public class CurrentUser + { + public List ProjectIds { get; set; } + public List ConstIds { get; set; } + public string RoleCode { get; set; } + public List OwnerIds { get; set; } + public long UserId { get; set; } = 0; + public long UserGroupId { get; set; } + public string NickName { get; set; } + public long AdminId { get; set; } + public string Pwd { get; set; } + public string UserName { get; set; } + public string UserFullName { get; set; } + public string RoleName { get; set; } + public long RoleId { get; set; } + public string Token { get; set; } + public ProAndConstPression ProAndConstPression { get; set; } + public string WeChat { get; set; } + + public string RemoteIPAddress { get;set; } + + public long HeaderProjectId { get; set; } + + public string UserPhone { get; set; } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs new file mode 100644 index 0000000..706b87a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs @@ -0,0 +1,45 @@ +using MySqlX.XDevAPI.Common; +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.BasicGroup; + +namespace WeiCloud.Core.Common.DataSetGroup +{ + public static class DataSetGroupMeta + { + /// + /// 获取数据集组的标准参数代码 + /// + /// + public static List GetGroupStanderParamCodes() + { + var result = new List(); + result.Add(new GroupStanderParamCodeDto + { + Code = "ElePrice", + Name = "电价", + Unit = "元/kWh" + }); + result.Add(new GroupStanderParamCodeDto + { + Code = "WaterPrice", + Name = "水价", + Unit = "元/t" + }); + result.Add(new GroupStanderParamCodeDto + { + Code = "GasPrice", + Name = "气价", + Unit = "元/m³" + }); + result.Add(new GroupStanderParamCodeDto + { + Code = "buildArea", + Name = "建筑面积", + Unit = "㎡" + }); + return result; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs new file mode 100644 index 0000000..0dfddad --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.DataStream +{ + public class ParamConfigConst + { + + } + public enum ParamConfigTypeEnum + { + Standard = 1, + RealData = 2, + ParamGroup = 3, + BreakOff = 4 + } + public class ParamConfigOperaConst + {//1-大于、2-大于等于、3-小于、4-小于等于 + public static Dictionary Dic = new Dictionary() { { 1, ">" }, { 2, ">=" }, { 3, "<" }, { 4, "<=" } }; + } + public enum DataStreamFrequencyUnitEnum + { + Year=6, + Month=5, + Day=4, + Hour=3 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs new file mode 100644 index 0000000..4c27715 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Const +{ + public class QualityMethodTypeConst + { + //1-大小值;2-补空值;3-正态分布;4-开箱;5-平衡;6-空值率 + public static readonly string DXZXZ = "DXZXZ"; + public static string BK = "BK"; + public static string ZTFB = "ZTFB"; + public static string KX = "KX"; + public static string PH = "PH"; + public static string KZL = "KZL"; + /// + /// 限幅滤波法(又称程序判断滤波法) + /// + public static string FTW = "FTW"; + /// + /// 中位值滤波法 + /// + public static string MFM = "MFM"; + } + public enum ProblemQualityTypeTypeEnum + { + Param = 1, + ParamGroup = 2 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs new file mode 100644 index 0000000..d30efb5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class DataTableHelper where T:new() + { + + + /// + /// datatable to list + /// + /// + /// + public static List ConvertToModel(DataTable dt) + { + + List ts = new List();// 定义集合 + Type type = typeof(T); // 获得此模型的类型 + string tempName = ""; + foreach (DataRow dr in dt.Rows) + { + T t = new T(); + PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性 + foreach (PropertyInfo pi in propertys) + { + tempName = pi.Name; + + if (dt.Columns.Contains(tempName)) + { + if (!pi.CanWrite) continue; + object value = dr[tempName]; + if (value != DBNull.Value) + pi.SetValue(t, value, null); + } + } + ts.Add(t); + } + + return ts; + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs new file mode 100644 index 0000000..e11c200 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels; + +namespace WeiCloud.Core.Common +{ + public static class DateNowSession + { + #region 获取当前季节以及是否营业时间 + public static SessionAndBusiness GetSessionAndBuss(DateTime now) + { + SessionAndBusiness model = new SessionAndBusiness(); + short? session = 0; + short? bussiness = 0; + //供冷季 + var collSatar = Convert.ToDateTime(now.Year + "-" + "05-15"); + var collEnd = Convert.ToDateTime(now.Year + "-" + "09-15"); + //过渡季 + var transSatar1 = Convert.ToDateTime(now.Year + "-" + "03-15"); + var transEnd1 = Convert.ToDateTime(now.Year + "-" + "05-15"); + var transSatar2 = Convert.ToDateTime(now.Year + "-" + "09-15"); + var transEnd2 = Convert.ToDateTime(now.Year + "-" + "11-8"); + //供热季 + var hotSatar = Convert.ToDateTime(now.Year + "-" + "11-8"); + var hotEnd = Convert.ToDateTime(now.Year + "-" + "03-15"); + if (now >= collSatar && now < collEnd) + { + session = 1;//供冷季 + } + else if ((now >= transSatar1 && now < transEnd1) || (now >= transSatar2 && now < transEnd2)) + { + session = 3; //过渡季 + } + else if ((now < hotEnd) || (now >= hotSatar)) + { + session = 2;//供热季 + } + if (now.Hour >= 9 && now.Hour < 22) + { + bussiness = 1; + } + model.Session = session; + model.Business = bussiness; + return model; + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs new file mode 100644 index 0000000..9e03f01 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs @@ -0,0 +1,351 @@ +using Microsoft.Extensions.Internal; +using System; +using System.Collections.Generic; +using System.Text; +using NodaTime; + +namespace WeiCloud.Core.Common +{ + public static class DateTimeTools + { + #region 获取系统当前时间的几个方法(返回时间+格式化后的时间字符串) + + /// + /// 获取系统当前时间 + /// + /// 系统当前时间 + public static DateTime GetSysDateTimeNow() + { + Instant now = NodaTime.SystemClock.Instance.GetCurrentInstant(); + var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"]; + return now.InZone(shanghaiZone).ToDateTimeUnspecified(); + } + + /// + /// 获取系统当前时间格式化字符串 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss.fff) + /// + /// 系统当前格式化的时间字符串(yyyy-MM-dd HH:mm:ss.fff) + public static string GetSysDateTimeNowStringYMD24HMSF() + { + return GetSysDateTimeNow().ToStringYMD24HMSF(); + } + + /// + /// 获取系统当前时间格式化字符串 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss.fff) + /// + /// 系统当前格式化的时间字符串(yyyy-MM-dd hh:mm:ss.fff) + public static string GetSysDateTimeNowStringYMD12HMSF(this DateTime time) + { + return GetSysDateTimeNow().ToStringYMD12HMSF(); + } + + /// + /// 获取系统当前时间格式化字符串 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss) + /// + /// 系统当前格式化的时间字符串(yyyy-MM-dd HH:mm:ss) + public static string GetSysDateTimeNowStringYMD24HMS(this DateTime time) + { + return GetSysDateTimeNow().ToStringYMD24HMS(); + } + + /// + /// 获取系统当前时间格式化字符串 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss) + /// + /// 系统当前格式化的时间字符串(yyyy-MM-dd hh:mm:ss) + public static string GetSysDateTimeNowStringYMD12HMS(this DateTime time) + { + return GetSysDateTimeNow().ToStringYMD12HMS(); + } + + /// + /// 获取系统当前时间格式化字符串 被格式化为 (yyyy-MM-dd) + /// + /// 系统当前格式化的时间字符串(yyyy-MM-dd) + public static string GetSysDateTimeNowStringYMD(this DateTime time) + { + return GetSysDateTimeNow().ToStringYMD(); + } + + #endregion + + #region DateTime 扩展几个 格式方法 + + /// + /// 时间 格式化 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss.fff) + /// + /// 被格式的时间 + /// 格式化后的时间字符串(yyyy-MM-dd HH:mm:ss.fff) + public static string ToStringYMD24HMSF(this DateTime time) + { + try + { + return time.ToString("yyyy-MM-dd HH:mm:ss.fff"); + } + catch (Exception ex) + { + return null; + } + + } + + /// + /// 时间 格式化 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss.fff) + /// + /// 被格式化时间 + /// 格式化后的时间字符串(yyyy-MM-dd hh:mm:ss.fff) + public static string ToStringYMD12HMSF(this DateTime time) + { + return time.ToString("yyyy-MM-dd hh:mm:ss.fff"); + } + + /// + /// 时间 格式化 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss) + /// + /// 被格式化时间 + /// 格式化后的时间字符串(yyyy-MM-dd HH:mm:ss) + public static string ToStringYMD24HMS(this DateTime time) + { + return time.ToString("yyyy-MM-dd HH:mm:ss"); + } + + /// + /// 时间 格式化 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss) + /// + /// 被格式化时间 + /// 格式化后的时间字符串(yyyy-MM-dd hh:mm:ss) + public static string ToStringYMD12HMS(this DateTime time) + { + return time.ToString("yyyy-MM-dd hh:mm:ss"); + } + + /// + /// 时间 格式化 被格式化为 (yyyy-MM-dd) + /// + /// 被格式化时间 + /// 连接符号 + /// 格式化后的时间字符串(yyyy-MM-dd) + public static string ToStringYMD(this DateTime time, string separator= null) + { + if (separator != null) + { + return time.ToString($"yyyy{separator}MM{separator}dd"); + } + return time.ToString("yyyy-MM-dd"); + + } + + public static string ToStringYMD(this DateTime time) + { + + return time.ToString("yyyy-MM-dd"); + + } + #endregion + + #region 获取时间戳 + + /// + /// 获取时间戳(秒) + /// + /// 秒时间戳 + public static long GetSecondTimestamp() + { + // 以1970-1-1 为时间开始 同系统当前时间的秒差值即为秒时间戳 + TimeSpan ts = GetSysDateTimeNow() - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalSeconds); + } + + /// + /// 获取时间戳(毫秒) + /// + /// 毫秒时间戳 + public static long GetMilliSecondTimestamp() + { + // 以1970-1-1 为时间开始 同系统当前时间的毫秒差值即为毫秒时间戳 + TimeSpan ts = GetSysDateTimeNow() - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalMilliseconds); + } + + #endregion + + #region 将一个时间戳转换为一个时间 + + /// + /// 将一个秒时间戳转换为时间格式(秒) + /// + /// 秒时间戳 + /// 转换后的时间 + public static DateTime? SecondStampToDateTime(long secondTimestamp) + { + // 做一个简单的判断 + if (secondTimestamp <= 0) + { + return null; + } + + // 以1970-1-1 为时间开始,通过计算与之的时间差,来计算其对应的时间 + DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); + dateTime = dateTime.AddSeconds(secondTimestamp).ToLocalTime(); + return dateTime; + } + + /// + /// 将一个字符串秒时间戳转换为时间格式(秒) + /// + /// 字符串秒时间戳 + /// 转换后的时间 + public static DateTime? SecondStampToDateTime(string secondTimestampStr) + { + // 如果为空,那么直接返回null + if (string.IsNullOrEmpty(secondTimestampStr)) + { + return null; + } + + // 首先将字符串时间戳转换为数字 + long secondTimestamp = 0; + long.TryParse(secondTimestampStr, out secondTimestamp); + + // 调用 + return SecondStampToDateTime(secondTimestamp); + } + + /// + /// 将一个字符串毫秒时间戳转换为时间格式(毫秒) + /// + /// 字符串毫秒时间戳 + /// 转换后的时间 + public static DateTime? MilliSecondStampToDateTime(long secondTimestamp) + { + // 做一个简单的判断 + if (secondTimestamp <= 0) + { + return null; + } + + // 以1970-1-1 为时间开始,通过计算与之的时间差,来计算其对应的时间 + DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); + dateTime = dateTime.AddMilliseconds(secondTimestamp).ToLocalTime(); + + return dateTime; + } + + /// + /// 将一个毫秒时间戳转换为时间格式(毫秒) + /// + /// 毫秒时间戳 + /// 转换后的时间 + public static DateTime? MilliSecondStampToDateTime(string milliSecondStampStr) + { + // 如果为空,那么直接返回null + if (string.IsNullOrEmpty(milliSecondStampStr)) + { + return null; + } + + // 首先将字符串时间戳转换为数字 + long milliSecondStamp = 0; + long.TryParse(milliSecondStampStr, out milliSecondStamp); + + // 调用 + return MilliSecondStampToDateTime(milliSecondStamp); + } + + #endregion + + /// + /// 获得当前某年的某一天 + /// + /// + /// + public static int GetYearDay( DateTime dateTime ) + { + return dateTime.DayOfYear; + } + /// + /// 获得一年多少天 + /// + /// + public static int GetYearDayCount(int year) + { + int count = 0; + try + { + for (int i = 1; i <= 12; i++) + { + count += DateTime.DaysInMonth(year, i); + } + return count; + } + catch (Exception ex) + { + return 365; + } + } + /// + /// 获得今年的第一天 + /// + /// + public static DateTime GetYearFirstDay() + { + DateTime dtFirstDay = new DateTime(GetSysDateTimeNow().Year, 1, 1); + return dtFirstDay; + } + /// + /// 获得今年的最后一天 + /// + /// + public static DateTime GetYearLastDay() + { + DateTime dtLastDay = new DateTime(GetSysDateTimeNow().Year, 1, 1).AddYears(1).AddDays(-1); + return dtLastDay; + } + /// + /// 将时间格式处理成 --- yyyy-MM-dd hh:00:00 + /// + /// + /// + public static DateTime? GetDateTimeCutHour(this DateTime? datetime) + { + if (datetime ==null) + { + return null; + } + return new DateTime(datetime.Value.Year,datetime.Value.Month,datetime.Value.Day,datetime.Value.Hour,0,0); + } + + + /// + /// 获取当前日期所属的季度、季度内的月份以及该月内的第几天。 + /// + /// 要判断的日期 + /// 包含季度、季度内的月份和该月内的天数的元组 + public static (int Quarter, int MonthInQuarter, int DayInMonth) GetQuarterInfo(DateTime date) + { + // 确定季度 + int quarter = (date.Month - 1) / 3 + 1; + + // 确定季度内的月份 + int monthInQuarter = (date.Month - 1) % 3 + 1; + + // 获取该月的天 + int dayInMonth = date.Day; + + return (quarter, monthInQuarter, dayInMonth); + } + + + + + // 指定周起始日的版本 + public static (DateTime Start, DateTime End) GetCurrentWeekRange(DayOfWeek startOfWeek) + { + DateTime today = DateTime.Today; + int diff = (7 + (today.DayOfWeek - startOfWeek)) % 7; + DateTime start = today.AddDays(-diff); + DateTime end = start.AddDays(6); + + return (start, end); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs new file mode 100644 index 0000000..eb9a37d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace WeiCloud.Core.Common +{ + + public class DatetimeJsonConverter : JsonConverter + { + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + if (DateTime.TryParse(reader.GetString(), out DateTime date)) + return date; + } + return reader.GetDateTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs new file mode 100644 index 0000000..1d2b92c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.EnergyConsumPlan +{ + public class EnergyConsumPlanConst + { + } + public enum EnergyConsumPlanTypeEnum + { + Custom = 0, + Year = 1, + Month = 2, + Day = 3, + Hour = 4 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs new file mode 100644 index 0000000..b8eb390 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class EnthalpyBase + { + /// + /// 获取温湿度焓值计算公式 + /// + /// 温度 + /// 湿度 + /// 返回的焓值结果 + /// 比较值 当大于值返回flalse 小于值返回true + /// + public static double GetTemHumiEnthalpy(double temperature, double humidity) + { + //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 + //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) + + //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; + double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; + //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) + double b = humidity / 100 * a * 100; + double c = 101300 - humidity / 100 * a * 100; + //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) + var enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); + return enthalpy; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs new file mode 100644 index 0000000..5807a0d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.EquipGroup +{ + public class EquipGroupConst + { + } + /// + /// 分组能耗类型 + /// + public enum EquipGroupItemTypeEnum + { + Other = 0, + Ele = 1, + Water = 2, + Gas = 3, + Heat = 4 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs new file mode 100644 index 0000000..40f2b7e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.EquipPart +{ + public class EquipPartConst + { + } + public enum EquipPartApplyEnum + { + In = 1, + Out = 2, + /// + /// 外借 + /// + LentOut = 3 + } + public enum EquipPartApproveState + {//流程状态 已发起 1 已审批 7 已完成 5 已拒绝 8 + Applied = 1, + Approved = 7, + Completed = 5, + Refuse = 8 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs new file mode 100644 index 0000000..3d076a2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public static class ExceptionHelp + { + public static int GetLineNumber(this Exception ex) + { + var line = 0; + try + { + var stackTrace = new StackTrace(ex, true); + var stackFrame = stackTrace.GetFrame(0); + line = stackFrame.GetFileLineNumber(); + } + catch (Exception innerex) + { + line = 0; + } + return line; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs new file mode 100644 index 0000000..472ab4a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs @@ -0,0 +1,677 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Linq; +using System.Text.RegularExpressions; +using System.Reflection; +using Org.BouncyCastle.Crypto.Agreement.Srp; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.Report; +using WeiCloud.Entity.LogicModels.HKPro; + +namespace WeiCloud.Core +{ + public static class ExpandClass + { + public static string ListToStr(this IEnumerable list, string separate = ",") + { + return string.Join(separate, list); + } + public static List StrArrayToLongArray(this string[] strList) + { + List list = new List(); + try + { + long n = 0; + foreach (var str in strList) + { + if (long.TryParse(str, out n)) + list.Add(n); + } + } + catch (Exception ex) + { + + } + return list; + } + public static List StrArrayToIntArray(this string[] strList) + { + List list = new List(); + try + { + int n = 0; + foreach (var str in strList) + { + if (int.TryParse(str, out n)) + list.Add(n); + } + } + catch (Exception ex) + { + + } + return list; + } + public static List StringToIntArray(this string strList, char splitchar) + { + List list = new List(); + try + { + var outresult = -1; + if (string.IsNullOrEmpty(strList)) + { + return new List { }; + } + var strArray = strList.Split(splitchar); + foreach (var str in strArray) + { + if (int.TryParse(str, out outresult)) + list.Add(outresult); + } + + + } + catch (Exception ex) + { + } + return list; + } + /// + /// 将字符串转为List int + /// + /// + /// + /// + public static List StringToIntList(this string str, char splitchar) + { + List list = new List(); + try + { + var outresult = -1; + if (String.IsNullOrEmpty(str)) + { + return null; + } + if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) + { + list.Add(outresult); + return list; + + } + var a = str.Split(splitchar); + for (int i = 0; i < a.Length; i++) + { + var result = -1; + int.TryParse(a[i], out result); + list.Add(result); + } + + return list; + } + catch (Exception ex) + { + return null; + } + + } + + public static List StringToStrList(this string str, char splitchar) + { + List list = new List(); + try + { + var outresult = -1; + if (String.IsNullOrEmpty(str)) + { + return null; + } + if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) + { + list.Add(outresult); + return list; + + } + var a = str.Split(splitchar); + for (int i = 0; i < a.Length; i++) + { + var result = -1; + int.TryParse(a[i], out result); + list.Add(result); + } + + return list; + } + catch (Exception ex) + { + return null; + } + + } + + + public static List StringToIntList1(this string str, char splitchar) + { + List list = new List(); + try + { + var outresult = -1; + if (String.IsNullOrEmpty(str)) + { + return null; + } + if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) + { + list.Add(outresult); + return list; + + } + var a = str.Split(splitchar); + for (int i = 0; i < a.Length; i++) + { + var result = -99; + if (int.TryParse(a[i], out result)) + { + list.Add(result); + } + + + } + + return list; + } + catch (Exception ex) + { + } + return list; + } + + + public static List StringToLongList(this string str, char splitchar) + { + List list = new List(); + try + { + long outresult = -1; + if (String.IsNullOrEmpty(str)) + { + return null; + } + if (!str.Contains(splitchar.ToString()) && long.TryParse(str, out outresult)) + { + list.Add(outresult); + return list; + + } + var a = str.Split(splitchar); + for (int i = 0; i < a.Length; i++) + { + long result = -1; + long.TryParse(a[i], out result); + list.Add(result); + } + + return list; + } + catch (Exception ex) + { + return null; + } + + } + public static List StringToLongList1(this string str, char splitchar) + { + List list = new List(); + try + { + long outresult = -1; + if (String.IsNullOrEmpty(str)) + { + return list; + } + if (!str.Contains(splitchar.ToString()) && long.TryParse(str, out outresult)) + { + list.Add(outresult); + return list; + + } + var a = str.Split(splitchar); + for (int i = 0; i < a.Length; i++) + { + long result = -1; + long.TryParse(a[i], out result); + list.Add(result); + } + + return list; + } + catch (Exception ex) + { + return null; + } + + } + public static string[] LongToStringList(this long[] str) + { + var results = new List { }; + for (var i = 0; i < str.Length; i++) + { + results[i] = str[i].ToString(); + } + return results.ToArray(); + } + public static string[] IntToStringList(this int[] str) + { + var results = new List { }; + for (var i = 0; i < str.Length; i++) + { + results[i] = str[i].ToString(); + } + return results.ToArray(); + } + /// + /// 将字符串转为string[] + /// + /// + /// + /// string[] + public static string[] StringToStringArray(this string str, char splitchar) + { + if (String.IsNullOrEmpty(str)) + { + return null; + } + if (!str.Contains(splitchar.ToString())) + { + return new string[] { str }; + } + return str.Split(splitchar); + } + public static List StringToStringList(this string str, char splitchar) + { + var result = new List { }; + if (String.IsNullOrEmpty(str)) + { + return result; + } + if (!str.Contains(splitchar.ToString())) + { + result.Add(str); + return result; + } + return str.Split(splitchar).ToList(); + } + /// + /// 判断两个字节数组是否相等 + /// + /// + /// + /// bool + public static bool BytesEquals(this byte[] b1, byte[] b2) + { + if (b1 == null || b2 == null) return false; + if (b1.Length != b2.Length) return false; + for (int i = 0; i < b1.Length; i++) + if (b1[i] != b2[i]) + return false; + return true; + } + + public static string ToLowerOnlyStart(this string str) + { + try + { + if (!string.IsNullOrEmpty(str)) + { + if (str.Length > 1) + { + return char.ToLower(str[0]) + str.Substring(1); + } + return char.ToLower(str[0]).ToString(); + } + return str; + } + catch (Exception ex) + { + return str; + } + } + +#if NETCOREAPP3_1 + public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector) + { + HashSet seenKeys = new HashSet(); + foreach (TSource element in source) + { + if (seenKeys.Add(keySelector(element))) + { + yield return element; + } + } + } +#endif + + public static double DoubleTakeRound(this double bl, int round = 0) + { + if (bl.ToString().Contains(".")) + { + return Math.Round(bl, round); + } + else + { + return bl; + } + } + + public static double? TakeRoundN(this double? b1, int round = 0) + { + if (b1 == null) + { + return null; + } + if (b1.Value.ToString().Contains(".")) + { + return Math.Round(b1.Value, round); + } + else + { + return b1; + } + } + + public static bool IsIpAddress(this string strIn) + { + try + { + if (String.IsNullOrEmpty(strIn)) + { + return false; + } + bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$"); + return b; + } + catch (Exception ex) + { + return false; + } + } + + public static bool IsIP(this string strIn) + { + try + { + if (String.IsNullOrEmpty(strIn)) + { + return false; + } + bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"); + return b; + } + catch (Exception ex) + { + return false; + } + } + + public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime) + { + return dateTime.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime + ? DateTimeOffset.MinValue + : new DateTimeOffset(dateTime); + } + /// + /// 截取一个字段中的ip:端口,失败的话返回空字符串 + /// + /// + /// + public static string ExtractIPAddressFStr(this string strIn) + { + try + { + if (string.IsNullOrEmpty(strIn)) + { + return string.Empty; + } + //@"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}" + //@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$" + Match m = Regex.Match(strIn, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:[0-9]{1,6}");// + if (m.Success) + { + return m.Value; + } + else + { + return string.Empty; + } + } + catch (Exception ex) + { + return string.Empty; + } + } + + public static bool IsIPAddress(string strIn) + { + bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$"); + return b; + } + + + public static bool CompareType(this T oneT, T twoT) + { + bool result = true;//两个类型作比较时使用,如果有不一样的就false + Type typeOne = oneT.GetType(); + Type typeTwo = twoT.GetType(); + //如果两个T类型不一样 就不作比较 + if (!typeOne.Equals(typeTwo)) { return false; } + PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) + PropertyInfo[] pisTwo = typeTwo.GetProperties(); + //如果长度为0返回false + if (pisOne.Length <= 0 || pisTwo.Length <= 0) + { + return false; + } + //如果长度不一样,返回false + if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; } + //遍历两个T类型,遍历属性,并作比较 + for (int i = 0; i < pisOne.Length; i++) + { + //获取属性名 + string oneName = pisOne[i].Name; + string twoName = pisTwo[i].Name; + //获取属性的值 + object oneValue = pisOne[i].GetValue(oneT, null); + object twoValue = pisTwo[i].GetValue(twoT, null); + //比较,只比较值类型 + if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String"))) + { + if (oneName.Equals(twoName)) + { + if (oneValue == null) + { + if (twoValue != null) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + else if (oneValue != null) + { + if (twoValue != null) + { + if (!oneValue.Equals(twoValue)) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + else if (twoValue == null) + { + result = false; + break; //如果有不一样的就退出循环 + } + } + } + else + { + result = false; + break; + } + } + else + { + //如果对象中的属性是实体类对象,递归遍历比较 + bool b = CompareType(oneValue, twoValue); + if (!b) { result = b; break; } + } + } + return result; + } + /// + /// 对表达式进行格式化处理 + /// + /// + /// + public static string FormatExpress(this string ori) + { + var result = ori; + try + { + var upStr = ori.ToUpper().Replace(" ", ""); + //var strs = upStr.Split(seps); + //result= string.Join(" ", strs); + result = upStr.Replace("AND", " AND ").Replace("OR", " OR "); + + } + catch (Exception ex) + { + result = ori; + } + return result; + } + + public static double NumberKeepTwo(this double? dou, int keep = 2) + { + var data = Math.Round(dou.GetValueOrDefault(), keep); + return data; + } + + public static float NumberKeepTwo(this float? flo, int keep = 2) + { + var dv = Math.Round(flo.GetValueOrDefault(), 2); + return (float)dv; + } + + public static float NumberKeepTwo(this float flo, int keep = 2) + { + var dv = Math.Round(flo, 2); + return (float)dv; + } + + public static double NumberKeepTwo(this double dou, int keep = 2) + { + return Math.Round(dou, keep); + } + + public static decimal NumberKeepTwo(this decimal? dou, int keep = 2) + { + return Math.Round(dou.GetValueOrDefault(), keep); + } + + public static decimal NumberToTenThousand(this decimal dou, int keep = 2) + { + const decimal divisor = 10000.0M; + if (divisor == 0) + { + throw new DivideByZeroException("Divisor cannot be zero."); + } + decimal result = dou / divisor; + + // 使用 Math.Round 保留两位小数,MidpointRounding.AwayFromZero 可以避免银行家舍入 + return Math.Round(result, keep, MidpointRounding.AwayFromZero); + } + + public static decimal NumberKeepTwo(this decimal dou, int keep = 2) + { + return Math.Round(dou, keep); + } + + public static double StrDoubuleKeepTwo(this string strdou, int keep = 2) + { + double outdouble = 0; + try + { + if (double.TryParse(strdou, out outdouble)) + { + return Math.Round(outdouble, keep); + } + else + { + return outdouble; + } + + } + catch (Exception ex) + { + return outdouble; + } + } + + /// + /// 获取list中指定索引的数据 当索引超出范围时返回null + /// + /// + /// + /// + /// + public static T SafeGet(this IList list, int index) where T : class + { + if (index >= 0 && index < list.Count) + { + return list[index]; + } + else + { + return null; + } + } + + public static Decimal StrToDecimal(this string str) + { + decimal outd = 0; + decimal.TryParse(str, out outd); + return Math.Round(outd, 2); + } + + public static long StrToLong(this string str) + { + long outd = 0; + long.TryParse(str, out outd); + return outd; + } + + public static DateTime StrToSafeDateTime(this string dateString) + { + DateTime dateValue; + + bool success = DateTime.TryParse(dateString, out dateValue); + if (success) + { + return dateValue; + } + else + { + return DateTime.MinValue; + } + } + + public static IEnumerable FlattenHierarchy(this BuildingNodeDto node) + { + yield return node; + foreach (var child in node.Children.SelectMany(c => c.FlattenHierarchy())) + { + yield return child; + } + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs new file mode 100644 index 0000000..771100e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.CylmPro; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Common +{ + public class FanCmdContextVo + { + public FanCmdBo FanCmdBo { get; set; } + + public int TryTime { get; set; } + + public ContextModel ContextModel { get; set; } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs new file mode 100644 index 0000000..27a7304 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.BulletinBoard; + +namespace WeiCloud.Core.Common +{ + public class HealthLevel + { + public static HealthModel GetHealthLevel(double value, int type) + { + HealthModel en = new HealthModel(); + string str = string.Empty; + string goodName = "极佳"; + string comfortName = "舒适"; + string badName = "一般"; + var date = DateTime.Now; + var time1 = Convert.ToDateTime(date.Year + "-11-01"); + var time2 = Convert.ToDateTime(date.Year + "-05-01"); + var temp1 = 24; + var temp2 = 26; + var temp3 = 21; + var temp4 = 28; + var wet1 = 40; + var wet2 = 60; + var wet3 = 31; + var wet4 = 70; + var co21 = 500; + var co22 = 750; + //var co23 = 2000; + var jiaquan1 = 60; + var jiaquan2 = 80; + //var jiaquan3 = 2000; + var pm1 = 30; + var pm2 = 50; + var TVOCGoodLevelMinValue = 0; + var TVOCGoodLevelMaxValue = 400; + var TVOCComfortLevelMinValue = 401; + var TVOCComfortLevelMaxValue = 600; + //var pm3 = 500; + if (date < time2 || date >= time1)//供暖季 + { + temp1 = 20; + temp2 = 24; + temp3 = 18; + wet1 = 30; + wet3 = 11; + } + + if (type == 1)//温度 + { + if (value >= temp1 && value <= temp2) + { + str = goodName; + en.Pecent = 100; + en.Level = goodName; + } + else if ((value >= temp3 && value < temp1) || (value >= temp2 && value <= temp4)) + { + str = comfortName; + en.Pecent = 80; + + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + } + else if (type == 2)//湿度 + { + if (value >= wet1 && value <= wet2) + { + en.Pecent = 100; + en.Level = goodName; + } + else if ((value >= wet3 && value < wet1) || (value >= wet2 && value <= wet4)) + { + en.Pecent = 80; + + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + } + else if (type == 3)//co2 + { + if (value >= 0 && value < co21) + { + en.Pecent = 100; + en.Level = goodName; + } + else if ((value >= co21 && value <= co22)) + { + en.Pecent = 80; + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + } + else if (type == 5)//甲醛 + { + if (value >= 0 && value < jiaquan1) + { + en.Pecent = 100; + en.Level = goodName; + } + else if ((value >= jiaquan1 && value <= jiaquan2)) + { + en.Pecent = 70; + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + + } + else if (type == 4)//PM + { + if (value >= 0 && value < pm1) + { + en.Pecent = 100; + en.Level = goodName; + } + else if ((value >= pm1 && value < pm2)) + { + en.Pecent = 70; + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + } + else if (type == 6)//TVOC + { + if (value >= TVOCGoodLevelMinValue && value <= TVOCGoodLevelMaxValue) + { + en.Pecent = 100; + en.Level = goodName; + } + else if (value >= TVOCComfortLevelMinValue && value <= TVOCComfortLevelMaxValue) + { + en.Pecent = 70; + en.Level = comfortName; + } + else + { + en.Pecent = 20; + en.Level = badName; + } + } + return en; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs new file mode 100644 index 0000000..64aa980 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Common +{ + public class HolidayUtil + { + /// 判断是不是周末/节假日 + /// + /// 日期 + /// 周末和节假日返回true,工作日返回false + public static async Task IsHolidayByDate(DateTime date) + { + var isHoliday = false; + //var webClient = new System.Net.WebClient(); + //var PostVars = new System.Collections.Specialized.NameValueCollection + //{ + // { "d", date.ToString("yyyyMMdd") }//参数 + //}; + try + { + var day = date.DayOfWeek; + + //判断是否为周末 + if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday) + return true; + + //0为工作日,1为周末,2为法定节假日 + //var byteResult = await webClient.UploadValuesTaskAsync("http://tool.bitefu.net/jiari/", "POST", PostVars);//请求地址,传参方式,参数集合 + //var result = Encoding.UTF8.GetString(byteResult);//获取返回值 + //if (result == "1" || result == "2") + // isHoliday = true; + } + catch + { + isHoliday = false; + } + return isHoliday; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs new file mode 100644 index 0000000..99eabf0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs @@ -0,0 +1,162 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Common +{ + public class HttpClientHelper + { + public static int clientTimeOut { get; set; } = 2000; + + public string Url { get; private set; } + public string Payload { get; private set; } + public string AuthorizationScheme { get; private set; } + public string AuthorizationParameter { get; private set; } + public string Type { get; private set; } + + + private readonly ILogger _logger; + public HttpClientHelper(ILogger logger) + { + _logger = logger; + Type = GetSetting("WexflowApi:type", "application/json"); + } + + private string GetSetting(string v1, string v2) + { + try + { + var type = ConfigHelper.GetSectionValue("WexflowApi:type"); + if (string.IsNullOrEmpty(type)) + { + return v2; + } + return type; + } + catch (Exception) + { + return v2; + } + + } + + public static async Task GetRunAsync(string baseUrl, string actionName) + { + using (var client = new HttpClient()) + { + client.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); + client.BaseAddress = new Uri(baseUrl); + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // HTTP GET + var response = await client.GetAsync(actionName); + if (response.IsSuccessStatusCode) + { + var result = await response.Content.ReadAsStringAsync(); + return result; + } + else + { + return string.Empty; + } + + } + } + + public async System.Threading.Tasks.Task Post(string url, string authScheme, string authParam, string payload) + { + using (var httpContent = new StringContent(payload, Encoding.UTF8, Type)) + using (var httpClient = new HttpClient()) + { + httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); + if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) + { + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); + } + + var httpResponse = await httpClient.PostAsync(url, httpContent); + if (httpResponse.Content != null) + { + var responseContent = await httpResponse.Content.ReadAsStringAsync(); + return responseContent; + } + } + return string.Empty; + } + + public async System.Threading.Tasks.Task Delete(string url, string authScheme, string authParam) + { + using (var httpClient = new HttpClient()) + { + httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); + if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) + { + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); + } + + var httpResponse = await httpClient.DeleteAsync(url); + if (httpResponse.Content != null) + { + var responseContent = await httpResponse.Content.ReadAsStringAsync(); + return responseContent; + } + } + return string.Empty; + } + + public async System.Threading.Tasks.Task Put(string url, string authScheme, string authParam, string payload) + { + using (var httpContent = new StringContent(payload, Encoding.UTF8, Type)) + using (var httpClient = new HttpClient()) + { + httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); + if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) + { + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); + } + + var httpResponse = await httpClient.PutAsync(url, httpContent); + if (httpResponse.Content != null) + { + var responseContent = await httpResponse.Content.ReadAsStringAsync(); + return responseContent; + } + } + return string.Empty; + } + + public async System.Threading.Tasks.Task Get(string url, string authScheme, string authParam) + { + try + { + //_logger.LogError(new NlogMessageHelper("yafo1", url).GetNlogMessage()); + using (var httpClient = new HttpClient()) + { + httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); + if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) + { + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); + } + + var httpResponse = await httpClient.GetAsync(url); + if (httpResponse.Content != null) + { + var responseContent = await httpResponse.Content.ReadAsStringAsync(); + return responseContent; + } + } + return string.Empty; + } + catch (Exception) + { + return string.Empty; + } + + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs new file mode 100644 index 0000000..93b7e4d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.WEIHttpContext +{ + public static class StaticHttpContextExtensions + { + + public static void AddHttpContextAccessor(this IServiceCollection services) + { + services.AddSingleton(); + } + + + public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app) + { + var httpContextAccessor = app.ApplicationServices.GetRequiredService(); + WEIHttpContext.Configure(httpContextAccessor); + return app; + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs new file mode 100644 index 0000000..e887fe1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common.WEIHttpContext +{ + public static class WEIHttpContext + { + private static IHttpContextAccessor _httpContextAccessor; + + public static Microsoft.AspNetCore.Http.HttpContext Current => _httpContextAccessor.HttpContext; + + internal static void Configure(IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs new file mode 100644 index 0000000..418f0ac --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core +{ + public class HttpContextHelper + { + + public async Task GetContextInfo(HttpContext httpContext) + { + if (httpContext == null) + { + return await Task.FromResult(new ContextModel()); + } + long userId = 0; + string userName = "系统"; + string actionName = httpContext.Request.Path; + if (httpContext.User.Claims != null) + { + foreach (var item in httpContext.User.Claims) + { + if (item.Type == "sub") + { + userId = long.Parse(item.Value); + } + if (item.Type == "name") + { + userName = item.Value; + } + } + } + string machineIp = httpContext.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + httpContext.Connection.RemotePort; + ContextModel contextModel = new ContextModel() + { + userId = userId, + userName = userName, + actionName = actionName, + machineIp = machineIp + }; + return await Task.FromResult(contextModel); + } + } + + + + public class BackGroudContextModel + { + public static ContextModel GetBackGroudContextModel() + { + return new ContextModel() + { + userId = 1, + userName = "admin", + actionName = "BackGroud", + machineIp = "127.0.0.1" + }; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs new file mode 100644 index 0000000..36075b3 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs @@ -0,0 +1,875 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core +{ + public class HttpHelper + { + public bool Debug { get; set; } + public CookieCollection Cookies + { + get { return _cookies; } + } + + public void ClearCookies() + { + _cookies = new CookieCollection(); + } + + CookieCollection _cookies = new CookieCollection(); + + private static readonly string DefaultUserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; + /// + /// 创建GET方式的HTTP请求 + /// + /// 请求的URL + /// 请求的超时时间 + /// 请求的客户端浏览器信息,可以为空 + /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 + /// + /// + /// + public HttpWebResponse CreateGetHttpResponse(string url, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Get Url:{0} ", url); + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + + HttpWebRequest request; + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + request = WebRequest.Create(url) as HttpWebRequest; + request.ProtocolVersion = HttpVersion.Version11; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + + request.Method = "GET"; + request.Headers["Pragma"] = "no-cache"; + request.Accept = "text/html, application/xhtml+xml, */*"; + request.Headers["Accept-Language"] = "en-US,en;q=0.5"; + request.ContentType = "application/x-www-form-urlencoded"; + request.UserAgent = DefaultUserAgent; + request.Referer = Referer; + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + var v = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + return v; + } + + /// + /// 创建POST方式的HTTP请求 + /// + /// 请求的URL + /// 随同请求POST的参数名称及参数值字典 + /// 请求的超时时间 + /// 请求的客户端浏览器信息,可以为空 + /// 发送HTTP请求时所用的编码 + /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 + /// + public HttpWebResponse CreatePostHttpResponse(string url, IDictionary parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Post Url:{0} ", url); + + foreach (KeyValuePair keyValuePair in parameters) + { + Console.Write(",{0}:{1}", keyValuePair.Key, keyValuePair.Value); + } + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + if (requestEncoding == null) + { + throw new ArgumentNullException("requestEncoding"); + } + HttpWebRequest request = null; + //如果是发送HTTPS请求 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + request = WebRequest.Create(url) as HttpWebRequest; + request.ProtocolVersion = HttpVersion.Version10; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + request.Method = "POST"; + request.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; + request.Referer = Referer; + request.Headers["Accept-Language"] = "en-US,en;q=0.5"; + request.UserAgent = DefaultUserAgent; + request.ContentType = "application/x-www-form-urlencoded"; + request.Headers["Pragma"] = "no-cache"; + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + else + { + request.UserAgent = DefaultUserAgent; + } + + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + + request.Expect = string.Empty; + + //如果需要POST数据 + if (!(parameters == null || parameters.Count == 0)) + { + var buffer = CraeteParameter(parameters); + byte[] data = requestEncoding.GetBytes(buffer.ToString()); + using (Stream stream = request.GetRequestStream()) + { + stream.Write(data, 0, data.Length); + } + } + var v = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + return v; + } + + /// + /// 创建POST方式的HTTP请求 + /// + /// 请求的URL + /// 随同请求POST的参数名称及参数值字典 + /// 请求的超时时间 + /// 请求的客户端浏览器信息,可以为空 + /// 发送HTTP请求时所用的编码 + /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 + /// + public HttpWebResponse CreatePostHttpResponse(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); + + + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + if (requestEncoding == null) + { + throw new ArgumentNullException("requestEncoding"); + } + HttpWebRequest request = null; + //如果是发送HTTPS请求 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + request = WebRequest.Create(url) as HttpWebRequest; + request.ProtocolVersion = HttpVersion.Version10; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + + request.Method = "POST"; + request.Headers.Add("Accept-Language", "zh-CN,en-GB;q=0.5"); + request.Accept = "text/html, application/xhtml+xml, */*"; + request.Referer = Referer; + request.Headers["Accept-Language"] = "en-US,en;q=0.5"; + request.UserAgent = DefaultUserAgent; + //request.ContentType = "application/x-www-form-urlencoded"; + request.ContentType = "multipart/form-data"; + + request.Headers["Pragma"] = "no-cache"; + + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + else + { + request.UserAgent = DefaultUserAgent; + } + + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + + request.Expect = string.Empty; + + //如果需要POST数据 + if (!string.IsNullOrEmpty(parameters)) + { + byte[] data = requestEncoding.GetBytes(parameters); + using (Stream stream = request.GetRequestStream()) + { + stream.Write(data, 0, data.Length); + } + } + + var v = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + + return v; + } + + + + /// + /// 创建post请求,获取token + /// + /// 请求的URL + /// 随同请求POST的参数名称及参数值字典 + /// 请求的超时时间 + /// 请求的客户端浏览器信息,可以为空 + /// 发送HTTP请求时所用的编码 + /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 + /// + public HttpWebResponse CreatePostHttpResponseJson(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + if (requestEncoding == null) + { + throw new ArgumentNullException("requestEncoding"); + } + HttpWebRequest request = null; + //如果是发送HTTPS请求 设置安全协议 不同的.NET framework安全协议版本不一样 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => + { + return true; //总是接受 + }); + ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; + request = WebRequest.Create(url) as HttpWebRequest; + } + + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + + + request.Method = "POST"; + request.ContentType = "application/json"; + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + else + { + request.UserAgent = DefaultUserAgent; + } + + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + + request.Expect = string.Empty; + + //如果需要POST数据 + + try + { + if (!string.IsNullOrEmpty(parameters)) + { + byte[] data = requestEncoding.GetBytes(parameters); + using (Stream stream = request.GetRequestStream()) + { + stream.Write(data, 0, data.Length); + } + } + var v = request.GetResponse() as HttpWebResponse; + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + + return v; + } + catch(Exception ex) + { + return null; + } + + + + + } + + /// + /// 华为云检测 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public HttpWebResponse CreatePostHttpResponseHW(string token,string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + if (requestEncoding == null) + { + throw new ArgumentNullException("requestEncoding"); + } + HttpWebRequest request = null; + //如果是发送HTTPS请求 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => + { + return true; //总是接受 + }); + ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; + request = WebRequest.Create(url) as HttpWebRequest; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + + request.Method = "POST"; + request.Headers.Add("X-Auth-Token", token); + + request.ContentType = "application/json"; + //request.AuthenticationLevel: + + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + else + { + request.UserAgent = DefaultUserAgent; + } + + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + + request.Expect = string.Empty; + + //如果需要POST数据 + if (!string.IsNullOrEmpty(parameters)) + { + byte[] data = requestEncoding.GetBytes(parameters); + request.ContentLength = data.Length; + using (Stream stream = request.GetRequestStream()) + { + stream.Write(data, 0, data.Length); + } + } + + var v = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + + return v; + + } + + /// + /// 创建POST方式的HTTP请求 + /// + /// 请求的URL + /// 随同请求POST的参数名称及参数值字典 + /// 请求的超时时间 + /// 请求的客户端浏览器信息,可以为空 + /// 发送HTTP请求时所用的编码 + /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 + /// + public HttpWebResponse CreatePostFileHttpResponse(string url, string filePath, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + if (Debug) + { + Console.Write("Start Post Url:{0} ", url); + + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + + HttpWebRequest request = null; + //如果是发送HTTPS请求 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + request = WebRequest.Create(url) as HttpWebRequest; + request.ProtocolVersion = HttpVersion.Version10; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + request.Method = "POST"; + request.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; + request.Referer = Referer; + request.Headers["Accept-Language"] = "en-US,en;q=0.5"; + request.UserAgent = DefaultUserAgent; + request.ContentType = "application/x-www-form-urlencoded"; + request.Headers["Pragma"] = "no-cache"; + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + else + { + request.UserAgent = DefaultUserAgent; + } + + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + + request.Expect = string.Empty; + + //如果需要POST数据 + if (!string.IsNullOrEmpty(filePath)) + { + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + { + BinaryReader r = new BinaryReader(fs); + + //时间戳 + string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); + byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); + + //请求头部信息 + StringBuilder sb = new StringBuilder(); + sb.Append("--"); + sb.Append(strBoundary); + sb.Append("\r\n"); + sb.Append("Content-Disposition: form-data; name=\"media\""); + sb.Append("file"); + sb.Append("\"; filename=\""); + sb.Append(fs.Name); + sb.Append("\""); + sb.Append("\r\n"); + sb.Append("Content-Type: "); + sb.Append("application/octet-stream"); + sb.Append("\r\n"); + sb.Append("\r\n"); + string strPostHeader = sb.ToString(); + byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); + + + request.ContentType = "multipart/form-data; boundary=" + strBoundary; + long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length; + + request.ContentLength = length; + + //开始上传时间 + DateTime startTime = DateTime.Now; + + byte[] filecontent = new byte[fs.Length]; + + fs.Read(filecontent, 0, filecontent.Length); + + using (Stream stream = request.GetRequestStream()) + { + + //发送请求头部消息 + stream.Write(postHeaderBytes, 0, postHeaderBytes.Length); + + stream.Write(filecontent, 0, filecontent.Length); + + //添加尾部的时间戳 + stream.Write(boundaryBytes, 0, boundaryBytes.Length); + } + + } + } + var v = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + + Cookies.Add(v.Cookies); + + if (Debug) + { + Console.WriteLine("OK"); + } + + return v; + } + + + public static string CraeteParameter(IDictionary parameters) + { + StringBuilder buffer = new StringBuilder(); + foreach (string key in parameters.Keys) + { + buffer.AppendFormat("&{0}={1}", key, parameters[key]); + } + return buffer.ToString().TrimStart('&'); + } + + private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) + { + return true; //总是接受 + } + + + + public string Post(string url, IDictionary parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + HttpWebResponse response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, Referer, headers); + + try + { + using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) + { + return reader.ReadToEnd(); + } + } + catch (Exception) + { + return null; + } + finally + { + response.Close(); + } + } + + + + public string Post(string url, string parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + HttpWebResponse response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, Referer, headers); + + try + { + using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) + { + return reader.ReadToEnd(); + } + } + catch (Exception) + { + return null; + } + finally + { + response.Close(); + } + } + + public string PostFile(string url, string filePath, Encoding responseEncoding, + int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", + Dictionary headers = null) + { + HttpWebResponse response = CreatePostFileHttpResponse(url, filePath, timeout, userAgent, cookies, Referer, + headers); + + try + { + using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) + { + return reader.ReadToEnd(); + } + } + catch (Exception) + { + return null; + } + finally + { + response.Close(); + } + } + + public string Get(string url, Encoding responseEncoding, Dictionary headers = null, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "") + { + HttpWebResponse response = CreateGetHttpResponse(url, timeout, userAgent, cookies, Referer, headers); + + try + { + using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) + { + return reader.ReadToEnd(); + } + } + catch (Exception) + { + return null; + } + finally + { + response.Close(); + } + } + + public byte[] GetFile(string url, out Dictionary header, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) + { + HttpWebResponse response = CreateGetHttpResponse(url, timeout, userAgent, cookies, Referer, headers); + + header = new Dictionary(); + + foreach (string key in response.Headers.AllKeys) + { + header.Add(key, response.Headers[key]); + } + + try + { + System.IO.Stream st = response.GetResponseStream(); + + byte[] by = new byte[response.ContentLength]; + + st.Read(by, 0, by.Length); + + st.Close(); + + return by; + } + catch (Exception) + { + return null; + } + + } + + string _AddressIP = String.Empty; + public string GetComputerIP() + { + try + { + foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) + { + if (_IPAddress.AddressFamily.ToString() == "InterNetwork") + { + _AddressIP = _IPAddress.ToString(); + } + } + } + catch (Exception ex) + { + + throw; + } + + return _AddressIP; + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs new file mode 100644 index 0000000..849f9d5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class HttpUtils + { + private static readonly string DefaultUserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; + private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) + { + return true; //总是接受 + } + + public static string Get(string url, Encoding responseEncoding, Dictionary headers = null, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "") + { + HttpWebResponse response = null; + HttpWebRequest request = null; + try + { + CookieCollection Cookies = new CookieCollection(); + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentNullException("url"); + } + + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + request = WebRequest.Create(url) as HttpWebRequest; + request.ProtocolVersion = HttpVersion.Version11; + } + else + { + request = WebRequest.Create(url) as HttpWebRequest; + } + + request.Method = "GET"; + request.Headers["Pragma"] = "no-cache"; + request.Accept = "text/html, application/xhtml+xml, */*"; + request.Headers["Accept-Language"] = "en-US,en;q=0.5"; + request.ContentType = "application/x-www-form-urlencoded"; + request.UserAgent = DefaultUserAgent; + request.Referer = Referer; + + if (headers != null) + { + foreach (var header in headers) + { + request.Headers.Add(header.Key, header.Value); + } + } + + + if (!string.IsNullOrEmpty(userAgent)) + { + request.UserAgent = userAgent; + } + if (timeout.HasValue) + { + request.Timeout = timeout.Value * 1000; + } + if (cookies != null) + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(cookies); + } + else + { + request.CookieContainer = new CookieContainer(); + request.CookieContainer.Add(Cookies); + } + response = request.GetResponse() as HttpWebResponse; + + Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); + Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); + Cookies.Add(response.Cookies); + + using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) + { + return reader.ReadToEnd(); + } + } + catch (Exception ex) + { + throw ex; + } + finally + { + if (response != null) + response.Close(); + } + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs new file mode 100644 index 0000000..cd6d96f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class IPUtil + { + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs new file mode 100644 index 0000000..1a4dbb5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore.Diagnostics; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Diagnostics; +using System.Text; +using System.Threading.Tasks; +using System.Threading; +using WeiCloud.Core.NlogTools; +using System.Linq; +using Microsoft.Extensions.Options; +using NLog; +using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Tokens; + +namespace WeiCloud.Core.Common.Interceptor +{ + public static class CallContext + { + private static readonly AsyncLocal _context = new AsyncLocal { }; + + public static string? CurrentMethod + { + get => _context.Value; + set => _context.Value = value; + } + } + public class EfMonitorOptions + { + public int EnableSlowQueryMonitor { get; set; } + public int SlowQueryThresholdMs { get; set; } = 1000; + } + + public class SlowQueryInterceptor : DbCommandInterceptor + { + private readonly ILogger _logger; + private readonly EfMonitorOptions _options; + + public SlowQueryInterceptor(IOptions options, ILogger logger) + { + _options = options.Value; + _logger = logger; + } + public override async ValueTask ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default) + { + if (_options.EnableSlowQueryMonitor == 1 && eventData.Duration.TotalMilliseconds >= _options.SlowQueryThresholdMs) + { + var caller = CallContext.CurrentMethod ?? "Unknown"; + _logger.LogWarning($@"⚠️ EF慢查询:耗时={eventData.Duration.TotalMilliseconds}ms +调用方法: {caller} +SQL: +{command.CommandText}"); + } + + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs new file mode 100644 index 0000000..ccd5d93 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs @@ -0,0 +1,10 @@ +namespace WeiCloud.Core.Common +{ + public static class LocalCache + { + /// + /// 报警个数 + /// + public static int AlarmCount { get; set; } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs new file mode 100644 index 0000000..37f8421 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public static class MathExpandClass + { + public static double KeepTwodig(this double num) + { + if (Math.Abs(num - num.ToInt()) <= 0.01){ + return num; + } + else + { + return Math.Round(num, 2); + } + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs new file mode 100644 index 0000000..ab295fa --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs @@ -0,0 +1,87 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization.Infrastructure; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Common +{ + public class MyAllowAnonymous : AuthorizeFilter + { + private static AuthorizationPolicy _policy_ = new AuthorizationPolicy(new[] { new DenyAnonymousAuthorizationRequirement() }, new string[] { }); + + public MyAllowAnonymous() : base(_policy_) { } + + public override async Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + #region 第三方验证 + ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; + //bool isActionAuthDescriptor = ad.MethodInfo.IsDefined(typeof(ThirdPartyAuthorizeAttribute), false); + var actionAuthDescriptor = ad.MethodInfo.GetCustomAttributes(typeof(ThirdPartyAuthorizeAttribute), false).FirstOrDefault(); + var controllerAuthDescriptor = ((ThirdPartyAuthorizeAttribute[])((ControllerActionDescriptor)context.ActionDescriptor).ControllerTypeInfo.GetCustomAttributes(typeof(ThirdPartyAuthorizeAttribute), false)).FirstOrDefault(); + //[0].ProjectNam; + if (actionAuthDescriptor != null || controllerAuthDescriptor != null) + {//x8duU2lvTLahXP2x + try + { + var requestTime = DateTime.Parse(context.HttpContext.Request.Headers["RequestTime"].FirstOrDefault()); + if (requestTime >= DateTime.Now.AddMinutes(-15) && requestTime < DateTime.Now.AddMinutes(15)) + { + var requestTimeStr = requestTime.ToString("yyyyMMddHHmmss"); + var customerSign = context.HttpContext.Request.Headers["RequestSign"].FirstOrDefault(); + string key = $"x8duU2lvTLahXP2x{requestTimeStr}"; + var sign = MD5Helper.GetMd5String(key); + if (sign.Equals(customerSign)) + { + return; + } + } + } + catch (Exception ex) + { + } + context.Result = new JsonResult(new { Code = (int)HttpStatusCode.Unauthorized }); + //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; + return; + } + #endregion + + await base.OnAuthorizationAsync(context); + if (!context.HttpContext.User.Identity.IsAuthenticated || + context.Filters.Any(item => item is IAllowAnonymousFilter)) return; + + //var url = context.HttpContext.url; + //解析url + // {/ Home / Index} + //var url = context.HttpContext.Request.Path.Value; + //if (string.IsNullOrWhiteSpace(url)) + //{ + // return; + //} + + //var list = url.Split("/"); + //if (list.Length <= 0 || url == "/") + //{ + // return; + //} + //var controllerName = list[1].ToString().Trim(); + //var actionName = list[2].ToString().Trim(); + } + } + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true)] + public class ThirdPartyAuthorizeAttribute : Attribute + { + public ThirdPartyAuthorizeAttribute(string projectName) => ProjectName = projectName; + + // Get or set the Age property by manipulating the underlying Policy property + public string ProjectName { get; set; } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs new file mode 100644 index 0000000..c54a6ee --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class NumberCharConvert + { + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs new file mode 100644 index 0000000..8dbbd7b --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Common +{ + public class PolicyContextModel + { + private readonly IConfiguration configuration; + public PolicyContextModel(IConfiguration configuration) + { + this.configuration = configuration; + } + + public ContextModel GetPolicyContextModel() + { + return new ContextModel() + { + userId = string.IsNullOrEmpty(configuration["PolicyConfig:BackUserId"]) ? 1 : configuration["PolicyConfig:BackUserId"].ToLong(), + userName = string.IsNullOrEmpty(configuration["PolicyConfig:BackUserName"]) ? "admin" : configuration["PolicyConfig:BackUserName"], + actionName = "控制策略", + machineIp = "127.0.0.1" + }; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs new file mode 100644 index 0000000..cf8c351 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public class PostUniClientModel + { + public long UserId { get; set; } + public string ClientId { get; set; } + } + + + + /// + /// 修改用户信息 + /// + public partial class PutUserDto + { + public long Id { get; set; } + public string Userfullname { get; set; } + + public short? Sex { get; set; } + + public string Userpost { get; set; } + + public string Phone { get; set; } + + public string Email { get; set; } + public string Wechat { get; set; } + } + + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs new file mode 100644 index 0000000..a54afad --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs @@ -0,0 +1,350 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Common +{ + public class QueryConst + { + public static List GetOwnerInitPermissions(long parentId, List allPermissions) + { + var result = new List { }; + var childs = allPermissions.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetOwnerInitPermissions(child.Id, allPermissions); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + /// + /// 获取所有建筑物 + /// + /// + /// + /// + public static List GetChilds(long parentId, List allConsts) + { + var result = new List(); + var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetChilds(child.Id, allConsts); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + + public static List GetChilds(long parentId, List allConsts) + { + var result = new List(); + var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetChilds(child.Id, allConsts); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + + public static List GetParents(long id, List allConsts) + { + var result = new List(); + var parentItem = allConsts.FirstOrDefault(t => t.Id == id); + if (parentItem != null) + { + result.Add(parentItem); + if (parentItem.Parentid != null && parentItem.Parentid > 0) + { + var _parentItems = GetParents(parentItem.Parentid ?? 0, allConsts); + if (_parentItems != null && _parentItems.Count > 0) + result.AddRange(_parentItems); + } + } + return result; + } + + public static ConstructionInfo GetConstParent(long id, List allConsts) + { + var result = new ConstructionInfo(); + try + { + var p = allConsts.FirstOrDefault(t => t.Id == id); + if (p == null) + { + return new ConstructionInfo { Id = id }; + } + else if (p.Parentid == null || p.Parentid == 0) + { + return p; + } + return GetConstParent((long)p.Parentid, allConsts); + } + catch (Exception ex) + { + } + return result; + } + + public static List GetTenementAreaChilds(long parentId, List allConsts) + { + var result = new List(); + var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetTenementAreaChilds(child.Id, allConsts); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + + public static List GetUserRoles(long parentId, List allRoles) + { + var result = new List(); + var childs = allRoles.Where(t => t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetUserRoles(child.Id, allRoles); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + + public static short CheckDataChangeStateTypeByTable(string tableName, string fieldName) + { + short result = 0; + if (tableName.Equals("Tb_Ammeter_History", System.StringComparison.OrdinalIgnoreCase)) + { + if (fieldName.Equals("Am_Parm_029", System.StringComparison.OrdinalIgnoreCase)) + { + result = DataChangeStateAccum; + } + } + + if (tableName.Equals("Tb_WaterMeter_History", System.StringComparison.OrdinalIgnoreCase)) + { + if (fieldName.Equals("Wm_Parm_003", System.StringComparison.OrdinalIgnoreCase)) + { + result = DataChangeStateAccum; + } + } + + if (tableName.Equals("Tb_GasMeter_History", System.StringComparison.OrdinalIgnoreCase)) + { + if (fieldName.Equals("Gm_Parm_002", System.StringComparison.OrdinalIgnoreCase)) + { + result = DataChangeStateAccum; + } + } + + if (tableName.Equals("Tb_HeatMeter_History", System.StringComparison.OrdinalIgnoreCase)) + { + if (fieldName.Equals("Hm_Parm_002", System.StringComparison.OrdinalIgnoreCase)) + { + result = DataChangeStateAccum; + } + } + return result; + } + /// + /// 累计值 + /// + public static short DataChangeStateAccum = 1; + + public static TenementArea GetParentTenementArea(long id, List allAreas) + { + try + { + var currentArea = allAreas.FirstOrDefault(t => t.Id == id); + if (currentArea == null) + { + return null; + } + else if (currentArea.Parentid == null || currentArea.Parentid == 0) + { + return currentArea; + } + var parentArea = allAreas.FirstOrDefault(t => t.Id == currentArea.Parentid); + if (parentArea == null) + { + return currentArea; + } + if (parentArea.Parentid == null || parentArea.Parentid == 0) + { + return parentArea; + } + return GetParentTenementArea(parentArea.Parentid ?? 0, allAreas); + } + catch (Exception ex) + { + + } + return null; + } + } + public class QueryEquipType + { + public static List GetChilds(long parentId, List all) + { + var result = new List(); + var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetChilds(child.Id, all); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + public static List GetAll(List parentEqTypes, List all) + { + var equipTypes = new List { }; + foreach (var parentEqType in parentEqTypes) + { + equipTypes.Add(parentEqType); + var childs = GetChilds(parentEqType.Id, all); + if (childs != null && childs.Count() > 0) + { + equipTypes.AddRange(childs); + } + } + return equipTypes; + } + } + public class QueryUserGroupType + { + public static List GetChilds(long parentId, List all) + { + var result = new List(); + var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetChilds(child.Id, all); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + } + public class QueryItem + { + /// + /// 获取分项下所有设备 + /// + /// + /// + /// + /// + public static List GetItemEquips(long id, List constEnergyItems, List allEquipmentInfos) + { + var equips = new List { }; + var childItems = constEnergyItems.Where(t => t.Parentid == id).ToList(); + if (childItems != null && childItems.Count() > 0) + { + foreach (var childItem in childItems) + { + var equipmentInfos = allEquipmentInfos.Where(t => t.Itemid == childItem.Id).ToList(); + if (equipmentInfos != null && equipmentInfos.Count() > 0) + { + var equipmentInfoIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); + equips.AddRange(equipmentInfoIds); + } + else + { + var _equips = GetItemEquips(childItem.Id, constEnergyItems, allEquipmentInfos); + if (_equips != null && _equips.Count() > 0) + { + equips.AddRange(_equips); + } + } + } + } + return equips; + } + } + public class QueryGroup + { + public static List GetParents(long id, List allConsts) + { + var result = new List(); + var parentItem = allConsts.FirstOrDefault(t => t.Id == id); + if (parentItem != null) + { + result.Add(parentItem); + if (parentItem.ParentId > 0) + { + var _parentItems = GetParents(parentItem.ParentId, allConsts); + if (_parentItems != null && _parentItems.Count > 0) + result.AddRange(_parentItems); + } + } + return result; + } + public static List GetParentRds(long id, List allConsts) + { + var result = new List(); + var parentItem = allConsts.FirstOrDefault(t => t.Id == id); + if (parentItem != null) + { + result.Add(parentItem); + if (parentItem.ParentId > 0) + { + var _parentItems = GetParentRds(parentItem.ParentId, allConsts); + if (_parentItems != null && _parentItems.Count > 0) + result.AddRange(_parentItems); + } + } + return result; + } + public static List GetChilds(long parentId, List all) + { + var result = new List(); + var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); + foreach (var child in childs) + { + result.Add(child); + var _childs = GetChilds(child.Id, all); + if (_childs != null && _childs.Count > 0) + result.AddRange(_childs); + } + return result; + } + } + public class QueryFunPermission + { + public static List GetParents(long parentId, List allFunPermissions) + { + var result = new List { }; + var parent = allFunPermissions.FirstOrDefault(t => t.Id == parentId); + if (parent == null) + { + return result; + } + else + { + result.Add(parent); + var parents = GetParents(parent.ParentId, allFunPermissions); + if (parents != null && parents.Count() > 0) + { + result.AddRange(parents); + } + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs new file mode 100644 index 0000000..02e030e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + /// + /// 生成随机数 ccx 20200731 + /// + public static class RandomNumberCreate + { + //随机数内容 + private static char[] constant = + { + '0','1','2','3','4','5','6','7','8','9', + 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', + 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' + }; + /// + /// 生成随机数 + /// + /// 随机数位数 + /// 指定位数的随机数 + public static string GenerateRandomNumber(int Length) + { + System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62); + Random rd = new Random(); + for (int i = 0; i < Length; i++) + { + newRandom.Append(constant[rd.Next(62)]); + } + return newRandom.ToString(); + } + public static string getRandomizer(int intLength, bool booNumber, bool booSign, bool booSmallword, bool booBigword) + { + //定义 + Random ranA = new Random(); + int intResultRound = 0; + int intA = 0; + string strB = ""; + while (intResultRound < intLength) + { + //生成随机数A,表示生成类型 + //1=数字,2=符号,3=小写字母,4=大写字母 + intA = ranA.Next(1, 5); + //如果随机数A=1,则运行生成数字 + //生成随机数A,范围在0-10 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 1 && booNumber) + { + intA = ranA.Next(0, 10); + strB = intA.ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + //如果随机数A=2,则运行生成符号 + //生成随机数A,表示生成值域 + //1:33-47值域,2:58-64值域,3:91-96值域,4:123-126值域 + if (intA == 2 && booSign == true) + { + intA = ranA.Next(1, 5); + //如果A=1 + //生成随机数A,33-47的Ascii码 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 1) + { + intA = ranA.Next(33, 48); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + //如果A=2 + //生成随机数A,58-64的Ascii码 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 2) + { + intA = ranA.Next(58, 65); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + + //如果A=3 + //生成随机数A,91-96的Ascii码 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 3) + { + intA = ranA.Next(91, 97); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + + //如果A=4 + //生成随机数A,123-126的Ascii码 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 4) + { + intA = ranA.Next(123, 127); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + } + + //如果随机数A=3,则运行生成小写字母 + //生成随机数A,范围在97-122 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 3 && booSmallword == true) + { + intA = ranA.Next(97, 123); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + + //如果随机数A=4,则运行生成大写字母 + //生成随机数A,范围在65-90 + //把随机数A,转成字符 + //生成完,位数+1,字符串累加,结束本次循环 + if (intA == 4 && booBigword == true) + { + intA = ranA.Next(65, 89); + strB = ((char)intA).ToString() + strB; + intResultRound = intResultRound + 1; + continue; + } + } + return strB; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs new file mode 100644 index 0000000..e8c09e5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Common +{ + public static class RealValueMean + { + #region 获取实时值相对应的含义 + public static string GetParamMean(string value, string paramMean) + { + string returnStr = string.Empty; + if (string.IsNullOrEmpty(paramMean)) + { + return returnStr; + } + if (paramMean.Contains(";")) + { + string[] arr = paramMean.Split(';'); + foreach (string s in arr) + { + if (!string.IsNullOrEmpty(s) && s.Contains(':')) + { + string[] ar = s.Split(':'); + + if (ar.Length == 2) + { + if (string.Equals(value.Trim(), ar[0].Trim(), StringComparison.OrdinalIgnoreCase)) + { + returnStr = ar[1]; + break; + } + } + + } + } + } + + return returnStr; + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs new file mode 100644 index 0000000..6142b3e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs @@ -0,0 +1,15 @@ +using NPOI.Util; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Common +{ + public static class SteamHeatCalculate + { + + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs new file mode 100644 index 0000000..1b24eed --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace WeiCloud.Core.Common.Tasks +{ + public class TaskManager + { + private static ConcurrentDictionary TasksCancel = new ConcurrentDictionary(); + public static void AddTask(long key, CancellationTokenSource cancellationTokenSource) + { + TasksCancel.AddOrUpdate(key, (key) => + { + return cancellationTokenSource; + }, (key, value) => + { + value.Cancel(); + return cancellationTokenSource; + }); + } + public static List GetTasks() + { + return TasksCancel.Keys.ToList(); + } + public static bool StopTask(long key) + { + var result = true; + try + { + CancellationTokenSource cancellationTokenSource = null; + TasksCancel.TryRemove(key, out cancellationTokenSource); + cancellationTokenSource.Cancel(); + } + catch (Exception ex) + { + result = false; + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs new file mode 100644 index 0000000..cd44f40 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 空气质量类型 + /// + public static class AirQuantityEnum + { + /// + /// 温度 + /// + public static readonly short Temperature = 1; + /// + /// 湿度 + /// + public static readonly short Humidity = 2; + /// + /// 二氧化碳 + /// + public static readonly short CO2 = 3; + /// + /// 挥发性有机物 + /// + public static readonly short TVOC = 4; + /// + /// PM2.5 + /// + public static readonly short PM = 5; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs new file mode 100644 index 0000000..0f13fd1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class AssetTypeEnum + { + public static readonly string VideoMonitor = "VideoMonitor"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs new file mode 100644 index 0000000..b6078e0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public enum CarbonEnum + { + } + public enum CarbonQuotaAdjustEnum + { + /// + /// 未提交 + /// + NotSubmitted = 0, + /// + /// 已发布待审核 + /// + Published = 1, + /// + /// 已审核 + /// + Audited = 2, + /// + /// 已审核调整中 + /// + AuditedAdjust = 3, + /// + /// 已完成 + /// + Completed = 4 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs new file mode 100644 index 0000000..b09f20f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class ClimNum + { + public static readonly long SevereCold = 1; + public static readonly long Cold = 2; + public static readonly long HotAndCold = 3; + public static readonly long HotAndWarm = 4; + public static readonly long Warm = 5; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs new file mode 100644 index 0000000..3dc119a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class ConModelEnum + { + /// + /// 暖通系统 + /// + public static readonly long HVACSystem = 1; + /// + /// 配电系统 + /// + public static readonly long DistributionSystem = 2; + /// + /// 照明系统 + /// + public static readonly long LightSystem = 3; + /// + /// 电梯系统 + /// + public static readonly long LiftSystem = 4; + /// + /// 给排水系统 + /// + public static readonly long WaterSupplyAndDrainageSystem = 5; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs new file mode 100644 index 0000000..90e866a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 建筑物类型 + /// + public static class ConstTypeEnum + { + /// + /// 室外 + /// + public const string OutRoomCode = "ct011"; + /// + /// 配电室 + /// + public const string ElectronicConstCode = "ct005"; + /// + /// 生活水泵房 + /// + public const string LifeWaterConstCode = "ct006"; + /// + /// 污水泵房 + /// + public const string SewageConstCode = "ct007"; + /// + /// 卫生间污水泵房 + /// + public const string BathWaterConstCode = "ct009"; + /// + /// 区域 + /// + public const string AreaConstCode = "ct017"; + /// + /// 楼层 + /// + public const string FloorCode = "ct002"; + /// + /// 楼栋 + /// + public const string BuildingCode = "ct001"; + /// + /// 楼栋 + /// + public const string HVACSystemCode = "ct004"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs new file mode 100644 index 0000000..1eb7567 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Entity.LogicModels.BasicGroup; + +namespace WeiCloud.Core.EnumTools +{ + public enum DataSetGroupIntervalTypeEnum + { + RealData = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6 + } + public enum AggregateEnum + { + Sum = 1, + Average = 2, + Max = 3, + Min = 4, + Count = 5, + First = 6, + Last = 7 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs new file mode 100644 index 0000000..30d8df9 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// ccx 能源分项元数据code + /// + public static class EnergyItemEnum + { + /// + /// 暖通空调用电 + /// + public static readonly string ElectForAirCondition = "it002"; + /// + /// 暖通空调用气 + /// + public static readonly string GasForAirCondition = "it031"; + /// + /// 生活用水 + /// + public static readonly string DomesticWater = "it023"; + /// + /// 中水 洁净卫生用水 + /// + public static readonly string NormalWater = "it024"; + /// + /// 照明插座用电 + /// + public static readonly string LightItem = "it001"; + /// + /// 动力用电 + /// + public static readonly string PowerItem = "it003"; + /// + /// 其他用电 + /// + public static readonly string OtherItem = "it021"; + + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs new file mode 100644 index 0000000..6239faf --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 能源计费方式 + /// + public static class EngeryBillingType + { + /// + /// 平均价 + /// + public static readonly short Average = 1; + /// + /// 谷峰平 + /// + public static readonly short Fengguping = 3; + /// + /// 阶梯 + /// + public static readonly short Ladder = 2; + } + /// + /// 谷峰平类型 + /// + public static class FenggupingType + { + /// + /// 尖峰 + /// + public static readonly short Peak = 1; + /// + /// 峰 + /// + public static readonly short PeakShort = 2; + /// + /// 平 + /// + public static readonly short Flat = 3; + /// + /// 谷 + /// + public static readonly short Valley = 4; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs new file mode 100644 index 0000000..a192936 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 能源类型枚举,水电气 + /// + public static class EngeryTypeEnum + { + /// + /// 电 + /// + public static readonly short ElectEngery = 1; + /// + /// 水 + /// + public static readonly short WaterEngery = 3; + /// + /// 气 + /// + public static readonly short GasEngery = 2; + /// + /// 热表 + /// + public static readonly short HeatEngery = 4; + /// + /// 蒸汽 + /// + public static readonly short Steam = 5; + /// + /// 煤气 + /// + public static readonly short CoalGas = 6; + /// + /// 柴油 + /// + public static readonly short Oil = 7; + /// + /// 热水 + /// + public static readonly short HotWater = 8; + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs new file mode 100644 index 0000000..67f4202 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Reflection; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class ZrhEnumHelper + { + public static string GetDescription(int value) where TEnum : Enum + { + var type = typeof(TEnum); + var name = Enum.GetName(type, value); + if (name == null) return null; + + var field = type.GetField(name); + if (field == null) return null; + + var attr = field.GetCustomAttribute(); + return attr?.Description ?? name; + } + public static List<(int Value, string Description)> GetEnumValueDescriptionList() where TEnum : Enum + { + var type = typeof(TEnum); + var result = new List<(int, string)>(); + + foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static)) + { + int value = (int)field.GetValue(null); + var attr = field.GetCustomAttribute(); + string desc = attr?.Description ?? field.Name; + + result.Add((value, desc)); + } + + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs new file mode 100644 index 0000000..3724f67 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class EnumSystemModel + { + /// + /// 暖通系统id + /// + public const int HVACSystem = 1; + /// + /// 照明系统 + /// + public const int LightingSystem = 3; + /// + /// 配电系统 + /// + public const int ElectricalSystem = 2; + /// + /// 电梯系统 + /// + public const int LiftSystem = 4; + /// + /// 给排水系统 + /// + public const int WaterSystem = 5; + /// + /// 能源系统 + /// + public const int EnergySystem = 11; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration.cs new file mode 100644 index 0000000..2b4e7c0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace WeiCloud.Core +{ + public class Enumeration : IComparable + { + private readonly int _value; + private readonly string _displayName; + + protected Enumeration() + { + } + + protected Enumeration(int value, string displayName) + { + _value = value; + _displayName = displayName; + } + + public int Value + { + get { return _value; } + } + + public string DisplayName + { + get { return _displayName; } + } + + public override string ToString() + { + return DisplayName; + } + + public static IEnumerable GetAll() where T : Enumeration, new() + { + var type = typeof(T); + var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); + + foreach (var info in fields) + { + var instance = new T(); + var locatedValue = info.GetValue(instance) as T; + + if (locatedValue != null) + { + yield return locatedValue; + } + } + } + + public override bool Equals(object obj) + { + var otherValue = obj as Enumeration; + + if (otherValue == null) + { + return false; + } + + var typeMatches = GetType().Equals(obj.GetType()); + var valueMatches = _value.Equals(otherValue.Value); + + return typeMatches && valueMatches; + } + + public override int GetHashCode() + { + return _value.GetHashCode(); + } + + public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) + { + var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value); + return absoluteDifference; + } + + public static T FromValue(int value) where T : Enumeration, new() + { + var matchingItem = parse(value, "value", item => item.Value == value); + return matchingItem; + } + + public static T FromDisplayName(string displayName) where T : Enumeration, new() + { + var matchingItem = parse(displayName, "display name", item => item.DisplayName == displayName); + return matchingItem; + } + + private static T parse(K value, string description, Func predicate) where T : Enumeration, new() + { + var matchingItem = GetAll().FirstOrDefault(predicate); + + if (matchingItem == null) + { + var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T)); + throw new ApplicationException(message); + } + + return matchingItem; + } + + public int CompareTo(object other) + { + return Value.CompareTo(((Enumeration)other).Value); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs new file mode 100644 index 0000000..6cf939f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; + +namespace WeiCloud.Core.EnumTools +{ + + [Serializable] + [DebuggerDisplay("{DisplayName} - {Value}")] + public abstract class Enumeration2 : IComparable, IEquatable + where TEnumeration : Enumeration2 + where TValue : IComparable + { + private static readonly Lazy Enumerations = new Lazy(GetEnumerations); + + [DataMember(Order = 1)] private readonly string _displayName; + + [DataMember(Order = 0)] private readonly TValue _value; + + protected Enumeration2(TValue value, string displayName) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + + _value = value; + _displayName = displayName; + } + + public TValue Value => _value; + + public string DisplayName => _displayName; + + public int CompareTo(TEnumeration other) + { + return Value.CompareTo(other == default(TEnumeration) ? default(TValue) : other.Value); + } + + public bool Equals(TEnumeration other) + { + return other != null && ValueEquals(other.Value); + } + + public sealed override string ToString() + { + return DisplayName; + } + + public static TEnumeration[] GetAll() + { + return Enumerations.Value; + } + + private static TEnumeration[] GetEnumerations() + { + var enumerationType = typeof(TEnumeration); + return enumerationType + .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Where(info => enumerationType.IsAssignableFrom(info.FieldType)) + .Select(info => info.GetValue(null)) + .Cast() + .ToArray(); + } + + public override bool Equals(object obj) + { + return Equals(obj as TEnumeration); + } + + public override int GetHashCode() + { + return Value.GetHashCode(); + } + + public static bool operator ==(Enumeration2 left, + Enumeration2 right) + { + return Equals(left, right); + } + + public static bool operator !=(Enumeration2 left, + Enumeration2 right) + { + return !Equals(left, right); + } + + public static TEnumeration FromValue(TValue value) + { + return Parse(value, "value", item => item.Value.Equals(value)); + } + + public static TEnumeration Parse(string displayName) + { + return Parse(displayName, "display name", item => item.DisplayName == displayName); + } + + private static bool TryParse(Func predicate, out TEnumeration result) + { + result = GetAll().FirstOrDefault(predicate); + return result != null; + } + + private static TEnumeration Parse(object value, string description, Func predicate) + { + if (TryParse(predicate, out var result)) + return result; + return null; + } + + public static bool TryParse(TValue value, out TEnumeration result) + { + return TryParse(e => e.ValueEquals(value), out result); + } + + public static bool TryParse(string displayName, out TEnumeration result) + { + return TryParse(e => e.DisplayName == displayName, out result); + } + + protected virtual bool ValueEquals(TValue value) + { + return Value.Equals(value); + } + + public static bool Any(Func predicate) + { + return GetAll().Any(predicate); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs new file mode 100644 index 0000000..da60124 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Core.RulesEngine.RulesModels; + +namespace WeiCloud.Core.EnumTools +{ + public static class EqGroupTypeEnum + { + /// + /// 分区能耗 + /// + public const short Digital_EnergyConsumZone = 20;//分区能耗 + /// + /// 分区能耗 + /// + public const short EnergyConsumZone = 1;//分区能耗 + /// + /// 规则引擎 + /// + public static short RuleEngine = 2;//规则引擎 + /// + /// 计算引擎 + /// + public static short EalculationEngine = 3;//计算引擎 + /// + /// 其他 + /// + public static short Other = 99;//其他 + /// + /// 支路 + /// + public static short AccessRd = 14; + /// + /// 数字孪生设备运行分组 + /// + public static short EquipRun = 15; + /// + /// 电梯系统 + /// + public static short ElevatorZone = 17; + /// + /// 照明系统 + /// + public static short LightingZone = 18; + /// + /// 能效分区 + /// + + public static short EnergyEfficiencyConsumZone = 19; + + /// + /// 系统评价 + /// + + public static short GroupType_SysDiagnosis = 12; + /// + /// 分项 + /// + public static short SubItem = 25; + /// + /// 历史参数 + /// + public static short HisParm = 26; + /// + /// 项目总能耗 + /// + public static short ProjectTotalEnergyConsum = 32; + /// + /// 能效分区(能耗模型) + /// + + public static short EnergyEfficiencyConsumZoneV02 = 50; + /// + /// 能效分区(能效看板) + /// + + public static short EnergyEfficiencyConsumZoneBulletinBoard = 51; + /// + /// App视频监控 + /// + + public static short AppVideo = 200; + /// + /// 数据分析-分项 + /// + public static short EngeryAnalisysItem = 201; + /// + /// 园区企业能耗 + /// + public static short IndustrialParkEnergy = 46; + + /// + /// AI 工况巡优 + /// + public static short AIConOpt { get; set; } = 399; + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs new file mode 100644 index 0000000..f7531c0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public class EquipRuningStatus : Enumeration + { + //设备运行状态枚举表示 + public EquipRuningStatus(int value, string displayName) : base(value, displayName) + { + } + //停止 + public static readonly EquipRuningStatus stop = new EquipRuningStatus(0, nameof(stop).ToLowerInvariant()); + //启动 + public static readonly EquipRuningStatus start = new EquipRuningStatus(1, nameof(start).ToLowerInvariant()); + //故障 + public static readonly EquipRuningStatus fail = new EquipRuningStatus(2, nameof(fail).ToLowerInvariant()); + //中断 + public static readonly EquipRuningStatus signal = new EquipRuningStatus(3, nameof(signal).ToLowerInvariant()); + ////电梯上行 + //public static readonly EquipRuningStatus up = new EquipRuningStatus(3, nameof(up).ToLowerInvariant()); + ////电梯下行 + //public static readonly EquipRuningStatus down = new EquipRuningStatus(4, nameof(down).ToLowerInvariant()); + ////直梯当前楼层 + //public static readonly EquipRuningStatus num = new EquipRuningStatus(4, nameof(down).ToLowerInvariant()); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs new file mode 100644 index 0000000..eac0135 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class EquipTypeEnum + { + /// + /// 仪表类型Code + /// + public const string InstrumentTypeCode = "eq128"; + /// + /// 电表类型Code + /// + public const string ElectricityMeterTypeCode = "eq128016"; + /// + /// 水表类型Code + /// + public const string WaterMeterTypeCode = "eq128017"; + /// + /// 气表类型Code + /// + public const string GasMeterTypeCode = "eq128018"; + /// + /// 热表类型Code + /// + public const string HeatMeterTypeCode = "eq128019"; + /// + /// 通讯模块 + /// + public const string PLCTypeCode = "eq038"; + + /// + /// 空调主机 + /// + public const string AirHostCode = "eq126001"; + /// + /// 冷却水循环泵 + /// + public const string FCCCode = "eq002005"; + /// + /// 冷却水补水泵 + /// + public const string CoolingWaterMakeUpCode = "eq002006"; + /// + /// 冷温水循环泵 + /// + public const string ColdWarmWaterCirculatingCode = "eq002003"; + /// + /// 冷温水补水泵 + /// + public const string ColdWarmWaterMakeUpCode = "eq002004"; + /// + /// 热水循环泵 + /// + public const string HPKCode = "eq002078"; + /// + /// 末端新风 + /// + public const string TerminalFreshAirCode = "eq013059"; + /// + /// 风机盘管 + /// + public const string FCUCode = "eq013014"; + /// + /// 热风幕 + /// + public const string HotAirCurtainCode = "eq013031"; + /// + /// 污水排水泵 + /// + public const string SewageDrainagePumpCode = "eq002033"; + /// + /// 生活水给水泵 + /// + public const string DomesticWaterSupplyPumpCode = "eq137"; + /// + /// 变压器温控器 + /// + public const string TransfTemperControCode = "eq125061"; + /// + /// 中交世通变压器温控器 + /// + public const string STTransfTemperControCode = "eq471718840970272"; + /// + /// 高压综保 + /// + public const string HighVoltageIntegProteCode = "eq125062"; + /// + /// 低压柜 + /// + public const string LowVoltageCabinetCode = "eq125065"; + /// + /// 给排水设备 + /// + public const string WaterSupplyDraeEquipCode = "eq002"; + /// + /// 室内照明 + /// + public const string IndoorLightingCode = "eq136069"; + /// + /// 室外照明 + /// + public const string OutdoorLightingCode = "eq136070"; + /// + /// 广告灯箱 + /// + public const string AdvertisingLightBoxCode = "eq136071"; + /// + /// 照明设备 + /// + public const string LightEquipCode = "eq136"; + /// + /// 空调风系统 + /// + public const string AirConditioningSystemCode = "eq126013"; + /// + /// 纯新风空调机组 + /// + public const string OnlyAirGroupCode = "eq013122"; + /// + /// 纯新风空调机组 + /// + public const string ReturnBackAirGroupCode = "eq013123"; + /// + /// 组合式空调机组 + /// + public const string ColectionAirGroupCode = "eq013124"; + + /// + /// 电梯 + /// + public const string ElevatorCode = "eq028"; + /// + /// 直梯 + /// + public const string VerticalLadderCode = "eq028029"; + /// + /// 货梯 + /// + public const string CargoLift = "eq028029479591567333920"; + /// + /// 客梯 + /// + public const string Elevator = "eq028029479591577861664"; + /// + /// 扶梯 + /// + public const string EscalatorCode = "eq028030"; + /// + /// 温湿度传感器 + /// + public const string TempHumSensorCode = "eq020036"; + /// + /// 照度传感器 + /// + public const string IllumSensorCode = "eq020037"; + /// + /// 高压综保 + /// + public const string HighVoltageProtection = "eq125062"; + /// + /// 液位传感器 + /// + public const string LiqueLevelCode = "eq020023"; + /// + /// 光伏并网柜 + /// + public const string PVCode = "eq468321121415712"; + /// + /// 燃气内燃发电机组 + /// + public const string OilElectricEngineCode = "468276635161120"; + /// + /// 直燃型吸收式机组 + /// + public const string DirectFiredUnitCode = "eq001039"; + /// + /// 开关阀 + /// + public const string OpenCloseSwichCode = "eq127109"; + /// + /// 冷却塔风扇 + /// + public const string CoolingTower = "eq126032"; + /// + /// 空气质量传感器 + /// + public const string AirQuatity = "eq020097"; + /// + /// 温度传感器 + /// + public const string TempEquip = "eq020075"; + /// + /// 压力传感器 + /// + public const string PressEquip = "eq020113"; + /// + /// 虚拟设备/控制柜 + /// + public const string AbstractEquip = "eq470527720737824"; + /// + /// 控制面板 + /// + public const string ControlEquip = "eq470577169286176"; + /// + /// 视频摄像头 + /// + public const string ViewCode = "eq104"; + /// + /// 中水泵 + /// + public const string CWarterPump = "eq471054413443104"; + /// + /// 风冷机组 + /// + public const string AirCooledUnit = "eq001120"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs new file mode 100644 index 0000000..41d72c0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public class FamilyDecorationEnum + { + public static Dictionary ProjectContractDocDic = new Dictionary { { 1, "合同文件" }, { 2, "报价单" }, { 3, "施工单" }, { 4, "设计图纸" } }; + /// + /// 家装管理员 + /// + public static readonly long FamilyDecorationAdminId = 484988093582368; + /// + /// 国润丰泽-业主 + /// + public static readonly long FamilyDecorationOwnerId = 482689495630880; + #region 部门 + /// + /// 国润丰泽-部门 + /// + public static readonly long FamilyDecorationGroupId = 482689495703584; + /// + /// 客户-部门 + /// + public static readonly long FamilyDecorationCustomerGroupId = 486331178355744; + /// + /// 销售-部门 + /// + public static readonly long FamilyDecorationSaleGroupId = 483536378644000; + #endregion + + #region 角色 + /// + /// 客户-角色 + /// + public static readonly long FamilyDecorationCustomerRoleId = 484284962365984; + /// + /// admin-角色 + /// + public static readonly long FamilyDecorationAdminRoleId = 483536405638176; + #endregion + /// + /// 角色权限,缓存key + /// + public static readonly string RoleFunPermissionCacheKey = "RoleFunPermission_{0}"; + /// + /// 项目角色权限,缓存key + /// + public static readonly string ProjectRoleFunPermissionCacheKey = "ProjectRoleFunPermission_{0}"; + } + public enum FamilyDecorationFormDocType + {//1-text、2-textarea、3-fileupload + Text = 1, + TextArea = 2, + FileUpload = 3 + } + public enum ProjectPlanStatusEnum + { + /// + /// 未开始 + /// + NotStarted = 0, + /// + /// 进行中 + /// + Processing = 1, + Completed = 2 + } + public enum ProjectStatusEnum + { + /// + /// 未进场 + /// + NotMobilized = 1, + /// + /// 已进场 + /// + AlreadyMobilized = 2, + /// + /// 已完工 + /// + Completed = 3 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs new file mode 100644 index 0000000..bbfa3d1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public class FauabnormalEnum + { + /// + /// 设备故障 + /// + public const long EquipDamage = 1; + /// + /// 参数超限 + /// + public const long ParamBeyond = 2; + /// + /// 视频报警 + /// + public const long ViewAlarm = 3; + /// + /// 能耗异常 + /// + public const long EnergyAbnormal = 4; + /// + /// 通讯中断 + /// + public const long Comloss = 5; + /// + /// 事件报警 + /// + public const long EventAlarm = 6; + /// + /// 维保报警 + /// + public const long MaintenAlarm = 7; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs new file mode 100644 index 0000000..1e8521f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class FaultHandleEnum + { + /// + /// 误报 + /// + public const long ErrorInfo = 1; + /// + /// 设备调试 + /// + public const long Handdle = 2; + /// + /// 转工单 + /// + public const long TurnWorkFlow = 3; + /// + /// 忽略 + /// + public const long Ignore = 4; + /// + /// 复位 + /// + public const long Reset= 5; + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs new file mode 100644 index 0000000..8a57098 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class FaultStatusEnum + { + /// + /// 发生故障 + /// + public const long FaultHappen = 1; + /// + /// 忽略 + /// + public const long Ignore = 2; + /// + /// 处理中 + /// + public const long Handle = 3; + /// + /// 已复位 + /// + public const long ArtificialHandle= 4; + /// + /// 已压制 + /// + public const long SystemHandle = 5; + /// + /// 关闭 + /// + public const long CloseHandle = 6; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs new file mode 100644 index 0000000..35b75d5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public enum FunPermissionEnum + { + Page = 1, + Func = 2, + Form = 3 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs new file mode 100644 index 0000000..de2cfa3 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 控制面板的低档、中档、高档、自动设定 ccx202012-15 + /// + public static class GearEnum + { + //低档 + public static readonly short LowGear = 1; + //中档 + public static readonly short MiddleGear = 2; + //高档 + public static readonly short HightGear = 3; + //自动 + public static readonly short AutomoGear = 4; + + } + public static class ModeEnum + { + //制冷 + public static readonly short CoolMode = 1; + //制热 + public static readonly short HeatMode = 2; + //送风 + public static readonly short WindMode = 3; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs new file mode 100644 index 0000000..ac6e190 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class HandWritetenEnum + { + public const short Month=1; + public const short Day =2; + public const short Hour = 3; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs new file mode 100644 index 0000000..02143cd --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs @@ -0,0 +1,239 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core +{ + /// + /// infoapi所有枚举值 + /// + internal class InfoApiEnum + { + } + /// + /// 0-自定义,1-时,2-天,3-月,4-年(查询时日期类型) + /// + public enum QueryTimeTypeEnum + { + Custom = 0, + Hour = 1, + Day = 2, + Month = 3, + Year = 4 + } + /// + /// 1-项目、2-空间、3-设备、4-参数 + /// + public enum IOTThingTypeEnum + { + Project = 1, + Construct = 2, + Equip = 3, + Param = 4 + } + public enum IOTLabelTypeEnum + { + /// + /// 能耗 + /// + EnergyConsum = 1 + } + /// + /// Equip\Consturct\Time + /// + public class IOTLabelDimensionEnum + { + /// + /// 设备 + /// + public static string Equip = "Equip"; + /// + /// 建筑物 + /// + public static string Consturct = "Consturct"; + /// + /// 时间(小时) + /// + public static string TimeHour = "TimeHour"; + /// + /// 时间(天) + /// + public static string TimeDay = "TimeDay"; + /// + /// 时间(月) + /// + public static string TimeMonth = "TimeMonth"; + /// + /// 时间(年) + /// + public static string TimeYear = "TimeYear"; + } + public enum IOTLabelCalculateEnum + { + Sum = 1, + Count = 2, + Max = 3, + Min = 4, + Average = 5, + /// + /// 去重 + /// + DuplicateRemoval = 6 + } + #region 策略 + public enum StratePlanGroupExecStateEnum + { + /// + /// 未开始 + /// + Unexecuted = 0, + /// + /// 已开始 + /// + Started = 1, + /// + /// 执行成功 + /// + ExecutionSucceeded = 2, + /// + /// 执行失败 + /// + ExecutionFailed = 3 + } + #endregion + + #region 参数类型 + /// + /// 实时参数类型 + /// + public enum RealPointTypeEnum + { + /// + /// 实时点 + /// + Real = 1, + /// + /// 计算点 + /// + Cal = 2, + Target = 3 + } + /// + /// 指标参数类型 + /// + public enum LabelPointTypeEnum + { + /// + /// 能耗值 + /// + EnergyConsum = 1, + /// + /// 当日能耗 + /// + TodayEnergyConsum = 2 + } + #endregion + + #region 舒适home + public enum ConformHomeTenantAuthCacheEnum + { + /// + /// 业主 + /// + ActivateOwner = 1, + /// + /// 其他成员 + /// + ActivateMember = 2 + } + #endregion + + #region 指标 + public enum TargetCalculationTypeEnum + { + /// + /// 物联参数聚合 + /// + ThingParam = 1, + /// + /// 多指标公式 + /// + MultipleIndicatorFormula = 2, + /// + /// 平台引用 + /// + PlatformRef = 3 + } + public enum TargetCalculateParamCalIntervalEnum + { + /// + /// 每小时 + /// + EveryHour = 1, + /// + /// 每天 + /// + EveryDay = 2 + } + public class TargetCalculateParamCalCronEnum + { + /// + /// 每小时 + /// + public static string EveryHour = "0 0 0/1 * * ?"; + /// + /// 每天 + /// + public static string EveryDay = "0 0 0 1/1 * ?"; + } + /// + /// 参数取值类型 + /// + public enum TargetCalculateParamCalTypeEnum + { + /// + /// 最大值 + /// + Max = 1, + /// + /// 最小值 + /// + Min = 2, + /// + /// 平均值 + /// + Avg = 3, + /// + /// 计数 + /// + Count = 4, + /// + /// 差值 + /// + DValue = 5, + /// + /// 求和 + /// + Sum = 6 + } + public enum PlatformDataTypeEnum + { + /// + /// 能源计费 + /// + EnergyBilling = 1, + /// + /// 能耗定额 + /// + EnergyConsumQuota = 2 + } + #endregion + #region 节能量 + public enum EnergySavingTimeTypeEnum + { + Custom = 0, + Month = 1, + Year = 2 + } + #endregion +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs new file mode 100644 index 0000000..d9dd109 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + internal class IotDsEnum + { + } + /// + /// 标签类型 + /// + public enum IotDsLabelTypeEnum + { + Type = 1, + ParamType = 2, + Extend = 3 + } + /// + /// 参数扩展标签 + /// + public class IotDsParamExtendLabelEnum + { + /// + /// 能耗计算 + /// + public static string DWCode = "DW"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs new file mode 100644 index 0000000..8145d74 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class KBCategoryEnum + { + public const short QA = 1; + public const short Article = 2; + public const short Sys = 3; + } + public static class KBContentTypeEnum + { + public const short Text = 1; + public const short Word = 2; + public const short Mp4 = 3; + public const short Html = 4; + public const short Pdf = 5; + } + public static class KBFileEnum + { + public const string FilePath = "KB"; + } + public static class KBUserActionTypeEnum + { + public const short Like = 1; + public const short Collection = 2; + } + public static class KBEnum + { + public const int ContentShowLen = 200; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs new file mode 100644 index 0000000..f5cfc90 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class MenuTypeEnum + { + //平台模块 + public static readonly short Model = 0; + //第三方 + public static readonly short Other = 1; + //组态3 + public static readonly short Config = 2; + //看板 + public static readonly short Board = 3; + //第三方嵌入 + public static readonly short OtherEmbed = 4; + //组态4 + public static readonly short Config4 = 5; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs new file mode 100644 index 0000000..cae0780 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public enum MsgServiceEnum + { + + } + /// + /// 服务商 + /// + public enum MsgServiceProviderEnum + { + /// + /// 自定义 + /// + Custom = 1, + /// + /// 阿里云 + /// + Aliyun = 2 + } + /// + /// 服务商 + /// + public enum MsgServiceTypeEnum + { + /// + /// 自定义 + /// + Custom = 0, + /// + /// 阿里云 + /// + Aliyun = 1 + } + public enum MsgTemplateTypeEnum + { + /// + /// 站内消息 + /// + [Description("站内消息")] + Internal = 1, + /// + /// 短信 + /// + [Description("短信")] + SMS = 2, + /// + /// App + /// + [Description("App")] + App = 3, + /// + /// 语音 + /// + [Description("语音")] + Voice = 4 + } + public enum MsgServiceApplyEnum + { + [Description("邮件")] + Email = 1, + [Description("短信")] + SMS = 2, + [Description("APP")] + App = 3, + [Description("语音")] + Voice = 4 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs new file mode 100644 index 0000000..6b5475f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class NlogTypeNum + { + //普通日志 + public static readonly int Normal = 1; + //设备操作日志 + public static readonly int EquipControl = 2; + //设备超权日志 + public static readonly int EquipPress = 3; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs new file mode 100644 index 0000000..99341cb --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class NormUnitNum + { + /// + /// 每平方米年均能耗千瓦时 + /// + public static string YearAvergAqueraEnergyKwh = "kWh/(㎡*a)"; + + public static string YearAvergAqueraEnergyGJ = "GJ/(㎡*a)"; + public static string YearAvergAqueraEnergyKgce = "kgce/(㎡*a)"; + public static string YearAvergAqueraEnergyNm3 = "Nm³/(㎡*a)"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs new file mode 100644 index 0000000..7fbd4c4 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 付款方式 + /// + public enum PayMethodEnum + { + /// + /// 微信付款码 + /// + WxAuthCode = 1, + /// + /// 微信支付 + /// + Wx = 2, + /// + /// 现金 + /// + Cash = 3 + } + public enum PayOrderStateEnum + { + Unpaid = 0, + Paid = 1, + } + /// + /// 付款结果 + /// + public enum PayResultEnum + { + Success = 1, + Fail = 2 + } + public enum PayCustomerTypeEnum + { + /// + /// 供热 + /// + HeatMeter = 1 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs new file mode 100644 index 0000000..de8ff75 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public enum ProAlarmLevelEnum + { + /// + /// 重大 - 最高级别,需要立即处理 + /// + [Description("重大")] + Critical = 1, + + /// + /// 严重 - 严重问题,需尽快处理 + /// + [Description("严重")] + Major = 2, + + /// + /// 一般 - 中等优先级,需跟踪处理 + /// + [Description("一般")] + Minor = 3, + + /// + /// 轻微 - 低优先级,观察即可 + /// + [Description("轻微")] + Warning = 4 + } + public enum ProAlarmStatus + { + /// + /// 未处理 - 报警尚未被查看或确认 + /// + [Description("未处理")] + Unhandled = 0, + + /// + /// 处理中 - 报警已被确认,处理进行中 + /// + [Description("处理中")] + InProgress = 1, + + /// + /// 无需处理 - 判断无需干预或响应 + /// + [Description("无需处理")] + NoActionRequired = 2, + + /// + /// 误报 - 报警是错误的或无效的 + /// + [Description("误报")] + FalseAlarm = 3, + + /// + /// 已完成 - 报警处理流程已完成 + /// + [Description("已完成")] + Completed = 4 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs new file mode 100644 index 0000000..6cf32a0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core +{ + public class RealDataValueTypeEnum : Enumeration + { + public RealDataValueTypeEnum(int value, string displayName) : base(value, displayName) + { + } + public static readonly RealDataValueTypeEnum allEnum = new RealDataValueTypeEnum(0, nameof(boolEnum).ToLowerInvariant()); + //1. 开关量 + public static readonly RealDataValueTypeEnum boolEnum = new RealDataValueTypeEnum(1, nameof(boolEnum).ToLowerInvariant()); + //2. 十进制码 + public static readonly RealDataValueTypeEnum intEnum = new RealDataValueTypeEnum(2, nameof(intEnum).ToLowerInvariant()); + //3. 01串 + public static readonly RealDataValueTypeEnum stringEnum = new RealDataValueTypeEnum(3, nameof(stringEnum).ToLowerInvariant()); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RequestBackStatuEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RequestBackStatuEnum.cs new file mode 100644 index 0000000..3c56130 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RequestBackStatuEnum.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace WeiCloud.Core +{ + public class RequestBackStatuEnum:Enumeration + { + private RequestBackStatuEnum(int value, string displayName) : base(value, displayName) { + + } + /// + /// 操作成功 + /// + public static readonly RequestBackStatuEnum success = new RequestBackStatuEnum(200, nameof(success).ToLowerInvariant()); + /// + /// 自定义msg + /// + public static readonly RequestBackStatuEnum diy = new RequestBackStatuEnum(2000, nameof(diy).ToLowerInvariant()); + /// + /// 不存在指定对象 + /// + public static readonly RequestBackStatuEnum notexist = new RequestBackStatuEnum(2001, nameof(notexist).ToLowerInvariant()); + /// + /// 已存在指定对象 + /// + public static readonly RequestBackStatuEnum exist = new RequestBackStatuEnum(2002, nameof(exist).ToLowerInvariant()); + /// + /// 已存在指定条件的数据集 + /// + public static readonly RequestBackStatuEnum hasdata = new RequestBackStatuEnum(2003, nameof(hasdata).ToLowerInvariant()); + /// + /// 不存在指定条件的数据集 + /// + public static readonly RequestBackStatuEnum nodata = new RequestBackStatuEnum(2004, nameof(nodata).ToLowerInvariant()); + /// + /// 服务端处理错误 + /// + public static readonly RequestBackStatuEnum fail = new RequestBackStatuEnum(2005, nameof(fail).ToLowerInvariant()); + /// + /// 请求失败 + /// + public static readonly RequestBackStatuEnum badrequest = new RequestBackStatuEnum(2006, nameof(badrequest).ToLowerInvariant()); + /// + /// 未找到指定接口 + /// + public static readonly RequestBackStatuEnum notfound = new RequestBackStatuEnum(2007, nameof(notfound).ToLowerInvariant()); + /// + /// 网络连接失败 + /// + public static readonly RequestBackStatuEnum loselink = new RequestBackStatuEnum(2008, nameof(loselink).ToLowerInvariant()); + /// + /// 没有权限 + /// + public static readonly RequestBackStatuEnum unauthorized = new RequestBackStatuEnum(401, nameof(unauthorized).ToLowerInvariant()); + /// + /// 失效用户 + /// + public static readonly RequestBackStatuEnum expireUser = new RequestBackStatuEnum(4001, nameof(unauthorized).ToLowerInvariant()); + /// + /// 需要wx同意获取手机号才能登录 + /// + public static readonly RequestBackStatuEnum wx_need_get_phone_by_code = new RequestBackStatuEnum(3001, nameof(wx_need_get_phone_by_code).ToLowerInvariant()); + + public static IEnumerable List() => + new[] { success, badrequest, notfound, loselink }; + + public static RequestBackStatuEnum From(int value) + { + var state = List().SingleOrDefault(s => s.Value == value); + + if (state == null) + { + throw new Exception($"Possible values for Volume: {String.Join(",", List().Select(s => s.Value))}"); + } + + return state; + } + + public static RequestBackStatuEnum FromName(string name) + { + var state = List() + .SingleOrDefault(s => String.Equals(s.DisplayName, name, StringComparison.CurrentCultureIgnoreCase)); + + if (state == null) + { + throw new Exception($"Possible values for Volume: {String.Join(",", List().Select(s => s.DisplayName))}"); + } + + return state; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs new file mode 100644 index 0000000..875600b --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 指标枚举值 + /// + public class STTargetCategoryEnum : Enumeration2 + { + + /// + /// 能效体检冷源类型数据分类 + /// + public static readonly STTargetCategoryEnum ColdSourceType = new STTargetCategoryEnum(6, "冷源类型"); + + + /// + /// 能源体检指标名称数据分类 + /// + public static readonly STTargetCategoryEnum EnergyExamTargetNameType = new STTargetCategoryEnum(9, "能源体检指标名称数据"); + + + private STTargetCategoryEnum(int value, string displayName) : base(value, displayName) + { + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs new file mode 100644 index 0000000..ab7ee65 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs @@ -0,0 +1,619 @@ +using Google.Protobuf.WellKnownTypes; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + + /// + /// 报警处置状态枚举 + /// + public class AlarmStatusEnum : Enumeration2 + { + + public static readonly AlarmStatusEnum NoAccept = new AlarmStatusEnum(0, "未受理"); + public static readonly AlarmStatusEnum Accepted = new AlarmStatusEnum(1, "已受理"); + public static readonly AlarmStatusEnum HasSendWork = new AlarmStatusEnum(2, "已派工"); + public static readonly AlarmStatusEnum FinishedJob = new AlarmStatusEnum(3, "已完成"); + + + private AlarmStatusEnum(int value, string displayName) : base(value, displayName) + { + } + } + + + + //m, 逗号11 + + + /// + /// 报警受理结果枚举 + /// + public class AlarmAcceptRes : Enumeration2 + { + + + /// + /// 确警 + /// + public static readonly AlarmAcceptRes AlarmYes = new AlarmAcceptRes(1, "确警"); + + /// + /// 误报 + /// + public static readonly AlarmAcceptRes AlarmFalse = new AlarmAcceptRes(2, "误报"); + + /// + /// 演习 + /// + public static readonly AlarmAcceptRes AlarmDrill = new AlarmAcceptRes(3, "演习"); + + + private AlarmAcceptRes(int value, string displayName) : base(value, displayName) + { + } + } + + + + + /// + /// 消防预案执行状态枚举 + /// + public class ExeStatusEnum : Enumeration2 + { + /// + /// 未开始 + /// + public static readonly ExeStatusEnum NoBegin = new ExeStatusEnum(1, "未开始"); + + /// + /// 进行中 + /// + public static readonly ExeStatusEnum Exeing = new ExeStatusEnum(2, "进行中"); + + /// + /// 已完成 + /// + public static readonly ExeStatusEnum ExeOver = new ExeStatusEnum(3, "已完成"); + + + private ExeStatusEnum(int value, string displayName) : base(value, displayName) + { + } + } + + + /// + /// 预案流程步骤执行状态枚举 + /// + public class PlanProcessStepEnum : Enumeration2 + { + //[{"Key":1,"Value":"报警推送"},{"Key":2,"Value":"确警推送"},{ "Key":3,"Value":"拨打报警电话"},{ "Key":4,"Value":"派送任务至应急队伍"},{ "Key":5,"Value":"派送任务至附近人员"}] + + /// + /// 报警推送 + /// + public static readonly PlanProcessStepEnum AlarmPush = new PlanProcessStepEnum(1, "报警推送"); + + /// + /// 确警推送 + /// + public static readonly PlanProcessStepEnum AlarmYesPush = new PlanProcessStepEnum(2, "确警推送"); + + /// + /// 拨打报警电话 + /// + public static readonly PlanProcessStepEnum AlarmCall = new PlanProcessStepEnum(3, "拨打报警电话"); + + /// + /// 派送任务至应急队伍 + /// + public static readonly PlanProcessStepEnum SendToEmergency = new PlanProcessStepEnum(4, "派送任务至应急队伍"); + + /// + /// 派送任务至附近人员 + /// + public static readonly PlanProcessStepEnum SendToNearby = new PlanProcessStepEnum(5, "派送任务至附近人员"); + + + + + private PlanProcessStepEnum(int value, string displayName) : base(value, displayName) + { + } + } + + /// + /// 预案流程执行动作枚举 + /// + public class PushTypeEnum : Enumeration2 + { + + + /// + /// 自动 + /// + public static readonly PushTypeEnum Auto = new PushTypeEnum(1, "自动"); + + /// + /// 手动 + /// + public static readonly PushTypeEnum Manual = new PushTypeEnum(2, "手动"); + + + + + private PushTypeEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + /// + /// 警情级别 + /// + public class AlarmLevelEnum : Enumeration2 + { + + //[{"Key":1,"Value":"紧急"},{"Key":2,"Value":"重要"},{ "Key":3,"Value":"一般"},{ "Key":4,"Value":"轻微"}] + + /// + /// 紧急 + /// + public static readonly AlarmLevelEnum Urgency = new AlarmLevelEnum(1, "紧急"); + + /// + /// 重要 + /// + public static readonly AlarmLevelEnum Importance = new AlarmLevelEnum(2, "重要"); + + /// + /// 一般 + /// + public static readonly AlarmLevelEnum Ordinary = new AlarmLevelEnum(3, "一般"); + + /// + /// 轻微 + /// + public static readonly AlarmLevelEnum Slight = new AlarmLevelEnum(4, "轻微"); + + + + + private AlarmLevelEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + + + /// + /// 预案流程执行动作枚举 + /// + public class CallStatusEnum : Enumeration2 + { + + + /// + /// 接通 + /// + public static readonly CallStatusEnum Auto = new CallStatusEnum(1, "接通"); + + /// + /// 未接通 + /// + public static readonly CallStatusEnum Manual = new CallStatusEnum(2, "未接通"); + + + + + private CallStatusEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + + /// + /// 出入口设备类型 + /// + public class CarAssetTypeEnum : Enumeration2 + { + + /// + /// 入场 + /// + public static readonly CarAssetTypeEnum Entry = new CarAssetTypeEnum(1, "入场"); + + /// + /// 出场 + /// + public static readonly CarAssetTypeEnum Out = new CarAssetTypeEnum(2, "出场"); + + private CarAssetTypeEnum(int value, string displayName) : base(value, displayName) + { + } + } + + /// + /// 车辆设备类型 1未出场 2已出场 + /// + public class CarStatusEnum : Enumeration2 + { + + /// + /// 未出场 + /// + public static readonly CarStatusEnum InPark = new CarStatusEnum(1, "未出场"); + + /// + /// 已出场 + /// + public static readonly CarStatusEnum OutPark = new CarStatusEnum(2, "已出场"); + + private CarStatusEnum(int value, string displayName) : base(value, displayName) + { + } + } + + + /// + /// 巡检要点类型 + /// + public class KeyPointTypeEnum : Enumeration2 + { + + + /// + /// 无 + /// + public static readonly KeyPointTypeEnum NoThing = new KeyPointTypeEnum(1, "无"); + + /// + /// 数值填空 + /// + public static readonly KeyPointTypeEnum NumericalRangeFilling = new KeyPointTypeEnum(2, "数值填空"); + + /// + /// 选项填空 + /// + public static readonly KeyPointTypeEnum OptionFilling = new KeyPointTypeEnum(3, "选项填空"); + + /// + /// 文本填空 + /// + public static readonly KeyPointTypeEnum TextFilling = new KeyPointTypeEnum(4, "文本填空"); + + private KeyPointTypeEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + /// + /// 巡检要点类型 + /// + public class TaskPointTypeEnum : Enumeration2 + { + + + /// + /// 设备任务点 + /// + public static readonly TaskPointTypeEnum AssetType = new TaskPointTypeEnum(1, "设备任务点"); + + /// + /// 空间任务点 + /// + public static readonly TaskPointTypeEnum PositionType = new TaskPointTypeEnum(2, "空间任务点"); + + /// + /// 风险点任务点 + /// + public static readonly TaskPointTypeEnum FxType = new TaskPointTypeEnum(3, "风险点任务点"); + + + private TaskPointTypeEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + + + /// + /// 任务计划周期类型 + /// + public class PeriodTypeDescEnum : Enumeration2 + { + + + /// + /// 单次 + /// + public static readonly PeriodTypeDescEnum Once = new PeriodTypeDescEnum(1, "单次"); + + /// + /// 每日 + /// + public static readonly PeriodTypeDescEnum Daily = new PeriodTypeDescEnum(2, "每日"); + + /// + /// 每周 + /// + public static readonly PeriodTypeDescEnum Weekly = new PeriodTypeDescEnum(3, "每周"); + + /// + /// 每月 + /// + public static readonly PeriodTypeDescEnum Monthy = new PeriodTypeDescEnum(4, "每月"); + + /// + /// 每季度 + /// + public static readonly PeriodTypeDescEnum Quarterly = new PeriodTypeDescEnum(5, "每季度"); + + /// + /// 每年 + /// + public static readonly PeriodTypeDescEnum Yearly = new PeriodTypeDescEnum(6, "每年"); + + + private PeriodTypeDescEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + + // 0未开始 1未完成 2已完成 3已超时 + /// + /// 任务计划周期类型 + /// + public class XjTaskInstanceExeStatusEnum : Enumeration2 + { + + + /// + /// 未开始 + /// + public static readonly XjTaskInstanceExeStatusEnum NoBegin = new XjTaskInstanceExeStatusEnum(0, "未开始"); + + /// + /// 未完成 + /// + public static readonly XjTaskInstanceExeStatusEnum NoCompleted = new XjTaskInstanceExeStatusEnum(1, "未完成"); + + /// + /// 已完成 + /// + public static readonly XjTaskInstanceExeStatusEnum Compeleted = new XjTaskInstanceExeStatusEnum(2, "已完成"); + + /// + /// 已超时 + /// + public static readonly XjTaskInstanceExeStatusEnum Timeout = new XjTaskInstanceExeStatusEnum(3, "已超时"); + + private XjTaskInstanceExeStatusEnum(int value, string displayName) : base(value, displayName) + { + } + + + } + + + /// + /// 巡检结果 + /// + public class InspectResultEnum : Enumeration2 + { + /// + /// 已巡 + /// + public static readonly InspectResultEnum HasInspect = new InspectResultEnum(1, "已巡"); + + /// + /// 未巡 + /// + public static readonly InspectResultEnum NoInspect = new InspectResultEnum(0, "未巡"); + + + + private InspectResultEnum(int value, string displayName) : base(value, displayName) + { + } + + } + + + + /// + /// 巡检是否合格 + /// + public class ScanResultEnum : Enumeration2 + { + /// + /// 已巡 + /// + public static readonly ScanResultEnum Pass = new ScanResultEnum(1, "合格"); + + /// + /// 未巡 + /// + public static readonly ScanResultEnum NoPass = new ScanResultEnum(0, "不合格"); + + + + private ScanResultEnum(int value, string displayName) : base(value, displayName) + { + } + + } + + + + /// + /// 警情上报临界值是否在阈值内 + /// + public class OperatorEnum : Enumeration2 + { + + /// + /// 等于 + /// + public static readonly OperatorEnum EQ = new OperatorEnum("=", "等于"); + + /// + /// 不等于 + /// + public static readonly OperatorEnum NE = new OperatorEnum("!=", "不等于"); + + /// + /// 小于 + /// + public static readonly OperatorEnum LT = new OperatorEnum("<", "小于"); + + /// + /// 小于等于 + /// + public static readonly OperatorEnum LE = new OperatorEnum("<=", "小于等于"); + + /// + /// 大于 + /// + public static readonly OperatorEnum GT = new OperatorEnum(">", "大于"); + + /// + /// 大于等于 + /// + public static readonly OperatorEnum GE = new OperatorEnum(">=", "大于等于"); + + + private OperatorEnum(string value, string displayName) : base(value, displayName) + { + } + + } + + //m, wdds + + /// + /// 工单状态 + /// + public class WoOrderStatusEnum : Enumeration2 + { + //m,指数/产品排序/,3001 + //m, 逗号11222 + /// + /// 未派工 + /// + public static readonly WoOrderStatusEnum Created = new WoOrderStatusEnum(1, "未派工"); + + + /// + /// 已派工 + /// + public static readonly WoOrderStatusEnum HasDistributed = new WoOrderStatusEnum(2, "已派工"); + + + /// + /// 部分完工 + /// + public static readonly WoOrderStatusEnum PartFinished = new WoOrderStatusEnum(3, "部分完工"); + + /// + /// 已完工 + /// + public static readonly WoOrderStatusEnum Finished = new WoOrderStatusEnum(4, "已完工"); + + /// + /// 已挂单 + /// + public static readonly WoOrderStatusEnum HangingOrder = new WoOrderStatusEnum(5, "已挂单"); + + /// + /// 已取消 + /// + public static readonly WoOrderStatusEnum Canceled = new WoOrderStatusEnum(6, "已取消"); + + + + private WoOrderStatusEnum(int value, string displayName) : base(value, displayName) + { + } + } + + + /// + /// 工单类型 + /// + + public class WoOrderTypeEnum : Enumeration2 + { + //1:警情处置 2:设备维修 3:设备保养 + + /// + /// 警情处置 + /// + public static readonly WoOrderTypeEnum AlarmDeal = new WoOrderTypeEnum(1, "警情处置"); + + + /// + /// 设备维修 + /// + public static readonly WoOrderTypeEnum AssetMaintain = new WoOrderTypeEnum(2, "设备维修"); + + + /// + /// 设备保养 + /// + public static readonly WoOrderTypeEnum AssetKeepInGood = new WoOrderTypeEnum(3, "设备保养"); + + + private WoOrderTypeEnum(int value, string displayName) : base(value, displayName) + { + } + } + + + /// + /// 工单来源 + /// + + public class WoOrderSourceEnum : Enumeration2 + { + + //1:事件报警 2:巡检报修 3:设备报警 + + /// + /// 事件报警 + /// + public static readonly WoOrderSourceEnum EventAlarm = new WoOrderSourceEnum(1, "事件报警"); + + /// + /// 巡检报修 + /// + public static readonly WoOrderSourceEnum AssetCheck = new WoOrderSourceEnum(2, "巡检报修"); + + /// + /// 设备报警 + /// + public static readonly WoOrderSourceEnum AssetAlarm = new WoOrderSourceEnum(3, "设备报警"); + + + private WoOrderSourceEnum(int value, string displayName) : base(value, displayName) + { + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs new file mode 100644 index 0000000..0c01c16 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 标煤换算 ccx 2020-09-17 + /// + public static class StandardCoalEnum + { + /// + /// 电能换算标煤 1 kWh=0.123 标煤 + /// + public static readonly double Electronic = 0.123; + /// + ///水能换算标煤 1t=0.086 标煤 + /// + public static readonly double Water = 0.086; + /// + /// 气能换算标煤 1 m³ =1.330 标煤 + /// + public static readonly double Gas = 1.330; + /// + /// 热力(当量值) kgce/MJ 0.03412 + /// + public static readonly double Heat = 0.034; + /// + /// 标煤换算二氧化碳 1吨标煤能量=2.6885吨CO2 + /// + public static readonly double CO2 = 2.6885; + /// + /// 每亩树林年减排CO2 1.336吨 + /// + public static readonly double EngeryChangeCO2 = 1.336; + /// + /// 亩换算公顷 1亩=0.0667公顷 + /// + public static readonly double MuChangeHectare = 0.0667; + + } + /// + /// 等效电法折算 + /// + public static class EquivalentElectricEnum + { + public static readonly double Water = 0; + /// + /// 气转电kWh + /// + public static readonly double Gas = 10;//7.133; + + public static readonly double StandardCoal = 3.691; + /// + /// 原煤 + /// + public static readonly double RawCoal = 2.640; + /// + /// 原油 + /// + public static readonly double Crude = 7.663; + /// + /// 柴油 + /// + public static readonly double DieselOil = 1.4571; + } + public class StandardCoalEnumNew + { + /// + /// 电能换算标煤 1 kWh=0.326 kg 标煤 + /// + public static readonly double Electronic = 0.326; + ///// + /////水能换算标煤 tce/m3 标煤 + ///// + public static readonly double Water = 0.0000857; + /// + /// 气能换算标煤 1 m³ =1.2286kg标煤 + /// + public static readonly double Gas = 1.2286; + /// + /// 柴油 1吨油当量=1.4286吨标准煤 + /// + public static readonly double Oil = 1.4286; + /// + /// 蒸汽 tce/ton + /// + public static readonly double Stream = 0.1286; + /// + /// 煤气 tce/m3 + /// + public static readonly double CoalGas = 0.00133; + /// + /// 热水 tce/m3 + /// + public static readonly double HotWater = 0.0000857; + /// + /// 1kWh= 0.0036GJ + /// + public static readonly double HotGJ = 0.0036; + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs new file mode 100644 index 0000000..23a5196 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 全局参数名称 + /// + public static class SyaConfigNameEnum + { + /// + /// 集团云平台名称 + /// + public static readonly string OrganizationName = "OrganizationName"; + /// + /// 集团云平台中文名称 + /// + public static readonly string OrganizationChinaName = "集团云平台名称"; + /// + /// 项目云平台名称 + /// + public static readonly string ProjectStageName = "ProjectStageName"; + /// + /// 项目云平台中文名称 + /// + public static readonly string ProjectStageChinaName = "项目云平台名称"; + /// + /// 平台Logo + /// + public static readonly string StageLogo = "StageLogo"; + /// + /// 平台Logo中文名称 + /// + public static readonly string StageLogoLable = "平台Logo"; + /// + /// 系统参数类型 + /// + public static readonly long ConfigType = 0; + + public static readonly string Showlable = "是否显示网站备案信息"; + public static readonly string IsShow = "IsShowRecord"; + //public static readonly short? Show; + public static readonly string ShowMessagelable = "是否显示网站备案信息"; + public static readonly string ShowMessage = "RecordMessage"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs new file mode 100644 index 0000000..a0ff828 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + /// + /// 系统元数据 + /// + public class SysBaseCodeMeta + { + /// + /// 类别 + /// + public static readonly string ProjectCodeTypePrefix = "pj"; + + public static readonly string ConstCodeTypePrefix = "cs"; + + public static readonly string AdminCode = "rl001"; + public static readonly string OwnerAdminCode = "rl002"; + + + //sysConfig + public static readonly int ParamType = 3; + /// + /// 碳排放因子 + /// + public static readonly long CarbonEmissionFactor = 506405592524320; + + //菜单 + public static readonly string MenuCode_YXJK = "c001";//运行监控 + public static readonly string MenuCode_PZGL = "x001";//配置管理 + /// + /// 管理员业主Id + /// + + public static readonly long AdminOwnerId = 0; + /// + /// 模块菜单关联 + /// + + public static readonly string SysModuleMenuMapHashId = "SysModuleMenuMap"; + #region 分组类型 + /// + /// 组-冷温水供水&回水温度 + /// + public static readonly short GroupType_LWS = 4; + /// + /// 组-冷却水供水&回水温度 + /// + public static readonly short GroupType_LQS = 5; + /// + /// 组-室外气象温度 + /// + public static readonly short GroupType_SWQX = 6; + + /// + /// 组-总能耗气 + /// + public static readonly short GroupType_ZNH_Q = 7; + /// + /// 组-总能耗电 + /// + public static readonly short GroupType_ZNH_D = 8; + + + /// + /// 组-主机-表 + /// + public static readonly short GroupType_ZJ_B = 9; + + /// + /// 组-系统-表 + /// + public static readonly short GroupType_XT_B = 10; + + /// + /// 组-室内空气传感器 + /// + public static readonly short GroupType_SNKQ = 11; + + + #endregion + + #region 企业 + public static readonly short EnterpriseType_Owner = 0;//业主 + public static readonly short EnterpriseType_PlatformManager = 1;//平台 + public static readonly short EnterpriseType_ThirdParty = 2;//第三方运维公司 + #endregion + + #region 系统诊断 + /// + /// 能效配置 + /// + public static readonly short SysDiagnosis_ConfigType_EnergyEffic = 1; + /// + /// 诊断配置 + /// + public static readonly short SysDiagnosis_ConfigType_Diagnosis = 2; + + /// + /// 优良值 + /// + public static readonly short SysDiagnosis_ValueType_YL = 1; + /// + /// 较差值 + /// + public static readonly short SysDiagnosis_ValueType_JC = 2; + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs new file mode 100644 index 0000000..b87abd8 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class SysModuleEnum + { + public const string FilePath = "sysmodule"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs new file mode 100644 index 0000000..78d6d77 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + internal class TaskApiEnum + { + } + public enum TimeTypeEnum + { + Hour = 1, + Day = 2, + Month = 3 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs new file mode 100644 index 0000000..179964e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core +{ + /// + /// 租户费用支付方式 + /// + public static class TenantPayWayEnum + { + /// + /// 线下支付 + /// + public static readonly short Offline = 1; + /// + /// 线上支付 + /// + public static readonly short ONline = 2; + } + public static class TenantPayTypeEnum + { + /// + /// 预付费 + /// + public static readonly int PrePay = 1; + /// + /// 线上支付 + /// + public static readonly int LastPay = 2; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs new file mode 100644 index 0000000..caad043 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class TimeSpanEnum + { + /// + /// 5分钟 + /// + public static readonly short FiveMinute = 5; + /// + /// 10分钟 + /// + public static readonly short TenMinute = 10; + /// + /// 半小时 + /// + public static readonly short HalfHour = 30; + /// + /// 一小时 + /// + public static readonly short Hour = 60; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs new file mode 100644 index 0000000..88fda4d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + internal class UserCenterApiEnum + { + } + /// + /// 账号登录状态 + /// + public enum AccountLoginEnum + { + /// + /// 在线 + /// + Online = 1, + /// + /// 离线 + /// + Offline = 2 + } + public enum UserMapClientTypeEnum + { + App = 1, + PC = 2, + SMS = 3 + } + //消息类型:1.工单 2.知识库,3.报警,4.计划,5.物业 6.场景通知消息 + public enum MsgTypeEnum + { + [Description("工单")] + WorkOrder = 1, + [Description("知识库")] + Knowledge = 2, + [Description("设备报警")] + Alarm = 3, + [Description("计划任务")] + Plan = 4, + [Description("物业通知")] + Scene = 5, + [Description("通知消息")] + Notice = 6, + [Description("场景通知消息")] + SceneNotice = 7, + [Description("安消报警")] + SafeFireProAlarm = 8, //消防报警 + } + public enum SysModuleTypeEnum + { + /// + /// 平台模块 + /// + Platform = 1, + /// + /// 项目模块 + /// + Project = 2, + /// + /// 个人中心 + /// + PersonCenter = 3 + } + /// + /// 日志分类 + /// + public enum LogTypeEnum + { + /// + /// 登录 + /// + Login = 1, + /// + /// 控制 + /// + Control = 2, + /// + /// 操作(模块功能) + /// + ModuleOper = 3, + /// + /// 用户行为 + /// + CustomerBehavior = 4 + } + public enum TerminalTypeEnum + { + /// + /// PC端 + /// + PC = 1, + /// + /// 移动端 + /// + APP = 2, + /// + /// 中控屏 + /// + CentralControlScreen = 3 + } + #region 中控屏 + public enum ConformHomeIdentityCodeEnum + { + + } + public class ConformHomeEnum + { + /// + /// 中控屏角色 + /// + public static readonly long CentralControlScreenRoleId = 509639289174048; + } + #endregion +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs new file mode 100644 index 0000000..3ce8224 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EnumTools +{ + public static class WorkOrderProConfig + { + + } + /// + /// 备品备件工单流程类型枚举 + /// + public static class ETEquipPartWorkOrderEnum + { + /// + /// 出库工单 + /// + public const short OutWorkOrder=1; + /// + /// 入库工单 + /// + public const short InWorkOrder = 2; + /// + /// 外借工单 + /// + public const short BorrowWorkOrder = 3; + } + /// + /// 计划管理工单流程类型枚举 + /// + public static class MaintenPLanWorkOrderEnum + { + /// + /// 巡检工单 + /// + public const short InspectionWorkOrder = 1; + /// + /// 维保工单 + /// + public const short MaintenanceWorkOrder = 2; + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/说明.txt b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/说明.txt new file mode 100644 index 0000000..32fa735 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/说明.txt @@ -0,0 +1,26 @@ +------ 枚举类文件说明 ccx 2022-2-17----- + +空气质量类型枚举 ------ AirQuantityEnum +建筑物类型枚举 ------ ConstTypeEnum +能耗分项类型枚举 ------ EnergyItemEnum +能源计费方式枚举 ------ EngeryBillingType +能源类型(水电气)枚举 ------ EngeryTypeEnum +系统类型枚举 ------ EnumSystemModel +设备分组类型枚举 ------ EqGroupTypeEnum +设备运行状态枚举 ------ EquipRuningStatus +设备类型枚举 ------ EquipTypeEnum +国润丰泽角色id枚举 ------ FamilyDecorationEnum +报警类型枚举 ------ FamilyDecorationEnum +报警处理方式类型枚举 ------ FaultHandleEnum +报警状态枚举 ------ FaultStatusEnum +控制面板挡位枚举 ------ GearEnum +人工抄表时间枚举 ------ HandWritetenEnum +知识库的多种枚举 ------ KBEnum +日志类型枚举 ------ NlogTypeNum +后端返回code枚举 ------ RequestBackStatuEnum +能源转标煤换算枚举 ------ StandardCoalEnum +全局参数名称枚举 ------ SyaConfigNameEnum +元数据枚举 ------ SysBaseCodeMeta +文件路径枚举 ------ SysModuleEnum +租户费用支付方式枚举 ------ TenantPayWayEnum +查询数据时间间隔枚举 ------ TimeSpanEnum diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs new file mode 100644 index 0000000..99e6a46 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using AutoMapper.Configuration; +using DotNetCore.CAP; +using Microsoft.Extensions.Logging; +using WeiCloud.Core.EventBus; +using Newtonsoft.Json; +using Microsoft.Extensions.Configuration; +using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration; + +namespace WeiCloud.Core.EventBus +{ + public class CapPublisherService : IPublisherService + { + private readonly ICapPublisher _capPublisher; + private readonly ILogger _logger; + private readonly IConfiguration _configuration; + public CapPublisherService(ICapPublisher capPublisher, ILogger logger,IConfiguration configuration) + { + _capPublisher = capPublisher ?? throw new ArgumentNullException(nameof(capPublisher)); + _logger = logger ?? throw new ArgumentNullException(nameof(_logger)); + _configuration = configuration ?? throw new ArgumentNullException(nameof(_configuration)); + } + + public async Task PublishNoticeMsg(ProduceMsgModel notice) + { + notice.MsgTopic = "msgcenter.services.msg.notice"; + await _capPublisher.PublishAsync("msgcenter.services.msg.notice", notice); + + } + + public async Task PublishNoticeMsgByApi(ProduceMsgModel notice) + { + notice.MsgTopic = "msgcenter.services.msg.notice"; + if (string.IsNullOrEmpty(notice.Extend))//Extend不为空 + { + notice.Extend = ""; + + } + var message2 = JsonConvert.SerializeObject(notice); + string result = string.Empty; + Uri postUrl = new Uri(_configuration["CapPublishUrl"]); + + using (HttpContent httpContent = new StringContent(message2)) + { + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + using (var httpClient = new HttpClient()) + { + httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8"); + httpClient.Timeout = new TimeSpan(0, 0, 30); + HttpResponseMessage responseMessage = await httpClient.PostAsync(postUrl, httpContent); + if (responseMessage.IsSuccessStatusCode) + { + result = responseMessage.Content.ReadAsStringAsync().Result; + } + else + { + result = ""; + } + } + } + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs new file mode 100644 index 0000000..adcd3e6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EventBus +{ + public class ProduceMsgModel + { + public List UserIds { get; set; } + public long? EquId { get; set; } + public long Id { get; set; } + public string Content { get; set; } + public long? ProjectId { get; set; } + public string Title { get; set; } + public string Extend { get; set; } + public List SendTypes { get; set; } + public string MsgTopic { get; set; } + /// + /// 紧急程度 0正常 1紧急 2一般 3非常紧急 + /// + public short? EmergencyType { get; set; } = 0; + + /// + /// 消息类型1.工单 2.知识库,3.报警,4.计划 + /// + public short MsgType { get; set; } + + /// + /// 对应的业务Id + /// + public long? MainId { get; set; } + + /// + /// 设备名称 + /// + public string EquName { get; set; } + /// + /// 项目名称 + /// + public string ProjectName { get; set; } + /// + /// 项目简称 + /// + public string ProjectShortName { get; set; } + #region websocket + public string SubscribeAction { get; set; } + public string SubscribeFilter { get; set; } + #endregion + public DateTime CreatedAt { get; set; } = DateTime.Now; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs new file mode 100644 index 0000000..567192e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.DataModels; + +namespace WeiCloud.Core.EventBus +{ + public interface IBusinessMessageSubscriberEventBus + { + Task BusinessNoticeMsg(BusinessNoticeMsgDto message); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs new file mode 100644 index 0000000..555c15a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs @@ -0,0 +1,9 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.DataModels; + +namespace WeiCloud.Core.EventBus +{ + public interface IMessageSubscriberEventBus + { + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs new file mode 100644 index 0000000..08e9c15 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.EventBus +{ + /// + /// 消息总线 生产发布者 + /// + public interface IPublisherService + { + + public Task PublishNoticeMsgByApi(ProduceMsgModel notice); + /// + /// 发布通知消息 + /// + /// 消息内容 主要以 ProduceMsgModel + /// + public Task PublishNoticeMsg(ProduceMsgModel notice); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs new file mode 100644 index 0000000..2283c1f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs @@ -0,0 +1,134 @@ +using DotNetCore.CAP; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Threading.Tasks; +using WeiCloud.Core.Services.EquipPart; +using WeiCloud.Core.Services.Message; +using WeiCloud.Entity.LogicModels.DataModels; +using WeiCloud.Entity.LogicModels.EquipPart; + +namespace WeiCloud.Core.EventBus +{ + public class BusinessMessageSubscriberEventBus : IBusinessMessageSubscriberEventBus, ICapSubscribe + { + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + public BusinessMessageSubscriberEventBus(ILogger logger, IServiceScopeFactory serviceScopeFactory) + { + _logger = logger; + _serviceScopeFactory = serviceScopeFactory; + } + [CapSubscribe("info.services.business.msg")] + public async Task BusinessNoticeMsg(BusinessNoticeMsgDto message) + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"BusinessNoticeMsg in message:{JsonConvert.SerializeObject(message)}").GetNlogMessage().ToString()); + try + { + using var scope = _serviceScopeFactory.CreateScope(); + switch (message.BusinessType) + { + case 0: // 预留 暂时不处理 + break; + case 1: // 报警业务处理 + /*var faultHistoryService = ServiceLocator1.Instance.GetService(typeof(IFaultHistoryService)) as IFaultHistoryService; + await faultHistoryService.PutFaultHistoryReadStatus(businessMsg.BusinessId, 1);*/ + break; + case 2: // 巡检业务处理 + break; + case 3: // 维保业务处理 + break; + case 4: // 备品备件业务处理 + //调用service + _logger.LogInformation($"备品备件业务处理{JsonConvert.SerializeObject(message)}"); + var input = new ApproveItemModel + { + OrderId = message.OrderId, + ApplyId = message.BusinessId, + ApproverUserId = message.UserId, + ApproverTime = message.ExecTime, + Status = (short)message.Status + }; + var equipPartStockService = scope.ServiceProvider.GetRequiredService(); + await equipPartStockService.ApproveItem(input); + break; + default: + break; + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + } + public class MessageSubscriberEventBus : IMessageSubscriberEventBus, ICapSubscribe + { + + private readonly ILogger _logger; + private readonly IMessageService _messageService; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IMsgCenterCoreService _msgCenterCoreService; + public MessageSubscriberEventBus(ILogger logger, IMessageService messageService, IServiceScopeFactory serviceScopeFactory, IMsgCenterCoreService msgCenterCoreSerivce) + { + _logger = logger; + _messageService = messageService; + _serviceScopeFactory = serviceScopeFactory; + _msgCenterCoreService = msgCenterCoreSerivce; + } + //public MessageSubscriberEventBus(ILogger logger, IServiceScopeFactory serviceScopeFactory) + //{ + // _logger = logger; + // _serviceScopeFactory = serviceScopeFactory; + //} + +#if RELEASE + /// + /// 消息 + /// + /// + /// + + [CapSubscribe("msgcenter.services.msg.notice")] + public async Task SaveMsg(ProduceMsgModel dto) + { + try + { + var age = DateTime.Now - dto.CreatedAt; + + if (age > TimeSpan.FromMinutes(2)) + { + // 消息已过期,记录日志或直接忽略 + _logger.LogWarning("消息过期,已忽略: {MainId} {Id}, Age: {Age}", dto.MainId, dto.Id, age); + return; + } + await _messageService.SendMsg(dto); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } +#endif + + /// + /// 发送消息 + /// + /// + /// + [CapSubscribe("msgcenter.services.msgv2")] + public async Task ReceivedMsg(object msgObj) + { + try + { + MsgTempateEventDto msg = JsonConvert.DeserializeObject(msgObj.ToString()); + await _msgCenterCoreService.SendMsg(msg); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs new file mode 100644 index 0000000..9c17119 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs @@ -0,0 +1,32 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.EventBus +{ + public class MsgTempateEventDto + { + /// + /// 消息模板ID + /// + public string MsgTempateId { get; set; } + /// + /// 消息名称 + /// + public string? Title { get; set; } + /// + /// 属性值 + /// + //public JObject? Fields { get; set; } + public JToken? Fields { get; set; } + /// + /// 扩展信息 + /// + public object? Extend { get; set; } + /// + /// 用户ID + /// + public List UserIds { get; set; } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs new file mode 100644 index 0000000..31d611f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace WeiCloud.Core.EventBus +{ + public enum SendTypeMeta + { + [Description("App消息")] + AppMsg = 1, + [Description("PC消息")] + PcMsg = 2, + [Description("短信消息")] + SMSMsg = 3 + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs new file mode 100644 index 0000000..cd1cd8e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Core.NlogTools; + +namespace WeiCloud.Core.Extension +{ + public static class ExceptionExtension + { + #region 获取最底层异常 + /// + /// 获取最底层异常 + /// + public static Exception GetDeepestException(this Exception ex) + { + var innerException = ex.InnerException; + var resultExcpetion = ex; + while (innerException != null) + { + resultExcpetion = innerException; + innerException = innerException.InnerException; + } + + return resultExcpetion; + } + #endregion + + + #region 异常文本日志 + public static void WriteErrorLog(this Exception ex, string message, string platHost = "") + { + LoggerHelper.Error(message, ex, platHost: platHost); + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs new file mode 100644 index 0000000..54fb68c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Extension +{ + public class FriendlyException : Exception + { + + public FriendlyException(string friendlyMessage) : base(friendlyMessage) + { + } + + public FriendlyException(string friendlyMessage, Exception innerException) : base(friendlyMessage, innerException) + { + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs new file mode 100644 index 0000000..061d608 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Linq; +using System.Text; + +namespace WeiCloud.Core.Extension +{ + public static class IQueryableExtensions + { + public static IQueryable WhereIf(this IQueryable query, bool condition, Expression> predicate) + { + return condition + ? query.Where(predicate) + : query; + } + + + public static IQueryable TakePage(this IQueryable source, int pageSize, int pageIndex) => source.Skip((pageIndex - 1) * pageSize).Take(pageSize); + + + /// + /// 动态添加多个 OR 条件 + /// + /// 实体类型 + /// 查询对象 + /// 条件列表 + /// 包含动态 OR 条件的查询对象 + public static IQueryable WhereAny(this IQueryable query, IEnumerable>> conditions) + { + if (conditions == null || !conditions.Any()) + return query; + + // 动态构建 OR 条件 + Expression> combinedCondition = null; + + foreach (var condition in conditions) + { + if (combinedCondition == null) + { + combinedCondition = condition; // 第一个条件 + } + else + { + // 使用 Expression.OrElse 连接条件 + var newCondition = Expression.Lambda>( + Expression.OrElse( + combinedCondition.Body, + new ReplaceParameterVisitor(condition.Parameters[0], combinedCondition.Parameters[0]).Visit(condition.Body) + ), + combinedCondition.Parameters + ); + + combinedCondition = newCondition; + } + } + + return query.Where(combinedCondition); + } + + /// + /// 用于替换表达式参数的帮助类 + /// + private class ReplaceParameterVisitor : ExpressionVisitor + { + private readonly ParameterExpression _oldParameter; + private readonly ParameterExpression _newParameter; + + public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter) + { + _oldParameter = oldParameter; + _newParameter = newParameter; + } + + protected override Expression VisitParameter(ParameterExpression node) + { + if (node == _oldParameter) + return _newParameter; + return base.VisitParameter(node); + } + } + } + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs new file mode 100644 index 0000000..e8256b9 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace WeiCloud.Core.Extension +{ + public static class TryConvertExtension + { + #region 类型转换 + /// + /// string转int + /// + /// 输入 + /// 转换失败默认 + /// + public static int TryInt(this object input, int defaultNum = 0) + { + if (input == null) + { + return defaultNum; + } + + return int.TryParse(input.ToString(), out var num) ? num : defaultNum; + } + /// + /// string转long + /// + /// 输入 + /// 转换失败默认 + /// + public static long TryLong(this object input, long defaultNum = 0) + { + if (input == null) + { + return defaultNum; + } + + return long.TryParse(input.ToString(), out var num) ? num : defaultNum; + } + /// + /// string转double + /// + /// 输入 + /// 转换失败默认值 + /// + public static double TryDouble(this object input, double defaultNum = 0) + { + if (input == null) + { + return defaultNum; + } + + return double.TryParse(input.ToString(), out var num) ? num : defaultNum; + } + /// + /// string转decimal + /// + /// 输入 + /// 转换失败默认值 + /// + public static decimal TryDecimal(this object? input, decimal defaultNum = 0) + { + if (input == null) + { + return defaultNum; + } + + return decimal.TryParse(input.ToString(), out decimal num) ? num : defaultNum; + } + /// + /// string转decimal + /// + /// 输入 + /// 转换失败默认值 + /// + public static float TryFloat(this object input, float defaultNum = 0) + { + if (input == null) + { + return defaultNum; + } + + return float.TryParse(input.ToString(), out var num) ? num : defaultNum; + } + /// + /// string转bool + /// + /// 输入 + /// + /// 转换失败默认值 + /// + /// + public static bool TryBool(this object input, bool defaultBool = false, string trueVal = "1", string falseVal = "0") + { + if (input == null) + { + return defaultBool; + } + + var str = input.ToString(); + if (bool.TryParse(str, out var outBool)) + { + return outBool; + } + + outBool = defaultBool; + if (trueVal == str) + { + return true; + } + + if (falseVal == str) + { + return false; + } + + return outBool; + } + /// + /// 值类型转string + /// + /// 输入 + /// 转换失败默认值 + /// + public static string TryString(this ValueType inputObj, string defaultStr = "") + { + var output = inputObj == null ? defaultStr : inputObj.ToString(); + return output; + } + /// + /// 字符串转时间 + /// + /// 输入 + /// 默认值 + /// + public static DateTime TryDateTime(this string inputStr, DateTime defaultValue = default) + { + if (inputStr.IsNullOrEmpty()) + { + return defaultValue; + } + + try + { + var result = DateTime.TryParse(inputStr, out var outPutDateTime); + if (result) + { + return outPutDateTime; + } + + return DateTime.FromOADate(double.Parse(inputStr)); + } + catch + { + return defaultValue; + } + } + /// + /// 字符串转时间 + /// + /// 输入 + /// + /// 默认值 + /// + public static DateTime TryDateTime(this string inputStr, string formater, DateTime defaultValue = default) + { + if (inputStr.IsNullOrEmpty()) + { + return defaultValue; + } + + return DateTime.TryParseExact(inputStr, formater, CultureInfo.InvariantCulture, DateTimeStyles.None, out var outPutDateTime) ? outPutDateTime : defaultValue; + } + /// + /// 字符串去空格 + /// + /// 输入 + /// + public static string TryTrim(this string inputStr) + { + var output = inputStr.IsNullOrEmpty() ? inputStr : inputStr.Trim(); + return output; + } + /// + /// 字符串转枚举 + /// + /// 输入 + /// + /// + /// + public static T TryEnum(this string str, T t = default) where T : struct + { + return Enum.TryParse(str, out var result) ? result : t; + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs new file mode 100644 index 0000000..e284dc5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Filters +{ + /// + /// 忽略统一返回结果特性 + /// + public class ApiIgnoreAttribute : Attribute + { + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs new file mode 100644 index 0000000..c762a06 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs @@ -0,0 +1,75 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Filters +{ + /// + /// 统一返回数据 + /// + public class ApiResultFilter : Attribute, IActionFilter + { + /// + /// 执行方法体之后 + /// 返回结果为JsonResult的请求进行Result包装 + /// + /// + public void OnActionExecuted(ActionExecutedContext context) + { + //特殊处理:对有ApiIgnoreAttribute标签的,不进行返回结果包装,原样输出 + var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; + if (controllerActionDescriptor != null) + { + var isDefined = controllerActionDescriptor.EndpointMetadata.Any(a => a.GetType().Equals(typeof(ApiIgnoreAttribute))); + if (isDefined) + { + return; + } + + } + // 返回结果为JsonResult的请求进行Result包装 + if (context.Result != null) + { + + if (context.Result is ObjectResult) + { + var result = context.Result as ObjectResult; + string str = JsonConvert.SerializeObject(result.Value); + if (!str.Contains("\"Code\":") && !str.Contains("\"Msg\":")) + { + context.Result = new JsonResult(new { code =200, msg = "操作成功", data = result.Value }); + } + + } + else if (context.Result is EmptyResult) + { + context.Result = new JsonResult(new { code = 200, msg = "操作成功", data = new { } }); + } + else if (context.Result is ContentResult) + { + var result = context.Result as ContentResult; + context.Result = new JsonResult(new { code = 200, msg = result.Content }); + } + + + } + + } + + /// + /// 执行方法体之前 + /// + /// + public void OnActionExecuting(ActionExecutingContext context) + { + //不做修改 + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs new file mode 100644 index 0000000..f4973f3 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs @@ -0,0 +1,175 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using WeiCloud.Core.Common; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Utils; +using WeiCloud.Core.Services; +using WeiCloud.Core.Services.Permission; +using Castle.Core.Logging; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Microsoft.Extensions.DependencyInjection; +using System.IO; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using NewLife.Reflection; +using Autofac; + +namespace WeiCloud.Core.Filters +{ + internal class AuthActionFilter + { + } + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] + public class ActionAuthAttribute : System.Attribute + { + /// + /// 权限Id + /// + public long PermissionId { get; set; } + public ActionAuthAttribute(long permissionId) + { + PermissionId = permissionId; + } + public ActionAuthAttribute() + { + + } + } + public class ActionFilter : IActionFilter//ActionFilterAttribute + { + private readonly CurrentContext _currentContext; + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + public ActionFilter(IServiceScopeFactory serviceScopeFactory, ILogger logger, CurrentContext currentContext) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + _currentContext = currentContext; + } + + public void OnActionExecuted(ActionExecutedContext context) { } + + public void OnActionExecuting(ActionExecutingContext context) + { + try + { + var currentUser = _currentContext.GetContext(); + if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) + { + //var lifetimeScope = context.HttpContext.RequestServices.GetService(); + //var funPermissionCoreService = lifetimeScope.Resolve(); + + using var scope = _serviceScopeFactory.CreateScope(); + var funPermissionCoreService = scope.ServiceProvider.GetRequiredService(); + + #region 添加接口权限验证 + long projectId = 0; + //var projectIdStr = string.Empty; + context.HttpContext.Request.Headers.TryGetValue("projectid", out var projectIdHeader); + if (projectIdHeader.Any()) + { + if (long.TryParse(projectIdHeader.FirstOrDefault(), out long parsedProjectId)) + { + if (currentUser.ProjectIds.Contains(parsedProjectId)) + { + projectId = parsedProjectId; + } + } + } + IDictionary actionArguments = context.ActionArguments; + if (actionArguments != null) + { + string method = context.HttpContext.Request.Method.ToUpper(); + if (method == "GET") + { + foreach (KeyValuePair item in actionArguments) + { + var key = item.Key; //参数名 + var val = item.Value; //参数值 + if (key.ToLower() == "projectid") + { + var id = long.Parse(item.Value.ToString()); + if (currentUser.ProjectIds.Contains(id)) + { + projectId = id; + break; + } + } + } + } + else + { + var it = actionArguments.Values.First().ToDictionary(); + foreach (var i in it) + { + if (i.Key.ToLower() == "projectid") + { + var id = long.Parse(i.Value.ToString()); + projectId = id; + break; + } + } + } + } + //if (projectId > 0) + //{ + if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) + { + string actionName = controllerActionDescriptor.ActionName; + string controllerName = controllerActionDescriptor.ControllerName; + string path = controllerName + "/" + actionName; + long menuId = 0;//菜单id + var pars = context.ActionArguments.ToList(); + //if(pars!=null&&pars.Count>0) + //{ + // var menu=pars.FirstOrDefault(t => t.Key == "menuId"); + // menuId= menu.Value==null?0:long.Parse(menu.Value.ToString()); + //} + var res = funPermissionCoreService.GetCurrentUserFun(projectId, path).Result; + if (res == 0) + { + var result = new JsonResult(new ApiResult { Code = RequestBackStatuEnum.diy.Value, Data = string.Empty, Msg = "没有分配权限" }); + result.ContentType = "application/json"; + result.StatusCode = StatusCodes.Status200OK; + context.Result = result; + return; + } + } + //} + #endregion + ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; + bool isActionAuthDescriptor = ad.MethodInfo.IsDefined(typeof(ActionAuthAttribute), false); + if (isActionAuthDescriptor) + { + var authAttr = ad.MethodInfo.GetCustomAttributes(typeof(ActionAuthAttribute), false).FirstOrDefault() as ActionAuthAttribute; + long permissionId = authAttr.PermissionId; + + var currentUserFunPermissions = funPermissionCoreService.GetCurrentUserFunPermissions().Result; + + if (currentUserFunPermissions == null || !currentUserFunPermissions.Any(t => t == permissionId)) + { + var result = new JsonResult(new ApiResult { Code = RequestBackStatuEnum.diy.Value, Data = string.Empty, Msg = "没有分配权限" }); + result.ContentType = "application/json"; + result.StatusCode = StatusCodes.Status200OK; + context.Result = result; + return; + } + } + // + + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs new file mode 100644 index 0000000..c368ca3 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Filters +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] + public class FunctionAttribute : System.Attribute + { + public string ControllerDesc { get; set; } + public string MathodDesc { get; set; } + public FunctionAttribute( string controllerDesc = "", string mathodDesc = "") + { + controllerDesc = ControllerDesc; + mathodDesc = MathodDesc; + } + public FunctionAttribute() + { + + } + } + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs new file mode 100644 index 0000000..3dc6964 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs @@ -0,0 +1,90 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Extension; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Common +{ + public class GlobalExceptionsFilter : IExceptionFilter + { + + private readonly IHostingEnvironment _env; + private readonly ILogger _loggerHelper; + + public GlobalExceptionsFilter(IHostingEnvironment env, ILogger loggerHelper) + { + _env = env; + _loggerHelper = loggerHelper; + + } + + + + public void OnException(ExceptionContext context) + { + if (context.Exception is FriendlyException friendlyException) + { + context.Result = new OkObjectResult(ApiResult.IsFail(friendlyException.Message)); + return; + } + + string strController = context.RouteData.Values["controller"].ToString(); + string strAction = context.RouteData.Values["action"].ToString(); + //3.记录异常日志 + string errMsg = String.Format("千牛卫网站错误:控制器:{0};功能方法:{1};异常信息:{2};堆栈:{3};内部异常信息:{4};源:{5};", + strController, + strAction, + context.Exception.Message, + context.Exception.StackTrace, + context.Exception.GetDeepestException(), + context.Exception.Source + ); + _loggerHelper.LogError($"全局捕获异常: {errMsg}"); + + ContentResult result = new ContentResult + { + StatusCode = 500, + ContentType = "application/json; charset=utf-8" + }; + + var result1 = new ApiResult { }; + result1.Msg = "系统错误"; + result1.Code = 500; + result.Content = JsonConvert.SerializeObject(result1); + context.Result = result; + context.ExceptionHandled = true; + context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + } + } + + public static class ExceptionExtension + { + #region 获取最底层异常 + /// + /// 获取最底层异常 + /// + public static Exception GetDeepestException(this Exception ex) + { + var innerException = ex.InnerException; + var resultExcpetion = ex; + while (innerException != null) + { + resultExcpetion = innerException; + innerException = innerException.InnerException; + } + + return resultExcpetion; + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs new file mode 100644 index 0000000..21535fc --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs @@ -0,0 +1,15 @@ +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Filters +{ + /// + /// 这是一个空过滤器 用于过滤全局Filter的执行 + /// + public class SkipMyGlobalActionFilter : ActionFilterAttribute + { + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs new file mode 100644 index 0000000..6ede1a2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs @@ -0,0 +1,88 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using MySqlX.XDevAPI.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.Tenant; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Filters +{ + public interface ITenantAccessContextProvider + { + TenantAccessDto Current { get; set; } + } + public class TenantAccessContextProvider : ITenantAccessContextProvider + { + private static readonly AsyncLocal _current = new AsyncLocal(); + + public TenantAccessDto Current + { + get + { + if (_current.Value == null) + { + _current.Value = new TenantAccessDto(); + } + return _current.Value; + } + set + { + _current.Value = value; + } + } + } + + + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] + public class TenantAccessCheckFilter : Attribute, IAsyncActionFilter + { + private readonly ITenantAccessContextProvider _contextProvider; + public TenantAccessCheckFilter(ITenantAccessContextProvider contextProvider) + { + _contextProvider = contextProvider ?? throw new ArgumentNullException(nameof(contextProvider)); + } + public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var httpContext = context.HttpContext; + var headers = httpContext.Request.Headers; + + if (!headers.TryGetValue("AccessKey", out var accessKey) || + !headers.TryGetValue("AccessSign", out var accessSign)) + { + context.Result = new UnauthorizedObjectResult("Missing AccessKey or AccessSign"); + return; + } + // 假设有一个服务可以做签名验证 + var _userCenterContext = httpContext.RequestServices.GetRequiredService(); + var tenant = _userCenterContext.MsgTenant.Where(t => t.AccessKey == accessKey.ToString() && t.IsDeleted == false).AsNoTracking().FirstOrDefault(); + if (tenant == null) + { + context.Result = new UnauthorizedObjectResult("无效的accessKey"); + return; + } + //验证签名 + var sign = MD5Helper.getMd5Hash($"{tenant.AccessKey}{tenant.SecretKey}{DateTime.Now.ToString("yyyyMMddHHmm")}"); + if (!accessSign.Equals(sign)) + { + context.Result = new UnauthorizedObjectResult("无效的签名"); + return; + } + // 设置自定义上下文信息,比如用户信息 + _contextProvider.Current = new TenantAccessDto + { + Id = tenant.Id, + Name = tenant.Name, + AccessKey = tenant.AccessKey + }; + await next(); // 验签通过,继续执行 Action + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs new file mode 100644 index 0000000..8c89c9f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs @@ -0,0 +1,89 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Filters +{ + public class ValidateFieldsMiddleware + { + private readonly RequestDelegate _next; + + public ValidateFieldsMiddleware(RequestDelegate next) + { + _next = next; + } + private bool IsJsonRequest(HttpContext context) + { + // 判断是否是 Content-Type 为 application/json 的请求 + return context.Request.ContentType != null && + context.Request.ContentType.Contains("application/json", StringComparison.OrdinalIgnoreCase); + } + public async Task Invoke(HttpContext context) + { + if ((context.Request.Method == HttpMethods.Post || context.Request.Method == HttpMethods.Put) && IsJsonRequest(context)) + { + context.Request.EnableBuffering(); + var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); + if (!string.IsNullOrEmpty(body)) + { + context.Request.Body.Position = 0; + + //var jsonObject = JsonConvert.DeserializeObject(body); + var jsonObject = System.Text.Json.JsonSerializer.Deserialize(body); + if (jsonObject.ValueKind.ToString() != "Array") + { + + var properties = jsonObject.EnumerateObject(); + + // 获取当前的路由信息 + var endpoint = context.GetEndpoint(); + var controllerAction = endpoint?.Metadata.GetMetadata(); + + if (controllerAction != null) + { + // 获取方法参数类型 + var parameterInfo = controllerAction.Parameters.FirstOrDefault(); + if (parameterInfo != null) + { + var entityType = parameterInfo.ParameterType; + var entityProperties = entityType.GetProperties().Select(p => p.Name.ToLower()).ToList(); + + // 检查传入字段 + foreach (var property in properties) + { + if (property.Name.ToLower() == "projectid") + { + try + { + var projectIdStr = property.Value.ToString(); + if (projectIdStr.Length > 20) + { + context.Response.StatusCode = StatusCodes.Status400BadRequest; + await context.Response.WriteAsync($"Invalid field: {property.Name}"); + return; + } + } + catch (System.Exception) + { + } + } + if (!entityProperties.Contains(property.Name.ToLower())) + { + context.Response.StatusCode = StatusCodes.Status400BadRequest; + await context.Response.WriteAsync($"Invalid field: {property.Name}"); + return; + } + } + } + } + } + } + } + + await _next(context); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs new file mode 100644 index 0000000..2911fbd --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs @@ -0,0 +1,36 @@ +using Microsoft.Extensions.Hosting; +using NLog; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace WeiCloud.Core.HostService +{ + public class LogHostedServiceHost : IHostedService, IAsyncDisposable + { + private Timer RunTimer { get; set; } + public ValueTask DisposeAsync() + { + return this.RunTimer.DisposeAsync(); + } + + public Task StartAsync(CancellationToken cancellationToken) + { + LogManager.Configuration.Install(new NLog.Config.InstallationContext());//启动后执行一次 + this.RunTimer = new Timer(LogInstall, null, DateTime.Now.AddDays(1).Date - DateTime.Now, TimeSpan.FromDays(1)); + return Task.CompletedTask; + } + public void LogInstall(object state) + { + LogManager.Configuration.Install(new NLog.Config.InstallationContext());//每天0点执行一次 + } + + public Task StopAsync(CancellationToken cancellationToken) + { + this.RunTimer?.Change(Timeout.Infinite, 0); + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs new file mode 100644 index 0000000..84508aa --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs @@ -0,0 +1,56 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using MonitorAopLog.Util; +using MonitorAopLog.Util.Model; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.HostService +{ + public class MonitorLogFlush : MonitorLogManager + { + private readonly WeiCloudDBUserCenterContext _userCenterContext; + private readonly ILogger _logger; + private readonly IConfiguration _configuration; + private readonly string InstanceName; + public MonitorLogFlush(ILogger logger, IConfiguration configuration, WeiCloudDBUserCenterContext userCenterContext) : base(logger) + { + _configuration = configuration; + _logger = logger; + _userCenterContext = userCenterContext; + InstanceName = _configuration["MonitorLog:Instance"]; + } + + protected override async Task FlushAsync(List list, CancellationToken token) + { + try + { + if (!string.IsNullOrEmpty(InstanceName)) + { + foreach (var item in list) + { + _userCenterContext.MonitorLog.Add(new Entity.Context.UserCenter.MonitorLog + { + InstanceName = InstanceName, + MethodName = item.MethodName, + Arguments = item.Arguments, + ElapsedMilliseconds = item.ElapsedMilliseconds, + StartTime = item.StartTime, + EndTime = item.EndTime, + CreateTime = DateTime.Now + }); + } + await _userCenterContext.SaveChangesAsync(); + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message, ex); + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs new file mode 100644 index 0000000..ff866e4 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace WeiCloud.Core.HostService +{ + public class MonitorLogTaskHost : IHostedService + { + private readonly MonitorLogFlush _monitor; + public MonitorLogTaskHost(MonitorLogFlush monitor) + { + _monitor = monitor; + } + public async Task StartAsync(CancellationToken cancellationToken) + { + //using var loggerFactory = LoggerFactory.Create(builder => + //{ + // builder.SetMinimumLevel(LogLevel.Warning); + //}); + + //var logger = loggerFactory.CreateLogger(); + + //var monitorLog = new MonitorLog(logger); + //await monitorLog.Start(); + await _monitor.Start(); + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs b/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs new file mode 100644 index 0000000..8f71bc6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs @@ -0,0 +1,402 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.FamilyDecoration; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.DataCollection; +using WeiCloud.Utils; +using WeiCloud.Utils.RedisUtil; + +namespace WeiCloud.Core +{ + public class LocalData + { + private readonly int realDataExpireTimeMinutes = 10; + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceProvider; + private readonly IDictionaryService _dictionaryService; + public LocalData(ILogger logger, IServiceScopeFactory serviceProvider, IDictionaryService dictionaryService) + { + _logger = logger; + _serviceProvider = serviceProvider; + _dictionaryService = dictionaryService; + } + //private ConcurrentDictionary> realDataDic = new ConcurrentDictionary>(); + private ConcurrentDictionary>> realDataDic = new ConcurrentDictionary>> { }; + private async Task> InitTbRealData(long projectId, List realIds = null) + { + try + { + using var scope = _serviceProvider.CreateScope(); + var userDBContext = scope.ServiceProvider.GetRequiredService(); + + var projectInfo = userDBContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); + if (projectInfo == null || string.IsNullOrWhiteSpace(projectInfo.Dbstr)) + { + return new List { }; + } + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) + .Options; + using var contextDB = new WeiCloudDBContext(contextOptions); + var realDataQuery = contextDB.TbRealData.AsQueryable(); + if (realIds != null && realIds.Count() > 0) + { + realDataQuery = realDataQuery.Where(t => realIds.Contains(t.Id)); + } + realDataQuery = realDataQuery.Where(t => t.Projectid == projectId); + var realDatas = await realDataQuery.AsNoTracking().ToListAsync(); + if (realDatas != null && realDatas.Count() > 0) + { + var dataCaches = realDatas.Select(t => new LocalDataCache + { + CacheTime = DateTime.Now.AddMinutes(realDataExpireTimeMinutes + (t.Id % 5)), + Data = t + }).ToList(); + realDataDic.AddOrUpdate(projectId, dataCaches, (key, values) => + { + if (values == null) + { + values = new List> { }; + } + foreach (var realData in dataCaches) + { + //var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id && t.CacheTime > DateTime.Now); + var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id); + if (value == null) + { + values.Add(realData); + } + else if (value != null && value.CacheTime > DateTime.Now) + {//不为空,但已经失效 + values.Remove(value); + values.Add(realData); + } + } + return values; + }); + } + + return realDatas; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("InitTbRealData", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return new List { }; + } + + //public async Task> GetTbRealDatas(long projectId, List realdIds = null) + //{ + // List items; + // List> dataCaches = null; + // realDataDic.TryGetValue(projectId, out dataCaches); + // if (dataCaches != null) + // { + // if (realdIds != null && realdIds.Count() > 0) + // { + // items = dataCaches.Where(t => realdIds.Contains(t.Data.Id) && t.CacheTime >= DateTime.Now).Select(t => t.Data).ToList(); + // } + // else + // { + // items = dataCaches.Where(t => t.CacheTime >= DateTime.Now).Select(t => t.Data).ToList(); + // } + // if ((realdIds != null && items.Count() == realdIds.Count()) || (items.Count() == dataCaches.Count() && dataCaches.Count() > 0)) + // { + // return items; + // } + // } + // return await InitTbRealData(projectId, realdIds); + //} + public async Task> GetTbRealDatas_bak(long projectId, List realdIds = null) + { + List realvaluelist = new List { }; + if (realdIds != null && realdIds.Count() > 0) + { + realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), realdIds.Select(t => t.ToString()).ToArray(), 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); + } + else + { + var keyValueDic = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Values.ToList(); + var pageIndex = 0; + var pageSize = 500; + + while (true) + { + var _realDatas = keyValueDic.Skip(pageIndex * pageSize).Take(pageSize).ToList(); + if (_realDatas != null && _realDatas.Count() > 0) + { + realvaluelist.AddRange(_realDatas); + } + else + { + break; + } + pageIndex++; + } + + //var pageIndex = 0; + //var pageSize = 500; + + //while (true) + //{ + // var _realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Select(t => t.Value).Where(t => t != null).Skip(pageIndex * pageSize).Take(pageSize).ToList(); + // if (_realDatas != null && _realDatas.Count() > 0) + // { + // realvaluelist.AddRange(_realDatas); + // } + // else + // { + // break; + // } + // pageIndex++; + //} + //realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); + } + return realvaluelist ?? new List { }; + } + public async Task> GetTbRealDatas(long projectId, List realdIds = null) + { + using var serviceScope = _serviceProvider.CreateScope(); + var userCenterContext = serviceScope.ServiceProvider.GetRequiredService(); + var projectInfo = await userCenterContext.ProjectInfo.Where(t => t.Id == projectId).Select(t => new + { + t.Id, + t.Dbstr + }).FirstOrDefaultAsync(); + if (projectInfo == null || string.IsNullOrEmpty(projectInfo.Dbstr)) + { + return null; + } + try + { + var contextOptions = new DbContextOptionsBuilder() +.UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) +.Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + List realvaluelist; + if (realdIds != null && realdIds.Count() > 0) + { + //var data=await __contextDB.TbRealData.ToListAsync(); + realvaluelist = await __contextDB.TbRealData.Where(t => realdIds.Contains(t.Id) && t.Projectid == projectId).Select(t => new TbRealData + { + Id = t.Id, + Projectid = t.Projectid, + Descname = t.Descname, + Tagname = t.Tagname, + Aitype = t.Aitype, + Unit = t.Unit, + Equid = t.Equid, + Standarparamid = t.Standarparamid, + Virtualformula = t.Virtualformula, + Virtualformulaparam = t.Virtualformulaparam, + JsonContent = t.JsonContent, + PointType = t.PointType + }).ToListAsync(); + } + else + { + realvaluelist = await __contextDB.TbRealData.Where(t => t.Projectid == projectId).Select(t => new TbRealData + { + Id = t.Id, + Projectid = t.Projectid, + Descname = t.Descname, + Tagname = t.Tagname, + Aitype = t.Aitype, + Unit = t.Unit, + Equid = t.Equid, + Standarparamid = t.Standarparamid, + Virtualformula = t.Virtualformula, + Virtualformulaparam = t.Virtualformulaparam, + JsonContent = t.JsonContent, + PointType = t.PointType + }).ToListAsync(); + } + return realvaluelist ?? new List { }; + } + catch (Exception ex) + { + + throw; + } + + + } + public async Task CheckProIdIsRefresh(long projectId, List proIds, List proValueIds) + { + return true; + } + public async Task UpdateTbRealData() + { + using var scope = _serviceProvider.CreateScope(); + var configuration = scope.ServiceProvider.GetRequiredService(); + var prefix = configuration.GetConnectionString("RedisPrefix"); + prefix = prefix.Substring(0, prefix.Length - 1); + await UpdateTbRealData(0, prefix: prefix); + } + /// + /// 更新本地实时配置 + /// + /// + /// + /// + /// + private async Task UpdateTbRealData(long projectId, string prefix = "", List realIds = null) + { + try + { + using var scope = _serviceProvider.CreateScope(); + var userDBContext = scope.ServiceProvider.GetRequiredService(); + var projectQuery = userDBContext.ProjectInfo.AsNoTracking(); + if (projectId > 0) + { + projectQuery = projectQuery.Where(t => t.Id == projectId); + } + else if (!string.IsNullOrEmpty(prefix)) + { + projectQuery = projectQuery.Where(t => t.Engabb == prefix); + } + else + { + return; + } + var projectInfo = projectQuery.AsNoTracking().FirstOrDefault(); + if (projectInfo == null || string.IsNullOrWhiteSpace(projectInfo.Dbstr)) + { + return; + } + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) + .Options; + using var contextDB = new WeiCloudDBContext(contextOptions); + var realDataQuery = contextDB.TbRealData.AsQueryable(); + if (realIds != null && realIds.Count() > 0) + { + realDataQuery = realDataQuery.Where(t => realIds.Contains(t.Id)); + } + var realDatas = await realDataQuery.Where(t => t.Projectid == projectInfo.Id).AsNoTracking().ToListAsync(); + var dataCaches = realDatas.Select(t => new LocalDataCache + { + CacheTime = DateTime.Now.AddMinutes(realDataExpireTimeMinutes + (t.Id % 5)), + Data = t + }).ToList(); + realDataDic.AddOrUpdate(projectInfo.Id, dataCaches, (key, values) => + { + if (realDatas == null || realDatas.Count() == 0) + { + return new List> { }; + } + if (values == null) + { + values = new List> { }; + } + foreach (var realData in dataCaches) + { + //var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id && t.CacheTime >= DateTime.Now); + var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id); + if (value != null && value.CacheTime > DateTime.Now) + {//不为空,但已经失效 + values.Remove(value); + values.Add(realData); + } + else if (value == null) + { + values.Add(realData); + } + } + //移除失效 + values.RemoveAll(t => t.CacheTime > DateTime.Now); + //values.RemoveAll(t => !realDatas.Select(t => t.Id).Contains(t.Data.Id) || t.CacheTime < DateTime.Now); + //values.RemoveAll(t => !realDatas.Select(t => t.Id).Contains(t.Data.Id)); + return values; + }); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("UpdateTbRealData", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + #region 组态相关 + private ConcurrentDictionary>>> ConfigurationPositionCache = new ConcurrentDictionary>>>(); + /// + /// 缓存组态数据 + /// + /// + /// + /// + public async Task>> GetConfigurationPositionCache(string key, Func>> func) + { + try + { + await ClearConfigurationPositionCache(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetConfigurationPositionCache", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + try + { + LocalDataCache>> result = null; + ConfigurationPositionCache.TryGetValue(key, out result); + if (result != null && result.CacheTime > DateTime.Now.AddSeconds(-2)) + {//缓存2秒内数据 + Console.WriteLine($"{key}缓存数据"); + return result.Data; + } + var data = func(key); + + ConfigurationPositionCache.AddOrUpdate(key, (key) => + { + return new LocalDataCache>> + { + CacheTime = DateTime.Now.AddSeconds(2), + Data = data + }; + }, (key, value) => + { + value.CacheTime = DateTime.Now.AddSeconds(2); + value.Data = data; + return value; + }); + Console.WriteLine($"{key}新数据"); + return data; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetConfigurationPositionCache", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return new ApiResult> { Code = RequestBackStatuEnum.fail.Value }; + } + private async Task ClearConfigurationPositionCache() + { + var keys = ConfigurationPositionCache.Keys; + foreach (var key in keys) + { + LocalDataCache>> value; + if (ConfigurationPositionCache.TryGetValue(key, out value) && value != null && value.CacheTime < DateTime.Now.AddSeconds(-10)) + { + ConfigurationPositionCache.TryRemove(key, out value); + } + } + } + #endregion + + public class LocalDataCache + { + public DateTime CacheTime { get; set; } + public T Data { get; set; } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs new file mode 100644 index 0000000..b46003e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs @@ -0,0 +1,161 @@ +using Microsoft.ML; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.LogicModels.ML; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core.ML +{ + public class RegressionUtil + { + private MLContext mlContext = new MLContext(seed: 0); + private IDataView dataView = null; + private ITransformer transModel = null; + public void Train(List trainModels) where T : class + { + var propertys = typeof(T).GetProperties(); + + var labelName = propertys.LastOrDefault().Name; + dataView = mlContext.Data.LoadFromEnumerable(trainModels); + //var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: nameof(labelName)); + var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: labelName); + List features = new List { }; + foreach (var property in propertys) + { + string name = property.Name; + + string type = (property.PropertyType).FullName; + + if ("System.Decimal" == type || "System.Double" == type || "System.Int16" == type + || "System.Int64" == type || "System.Int32" == type || "System.Single" == type) + { + //features.Add(nameof(name)); + features.Add(name); + //pipeline.Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(name))); + pipeline.Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: name)); + } + else + { + features.Add(name + "Encoded"); ; + //pipeline.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: name + "Encoded", inputColumnName: nameof(name))); + pipeline.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: name + "Encoded", inputColumnName: name)); + } + } + pipeline.Append(mlContext.Transforms.Concatenate("Features", features.ToArray())); + pipeline.Append(mlContext.Regression.Trainers.FastTree()); + transModel = pipeline.Fit(dataView); + } + public void TrainBinary(List trainModels) + { + dataView = mlContext.Data.LoadFromEnumerable(trainModels); + + var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: nameof(BinaryTrainModel.PhyValue)) + .Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "efectphytypeEncoded", inputColumnName: nameof(BinaryTrainModel.EfectPhyType))) + .Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "efectphytype1Encoded", inputColumnName: nameof(BinaryTrainModel.EfectPhyType1))) + .Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(BinaryTrainModel.EfectPhyValue))) + .Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(BinaryTrainModel.EfectPhyValue1))) + + .Append(mlContext.Transforms.Concatenate("Features", "efectphytypeEncoded", "efectphytype1Encoded", nameof(BinaryTrainModel.EfectPhyValue), nameof(BinaryTrainModel.EfectPhyValue1))) + .Append(mlContext.Regression.Trainers.FastTree()); + + transModel = pipeline.Fit(dataView); + } + public void Evaluate(List evaluateModels) where T : class + { + var _dataView = mlContext.Data.LoadFromEnumerable(evaluateModels); + var predictions = transModel.Transform(_dataView); + mlContext.Regression.Evaluate(predictions, "Label", "Score"); + } + public void EvaluateBinary(List evaluateModels) + { + var _dataView = mlContext.Data.LoadFromEnumerable(evaluateModels); + var predictions = transModel.Transform(_dataView); + mlContext.Regression.Evaluate(predictions, "Label", "Score"); + } + public ParamPrediction Prediction(TSrc input) where TSrc : class + { + var predictionFunction = mlContext.Model.CreatePredictionEngine(transModel); + var prediction = predictionFunction.Predict(input); + return prediction; + } + public void LoadTranModel(string url) + { + DataViewSchema modelSchema; + using (HttpClient client = new HttpClient()) + { + Stream modelFile = client.GetStreamAsync(url).Result; + transModel = mlContext.Model.Load(modelFile, out modelSchema); + } + } + public FileInfo GetModelFile() + { + string fileName = Guid.NewGuid().ToString("N") + ".zip"; + string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); + FileInfo file = null; + try + { + //mlContext.Model.Save(transModel, dataView.Schema, path); + mlContext.Model.Save(transModel, dataView.Schema, path); + file = new FileInfo(path); + } + catch (Exception ex) + { + } + finally + { + if (File.Exists(path)) + File.Delete(path); + } + return file; + } + public Stream GetModelFileStream() + { + MemoryStream memoryStream = new MemoryStream(); + try + { + mlContext.Model.Save(transModel, dataView.Schema, memoryStream); + memoryStream.Flush(); + memoryStream.Position = 0; + } + catch (Exception ex) + { + } + finally + { + } + return memoryStream; + } + public string SaveModel() + { + if (transModel == null || dataView == null) + { + return "error"; + } + string fileName = Guid.NewGuid().ToString("N") + ".zip"; + string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); + try + { + mlContext.Model.Save(transModel, dataView.Schema, path); + var file = new FileInfo(path); + var t = FileHelper.FileUpload(file); + Task.WaitAny(t); + } + catch (Exception ex) + { + throw ex; + } + finally + { + //if (File.Exists(path)) + // File.Delete(path); + } + return fileName; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs b/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs new file mode 100644 index 0000000..5b25290 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs @@ -0,0 +1,18 @@ +using Microsoft.ML.Data; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace WeiCloud.Core.ML +{ + public class TrainModel + { + public Dictionary ParamDic { get; set; } + } + public class ParamPrediction + { + [ColumnName("Score")] + public float phyvalue { get; set; } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs new file mode 100644 index 0000000..8263a2f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs @@ -0,0 +1,265 @@ +using Castle.Core.Logging; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using NPOI.OpenXmlFormats; +using Org.BouncyCastle.Asn1.Ocsp; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Middleware +{ + public static class MiddlewareExtensions + { + public static IApplicationBuilder UseImgResponse( + this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } + public class ImgResponseMiddleware + { + private readonly RequestDelegate _next; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + private readonly List _outerNets; + private readonly List _internalNets; + public ImgResponseMiddleware(RequestDelegate next, IConfiguration config, ILogger logger) + { + _next = next; + _configuration = config; + _logger = logger; + _outerNets = _configuration["ImgConvertConfig:OuterNet"].Split(",").ToList(); + _internalNets = _configuration["ImgConvertConfig:InternalNet"].Split(",").ToList(); + } + private bool IsInternalNet(string host) + { + var result = false; + try + { + /* var addr = host.Split(".")[0]; + + if (addr == "10" || addr == "172" || addr == "192") + { + result = true; + }*/ + if (host.Contains(_configuration["ImgConvertConfig:OuterNet"])) + { + return false; + } + return true; + } + catch (Exception) + { + } + return result; + } + private Tuple GetFileHost(string host) + { + var result = false; + try + { + /* var addr = host.Split(".")[0]; + + if (addr == "10" || addr == "172" || addr == "192") + { + result = true; + }*/ + foreach (var _outerNet in _outerNets) + { + if (host.Contains(_outerNet)) + { + return new Tuple(false, _outerNet); + } + } + //if (host.Contains(_configuration["ImgConvertConfig:OuterNet"])) + //{ + // return false; + //} + var internalNet = _internalNets.First(); + foreach (var _internalNet in _internalNets) + { + if (host.Contains(_internalNet)) + { + internalNet = _internalNet; + } + } + return new Tuple(true, internalNet); + } + catch (Exception) + { + } + return new Tuple(result, string.Empty); + } + public async Task InvokeAsync(HttpContext context) + { + try + { + var method = context.Request.Method; + var isJsonRequest = false; + if (context.Request.Headers["accept"].Count > 0) + { + isJsonRequest = context.Request.Headers["accept"][0].Contains("application/json"); + } + + var scheme = "http"; + var referer = context.Request.Headers["Referer"].ToString(); + if (referer.StartsWith("https")) + { + scheme = "https"; + } + Console.WriteLine($"Referer:{referer}"); + Console.WriteLine($"Scheme:{scheme}"); + var isInternalNetInfo = GetFileHost(referer); + var isInternalNet = isInternalNetInfo.Item1; + var fileHost = isInternalNetInfo.Item2; + //if ((method.Equals("POST") || method.Equals("GET")) && !context.Request.Host.Value.StartsWith(_configuration["FileUpload:hostname"]) && isJsonRequest) + if ((method.Equals("POST") || method.Equals("GET")) && isJsonRequest) + { + var orgResponseBody = context.Response.Body; + + //替换response流 + using var newResponse = new MemoryStream(); + context.Response.Body = newResponse; + await _next.Invoke(context); + //await _next(context); + using var reader = new StreamReader(newResponse); + + newResponse.Seek(0, SeekOrigin.Begin); + + var strBody = await reader.ReadToEndAsync(); + + newResponse.Seek(0, SeekOrigin.Begin); + + if (!string.IsNullOrWhiteSpace(strBody) && (strBody.Contains("/imageserve") || strBody.Contains("live?port=1935&app="))) + { + var newStrBody = strBody; + //var newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + context.Request.HttpContext.Request.Host.Value).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + context.Request.HttpContext.Request.Host.Value); + + //if (isInternalNet) + //{//context.Request.Headers["Referer"].ToString() + // //newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:InternalNet"]).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:InternalNet"]); + + // newStrBody = strBody.Replace("http://" + _configuration["ImgConvertConfig:OuterNet"] + "/", "http://" + _configuration["ImgConvertConfig:InternalNet"] + "/").Replace("https://" + _configuration["ImgConvertConfig:OuterNet"] + "/", "https://" + _configuration["ImgConvertConfig:InternalNet"] + "/"); + //} + //else + //{ + // //newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:OuterNet"]).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:OuterNet"]); + // newStrBody = strBody.Replace("http://" + _configuration["ImgConvertConfig:InternalNet"]+"/", "http://" + _configuration["ImgConvertConfig:OuterNet"] + "/").Replace("https://" + _configuration["ImgConvertConfig:InternalNet"] + "/", "https://" + _configuration["ImgConvertConfig:OuterNet"] + "/"); + + //} + foreach (var _outerNet in _outerNets) + { + strBody = strBody.Replace("http://" + _outerNet + "/", scheme + "://" + fileHost + "/").Replace("https://" + _outerNet + "/", scheme + "://" + fileHost + "/"); + } + foreach (var _internalNet in _internalNets) + { + strBody = strBody.Replace("http://" + _internalNet + "/", scheme + "://" + fileHost + "/").Replace("https://" + _internalNet + "/", scheme + "://" + fileHost + "/"); + } + newStrBody = strBody; + Console.WriteLine(_configuration["FileUpload:hostname"]); + Console.WriteLine(_configuration["ImgConvertConfig:InternalNet"]); + Console.WriteLine(_configuration["ImgConvertConfig:OuterNet"]); + + + //显示修改后的数据 + //using var writer = new StreamWriter(newResponse); + + //await writer.WriteAsync(newStrBody); + //await writer.FlushAsync(); + + //newResponse.Seek(0, SeekOrigin.Begin); + + //context.Response.ContentLength = newResponse.Length; + //await newResponse.CopyToAsync(orgResponseBody); + + //await newResponse.CopyToAsync(context.Response.Body); + var buffer = Encoding.UTF8.GetBytes(newStrBody); + context.Response.Body = orgResponseBody; + context.Response.ContentLength = buffer.Length; + await context.Response.WriteAsync(newStrBody, Encoding.UTF8); + } + else + { + //context.Response.Body = orgResponseBody; + //await context.Response.WriteAsync(strBody, Encoding.UTF8); + await context.Response.Body.CopyToAsync(orgResponseBody); + } + } + else + { + await _next(context); + } + } + catch (System.Exception ex) + { + _logger.LogError($" http中间件发生错误: " + ex.ToString()); + } + context.Response.OnCompleted(() => + { + return Task.CompletedTask; + }); + } + + //public async Task InvokeAsync(HttpContext context) + //{ + // var response = context.Response.Body; + // try + // { + // if (_configuration["FileUpload:hostname"] != context.Request.HttpContext.Request.Host.Value) + // { + // //替换response流 + // using var newResponse = new MemoryStream(); + // context.Response.Body = newResponse; + + // await _next(context); + + // using var reader = new StreamReader(newResponse); + // newResponse.Position = 0; + // var strBody = await reader.ReadToEndAsync(); + + // if (!string.IsNullOrWhiteSpace(strBody) && strBody.Contains("/imageserve")) + // { + // var newStrBody = strBody.Replace(_configuration["FileUpload:hostname"], context.Request.HttpContext.Request.Host.Value); + + // //var buffer = Encoding.UTF8.GetBytes(newStr); + + // //using var ms2 = new MemoryStream(); + // //ms2.Write(buffer, 0, buffer.Length); + // //ms2.Seek(0, SeekOrigin.Begin); + // //await ms2.CopyToAsync(response); + + // using (var writer = new StreamWriter(response)) + // { + // await writer.WriteAsync(newStrBody); + // await writer.FlushAsync(); + // } + // } + // } + // else + // { + // await _next(context); + // } + // } + // catch (System.Exception ex) + // { + // _logger.LogError($" http中间件发生错误: " + ex.ToString()); + // } + // finally + // { + // context.Response.Body = response; + // } + // context.Response.OnCompleted(() => + // { + // return Task.CompletedTask; + // }); + //} + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs new file mode 100644 index 0000000..9dbb302 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs @@ -0,0 +1,65 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Middleware +{ + public class LogMiddleware + { + private readonly ILogger _logger; + + public LogMiddleware(ILogger logger) + { + _logger = logger; + } + private readonly RequestDelegate _next; + public LogMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = logger; + } + public async Task InvokeAsync(HttpContext context) + { + try + { + if (context.Request.Method == "POST" || context.Request.Method == "PUT") + { + context.Request.EnableBuffering(); + var body = string.Empty; + using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true)) + { + body = await reader.ReadToEndAsync(); + } + context.Request.Body.Position = 0; // 重置Body流,以便后续使用 + + context.Items["RequestBody"] = body; + } + else if (context.Request.Method == "GET") + { + // 获取GET请求的参数 + var parameters = context.Request.Query; + if (parameters != null && parameters.Any()) + { + StringBuilder sbParams = new StringBuilder(); + foreach (var parameter in parameters) + { + var paramName = parameter.Key; + var paramValue = parameter.Value; + sbParams.Append($"{paramName}={paramValue}&"); + } + context.Items["Querystring"] = sbParams.ToString().TrimEnd('&'); + } + } + } + catch (Exception ex) + { + _logger.LogError("Error reading request body: {0}", ex.Message); + } + await _next(context); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs new file mode 100644 index 0000000..8cb3233 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs @@ -0,0 +1,191 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Utils; + +namespace WeiCloud.Core.MsgSocket +{ + public class MsgWebSocketClientInstance + { + private readonly ILogger _logger; + public MsgWebSocketClientInstance(ILogger logger) + { + _logger = logger; + } + /// + /// 客户端 hubName-clientIds + /// + //private readonly ConcurrentDictionary> Clients = new ConcurrentDictionary>(); + /// + /// clientId-hubName + /// + private readonly ConcurrentDictionary ClientHub = new ConcurrentDictionary(); + /// + /// clientId-userId + /// + private readonly ConcurrentDictionary ClientUserId = new ConcurrentDictionary(); + //public List GetClientIdsByHubName(string hubName) + //{ + // List _; + // if (Clients.TryGetValue(hubName, out _)) + // { + // return _; + // } + // return null; + //} + public async Task UnSubscribe(string clientId) + { + try + { + ClientHub.TryRemove(clientId, out _); + //var userId = 0L; + ClientUserId.TryRemove(clientId,out var userId); + + //Console.WriteLine($"当前在线人数:{keys}"); + //_logger.LogInformation($"{clientId}下线,UserId:{userId}"); + //var clientIds = ClientUserId.Keys.ToList().Join(","); + //var userIds = ClientUserId.Values.ToList().Join(","); + var clientIds = ClientUserId.Where(t => t.Value == userId).Select(t => t.Key).ToList(); + _logger.LogInformation($"{clientId}下线,在线用户:UserId:{userId} 客户端ID:{clientIds.Join(",")}"); + } + catch (Exception ex) + { + _logger.LogError(ex, $"{clientId} UnSubscribe 取消连接"); + } + } + public async Task ClientIdMapUserId(string clientId, long userId) + { + ClientUserId.TryAdd(clientId, userId); + } + private string GetRequestMsg(string action, object message) + { + var requestMsg = string.Empty; + if (message != null) + { + requestMsg = $"{action}_{message}"; + } + else + { + requestMsg = action; + } + return requestMsg; + } + public async Task GetClientMapUserId(string clientId) + { + long userId = 0; + int count = 0; + while (count < 10) + { + ClientUserId.TryGetValue(clientId, out userId); + if (userId > 0) + { + break; + } + count++; + await Task.Delay(1000); + } + _logger.LogInformation($"获取用户Id:ClientId:{clientId};UserId:{userId}"); + if (userId == 0) + { + _logger.LogWarning($"获取用户Id失败:ClientId:{clientId}"); + } + return userId; + } + public async Task Subscribe(string clientId, string action, object message) + { + var result = string.Empty; + try + { + if (string.IsNullOrWhiteSpace(action)) + { + _logger.LogError("action为空"); + return result; + } + var requestMsg = GetRequestMsg(action, message); + + var orgHubName = string.Empty; + + var userId = await GetClientMapUserId(clientId); + var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); + ClientHub.TryAdd(clientId, hubName); + + _logger.LogWarning($"订阅完成:ClientId:{clientId} UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()}"); + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + } + return result; + } + /// + /// 获取客户端ID + /// + /// + /// + /// + public async Task?> GetClientIds(string action, object message) + { + List? clientIds = null; + try + { + if (string.IsNullOrWhiteSpace(action)) + { + _logger.LogError("action为空"); + return clientIds; + } + var requestMsg = string.Empty; + if (message != null) + { + requestMsg = $"{action}_{message}"; + } + else + { + requestMsg = action; + } + var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); + //Clients.TryGetValue(hubName, out clientIds); + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + } + return clientIds; + } + public async Task?> GetClientIds(long userId, string action, object message) + { + List? clientIds = null; + try + { + if (string.IsNullOrWhiteSpace(action)) + { + _logger.LogError("action为空"); + return clientIds; + } + var requestMsg = GetRequestMsg(action, message); + var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); + //Clients.TryGetValue(hubName, out clientIds); + + clientIds = ClientHub.Where(t => t.Value == hubName).Select(t => t.Key).ToList(); + + var userClientIds = ClientUserId.Where(t => t.Value == userId).Select(t => t.Key).ToList(); + clientIds = clientIds.Where(t => userClientIds.Contains(t)).ToList(); + if (clientIds != null && clientIds.Any()) + { + _logger.LogInformation($"获取客户端ID:UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()} 客户端ID:{clientIds.Join(",")}"); + } + else + { + _logger.LogInformation($"获取客户端ID:UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()} 客户端ID:空"); + } + } + catch (Exception ex) + { + _logger.LogError(ex.Message); + } + return clientIds; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs new file mode 100644 index 0000000..6f99b70 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs @@ -0,0 +1,76 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using System; +using System.Net.WebSockets; +using System.Threading.Tasks; +using WebSocketUtil; +using WeiCloud.Core.Services; +using WeiCloud.Core.Services.Message; + +namespace WeiCloud.Core.MsgSocket +{ + public class MsgWebSocketMessageHandler : WebSocketHandler + { + private readonly MsgWebSocketClientInstance _msgWebSocketClientInstance; + private readonly IUsersCoreService _usersCoreService; + private readonly IMsgCenterCoreService _msgCenterCoreService; + private readonly ILogger _logger; + public MsgWebSocketMessageHandler(WebSocketConnectionManager webSocketConnectionManager, MsgWebSocketClientInstance msgWebSocketClientInstance, IUsersCoreService usersCoreService, IMsgCenterCoreService msgCenterCoreService, ILogger logger) : base(webSocketConnectionManager) + { + _msgWebSocketClientInstance = msgWebSocketClientInstance; + _usersCoreService = usersCoreService; + _msgCenterCoreService = msgCenterCoreService; + _logger = logger; + } + public override async void OnConnected(WebSocket socket, HttpContext context, string key) + { + var token = string.Empty; + try + { + base.OnConnected(socket, context, key); + token = context.Request.Query["token"]; + var userId = 0L; + if (!string.IsNullOrEmpty(token)) + { + //var user = await _usersCoreService.GetUserInfoByJwt(token); + var user = _usersCoreService.GetUserInfoByJwtStr(token); + long.TryParse(user.Sub, out userId); + if (userId > 0) + { + //Console.WriteLine($"{userId}上线:ClientId={key}"); + await _msgWebSocketClientInstance.ClientIdMapUserId(key, userId); + } + else + { + _logger.LogWarning($"{key} {token} token验证失败"); + } + } + _logger.LogInformation($"{userId}上线:ClientId={key}"); + } + catch (Exception ex) + { + Console.WriteLine($"token验证失败{ex.Message} {ex.StackTrace} {ex.Source} {token}"); + _logger.LogError(ex, $"{token} token验证失败"); + } + } + public override async Task OnDisconnected(WebSocket socket, string connectId) + { + await _msgWebSocketClientInstance.UnSubscribe(connectId); + await base.OnDisconnected(socket, connectId); + //Console.WriteLine($"{connectId}下线"); + } + public override async Task ReceiveAsync(string action, string clientId, object message) + { + if (string.IsNullOrWhiteSpace(action)) + { + return; + } + var _userId = await _msgWebSocketClientInstance.GetClientMapUserId(clientId); + await _msgWebSocketClientInstance.Subscribe(clientId, action, message); + if (_userId > 0) + { + await _msgCenterCoreService.ResendInternalMsg(_userId);//重发未读消息 + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs new file mode 100644 index 0000000..5ccaa75 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Text; +using WeiCloud.Utils; + +namespace WeiCloud.Core +{ + public interface INlogMessageHelper: ITransentInject + { + string GetNlogMessage(HttpContext context, string parameter, string parmValue, string message); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs new file mode 100644 index 0000000..e60aa33 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs @@ -0,0 +1,187 @@ +using NLog.Config; +using NLog; +using System; +using System.Collections.Generic; +using System.Text; +using System.Xml.Linq; +using System.Linq; + +namespace WeiCloud.Core.NlogTools +{ + public static class LoggerHelper + { + //优先级:Trace>Debug>Info>Warn>Error>Fatal + private const string MssqlDbProvider = "Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"; + private const string MysqlDbProvider = "MySql.Data.MySqlClient.MySqlConnection, MySql.Data"; + public static Logger DbLogger = LogManager.GetLogger("logdb"); + public static Logger FileLogger = LogManager.GetLogger("logfile"); + /// + /// 确保NLog配置文件sql连接字符串正确 + /// + /// + /// + /// + public static void EnsureNLogConfig(string nLogPath, string dbType, string sqlConnectionStr) + { + var xd = XDocument.Load(nLogPath); + if (xd.Root != null && xd.Root.Elements().FirstOrDefault(a => a.Name.LocalName == "targets") is XElement targetsNode && targetsNode.Elements().FirstOrDefault(a => a.Name.LocalName == "target" && a.Attribute("name")?.Value == "log_database") is XElement targetNode) + { + if (!targetNode.Attribute("connectionString").Value.Equals(sqlConnectionStr)) //连接字符串不一致则修改 + { + targetNode.Attribute("connectionString").Value = sqlConnectionStr; + //dbProvider的变动仅限mssql和mysql + targetNode.Attribute("dbProvider").Value = dbType.ToLower() == "mysql" ? MysqlDbProvider : MssqlDbProvider; + xd.Save(nLogPath); + //编辑后重新载入配置文件(不依靠NLog自己的autoReload,有延迟) + LogManager.Configuration = new XmlLoggingConfiguration(nLogPath); + } + } + } + /// + /// 写日志到数据库 + /// + /// 日志等级 + /// 信息 + /// 异常 + public static void WriteDbLog(LogLevel logLevel, string message, Exception exception = null, string platHost = "") + { + var msg = message; + if (exception != null) + { + msg = $"{exception.StackTrace}"; + + } + var theEvent = new LogEventInfo(logLevel, DbLogger.Name, msg) + { + Exception = exception, + Properties = + { + ["LogType"] = exception != null ? exception.Source : "", + ["platHost"] = platHost + } + }; + DbLogger.Log(theEvent); + } + /// + /// 写日志到文件 + /// + /// 日志等级 + /// 信息 + /// 异常 + public static void WriteFileLog(LogLevel logLevel, string message, Exception exception = null, string platHost = "") + { + var msg = $"{message}===="; + if (exception != null) + { + msg = $"{message}======StackTrace====={exception.StackTrace}"; + } + + var theEvent = new LogEventInfo(logLevel, FileLogger.Name, msg) + { + Exception = exception, + Properties = + { + ["LogType"] = exception != null ? exception.Source : "", + ["platHost"] = platHost + } + }; + FileLogger.Log(theEvent); + } + #region 输出日志 + /// + /// 错误日志 + /// + /// + /// + /// 1、DB 2、File + /// + public static void Error(string message, Exception ex, int type = 1, string platHost = "") + { + var msg = ""; + if (ex != null) + { + message += $",Ex:{ex.Message}"; + } + + if (!string.IsNullOrEmpty(message) && ex == null) + { + msg = $"【附加信息】 : {message}
"; + } + else if (!string.IsNullOrEmpty(message) && ex != null) + { + var errorMsg = BeautyErrorMsg(ex); + msg = $"【附加信息】 : {message}
{errorMsg}"; + } + else if (string.IsNullOrEmpty(message) && ex != null) + { + msg = BeautyErrorMsg(ex); + } + + if (type == 1) + { + WriteDbLog(LogLevel.Error, msg, ex, platHost); + } + else + { + WriteFileLog(LogLevel.Error, msg, ex, platHost); + } + } + public static void Error(string message, int type = 1, Exception ex = null, string platHost = "") + { + if (type == 1) + { + WriteDbLog(LogLevel.Error, message, ex, platHost); + } + else + { + WriteFileLog(LogLevel.Error, message, ex, platHost); + } + } + public static void Debug(string message, int type = 1, string platHost = "") + { + if (type == 1) + { + WriteDbLog(LogLevel.Debug, message, platHost: platHost); + } + else + { + WriteFileLog(LogLevel.Debug, message); + } + } + public static void Info(string message, int type = 1) + { + if (type == 1) + { + WriteDbLog(LogLevel.Info, message); + } + else + { + WriteFileLog(LogLevel.Info, message); + } + } + public static void Warn(string message, int type = 1) + { + if (type == 1) + { + WriteDbLog(LogLevel.Warn, message); + } + else + { + WriteFileLog(LogLevel.Warn, message); + } + } + /// + /// 美化错误信息 + /// + /// 异常 + /// 错误信息 + private static string BeautyErrorMsg(Exception ex) + { + var errorMsg = string.Format("【异常类型】:{0}
【异常信息】:{1}
【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace }); + // errorMsg = errorMsg.Replace("\r\n", "
"); + // errorMsg = errorMsg.Replace("位置", "位置"); + return errorMsg; + } + #endregion + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs new file mode 100644 index 0000000..2c4e751 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs @@ -0,0 +1,300 @@ +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using System; +using System.Text; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.InfoModels; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core +{ + public class NlogMessageHelper + { + private readonly HttpContext _context; + private readonly string _parameter; + private readonly string _parmValue; + private readonly string _message; + private readonly Exception _exception; + private readonly string _actionname; + + private readonly int? _equipId; + private readonly string _newParmValue; + private readonly int _logType; + private readonly int? _projectId; + private long? _userId = 0; + private string _userName = ""; + private string _machineIp = ""; + //private WeiCloudDBContext _cloudContext; + /// + /// 实例化 WebAPI Controller类的日志消息获取类 + /// + /// 当前API的上下文 + /// API返回参数名 + /// API返回参数值 + /// 提示信息 + public NlogMessageHelper(HttpContext context, string parameter, string parmValue, string message) + { + _context = context; + _parameter = parameter; + _parmValue = parmValue; + _message = message; + } + /// + /// 实例化 控制台程序或一般类的日志消息获取类 + /// + /// + /// + /// + public NlogMessageHelper(string actionname, string message) + { + _actionname = actionname; + _message = message; + } + public NlogMessageHelper(string actionname, Exception ex) + { + _actionname = actionname; + _exception = ex; + } + + public Nlog GetAPINlog() + { + long userid = 0; + string username = ""; + //通过授权验证信息获得当前用户 + if (_context.User.Claims != null) + { + foreach (var item in _context.User.Claims) + { + if (item.Type == "sub") + { + userid = long.Parse(item.Value); + } + if (item.Type == "name") + { + username = item.Value; + } + } + } + + var log = new Nlog() + { + Id = UidGenerator.Uid(), + MachineIp = _context.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + _context.Connection.RemotePort, + CreateUserId = userid, + CreateUserName = username, + CreateTime = DateTime.Now, + ActionName = _context.Request.Path, + Parameter = _parameter, + OldParmValue = _parmValue, + Message = _message, + EndDateTime = DateTime.Now + }; + + return log; + } + + public Nlog GetClassNlog() + { + var log = new Nlog() + { + Id = UidGenerator.Uid(), + MachineIp = "localhost", + CreateTime = DateTime.Now, + ActionName = _actionname, + Message = _message, + EndDateTime = DateTime.Now + }; + return log; + } + /// + /// 日志写入文件 + /// + /// + public string GetNlogMessage() + { + Nlog log; + if (_context != null) + { + log = GetAPINlog(); + //------日志添加入数据库 + //edit by wt 2020.06.18 此处写数据库日志先屏蔽掉 用全局ActionFilter进行代替 + //PostNlogs(log).Wait(); + //--------end------- + } + else + { + log = GetClassNlog(); + } + + StringBuilder messageString = new StringBuilder(); + messageString.Append(string.IsNullOrEmpty(log.MachineIp) ? "" : log.MachineIp + "|"); + messageString.Append(log.CreateUserId == 0 ? "" : log.CreateUserId.ToString() + "|"); + messageString.Append(string.IsNullOrEmpty(log.CreateUserName) ? "" : log.CreateUserName + "|"); + messageString.Append(string.IsNullOrEmpty(log.ActionName) ? "" : log.ActionName + "|"); + messageString.Append(string.IsNullOrEmpty(log.Parameter) ? "" : log.Parameter + "|"); + messageString.Append(string.IsNullOrEmpty(log.OldParmValue) ? "" : log.OldParmValue + "|"); + if (_exception != null) + { + var _msg = JsonConvert.SerializeObject(_exception); + messageString.Append(_msg + "|"); + } + else + { + messageString.Append(string.IsNullOrEmpty(log.Message) ? "" : log.Message + "|"); + } + return messageString.ToString(); + } + /// + /// 日志写入数据库 + /// + /// + /// + /*public async Task PostNlogs(Nlog log) + { + _cloudContext = new WeiCloudDBContext(); + var res = 0; + _cloudContext.Nlog.Add(log); + //数据库中更新用户状态 + res = await _cloudContext.SaveChangesAsync(); + if (res > 0) + { + return RequestBackStatuEnum.success.Value; + } + else + return RequestBackStatuEnum.fail.Value; + }*/ + /* public async Task GetLog(Nlog log) + { + int n = await PostNlogs(log); + return n; + }*/ + + + /// + /// 构造函数3 + /// + /// 当前API的上下文 + /// 设备id + /// 控制的参数名称 + /// 参数老的值 + /// 参数新的值 + /// 备注提示信息 + /// 日志类型 + public NlogMessageHelper(HttpContext context, int? projectId, int? equipId, string parameter, string oldParmValue, string newParmValue, string message, int logType) + { + _context = context; + _parameter = parameter; + _parmValue = oldParmValue; + _message = message; + _equipId = equipId; + _newParmValue = newParmValue; + _logType = logType; + _projectId = projectId; + _actionname = _context.Request.Path; + } + /// + /// 构造函数4 + /// + /// 用户id + /// 用户名称 + /// 操作名称 + /// 项目id + /// 设备id + /// 设备调用参数 + /// 老值 + /// 新的值 + /// 备注操作返回信息 + /// 日志类型 + public NlogMessageHelper(ContextModel contextModel, int? projectId, int? equipId, string parameter, string oldParmValue, string newParmValue, string message, int logType) + { + _context = null; + _parameter = parameter; + _parmValue = oldParmValue; + _message = message; + _equipId = equipId; + _newParmValue = newParmValue; + _logType = logType; + _projectId = projectId; + _actionname = contextModel.actionName; + _userId = contextModel.userId; + _userName = contextModel.userName; + _machineIp = contextModel.machineIp; + } + /// + /// 获取日志信息 配合构造函数3使用 + /// + /// 返回日志对象 + public Nlog GetAPINlogEx() + { + + //通过授权验证信息获得当前用户 + + if (_context != null) + { + if (_context.User.Claims != null) + { + foreach (var item in _context.User.Claims) + { + if (item.Type == "sub") + { + _userId = long.Parse(item.Value); + } + if (item.Type == "name") + { + _userName = item.Value; + } + } + } + _machineIp = _context.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + _context.Connection.RemotePort; + } + + var log = new Nlog() + { + Id = UidGenerator.Uid(), + MachineIp = _machineIp, + CreateUserId = _userId.Value, + CreateUserName = _userName, + CreateTime = DateTime.Now, + ActionName = _actionname, + Parameter = _parameter, + OldParmValue = _parmValue, + Message = _message, + EndDateTime = DateTime.Now, + NewParmValue = _newParmValue, + LogType = _logType, + EquipId = _equipId, + ProjectId = _projectId + }; + return log; + } + + /// + /// 存储用户日志信息2 并输出文本信息 + /// + /// 日志文本信息 + public string GetNlogMessageEx() + { + Nlog log; + if (_context != null) + { + log = GetAPINlogEx(); + //------日志添加入数据库 + //PostNlogs(log).Wait(); + //--------end------- + } + else + { + log = GetClassNlog(); + } + StringBuilder messageString = new StringBuilder(); + messageString.Append(string.IsNullOrEmpty(log.MachineIp) ? "" : log.MachineIp + "|"); + messageString.Append(log.CreateUserId == 0 ? "" : log.CreateUserId.ToString() + "|"); + messageString.Append(string.IsNullOrEmpty(log.CreateUserName) ? "" : log.CreateUserName + "|"); + messageString.Append(string.IsNullOrEmpty(log.ActionName) ? "" : log.ActionName + "|"); + messageString.Append(string.IsNullOrEmpty(log.Parameter) ? "" : log.Parameter + "|"); + messageString.Append(string.IsNullOrEmpty(log.OldParmValue) ? "" : log.OldParmValue + "|"); + messageString.Append(string.IsNullOrEmpty(log.Message) ? "" : log.Message + "|"); + return messageString.ToString(); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs new file mode 100644 index 0000000..da85be0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.PayTool +{ + /// + /// Http方法 + /// + public class HttpMethods + { + /// + /// 创建HttpClient + /// + /// + public static HttpClient CreateHttpClient(string url, IDictionary cookies = null) + { + HttpClient httpclient; + HttpClientHandler handler = new HttpClientHandler(); + var uri = new Uri(url); + if (cookies != null) + { + foreach (var key in cookies.Keys) + { + string one = key + "=" + cookies[key]; + handler.CookieContainer.SetCookies(uri, one); + } + } + //如果是发送HTTPS请求 + if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) + { + ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; + httpclient = new HttpClient(handler); + } + else + { + httpclient = new HttpClient(handler); + } + return httpclient; + } + #region 同步请求 + + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static string Post(string url, string jsonData) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new StringContent(jsonData); + postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); + return result.Result; + } + + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static string Post(string url, byte[] req) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new ByteArrayContent(req); + Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); + return result.Result; + } + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static string Post(string url, Dictionary pairs) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new FormUrlEncodedContent(pairs); + var result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); + return result.Result; + + } + /// + /// get 请求 + /// + /// 请求地址 + /// + public static string Get(string url) + { + HttpClient httpClient = CreateHttpClient(url); + Task result = httpClient.GetAsync(url).Result.Content.ReadAsStringAsync(); + return result.Result; + } + + #endregion + + #region 异步请求 + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static Task PostAsync(string url, string jsonData) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new StringContent(jsonData); + postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); + var result = httpClient.PostAsync(url, postData); + return result; + } + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static Task PostAsync(string url, byte[] req) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new ByteArrayContent(req); + var result = httpClient.PostAsync(url, postData); + return result; + } + /// + /// post 请求 + /// + /// 请求地址 + /// 请求参数 + /// + public static Task PostAsync(string url, Dictionary pairs) + { + HttpClient httpClient = CreateHttpClient(url); + var postData = new FormUrlEncodedContent(pairs); + var result = httpClient.PostAsync(url, postData); + return result; + } + + /// + /// get 请求 + /// + /// 请求地址 + /// + public static Task GetAsync(string url) + { + HttpClient httpClient = CreateHttpClient(url); + var result = httpClient.GetAsync(url); + return result; + } + #endregion + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs new file mode 100644 index 0000000..43b6a4a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.PayTool +{ + public class PayRequesEntity + { + /// + /// 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 + /// + public string timeStamp { get; set; } + + /// + /// 随机字符串,长度为32个字符以下。 + /// + public string nonceStr { get; set; } + + /// + /// 统一下单接口返回的 prepay_id 参数值 + /// + public string package { get; set; } + + /// + /// 签名算法 + /// + public string signType { get; set; } + + /// + /// 签名 + /// + public string paySign { get; set; } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs new file mode 100644 index 0000000..b4ca760 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Xml.Linq; + +namespace WeiCloud.Core.PayTool +{ +// public class WeChatPayHelper +// { +// //private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + +// public PayRequesEntity Unifiedorder(string openid, string totalfee, string orderNo) +// { +// //var PayUrl = AppSetting.Load().WechatPayStrings.FirstOrDefault().UnifiedorderURL; +// //获取统一下单参数 +// var param = GetUnifiedOrderParam(openid, orderNo, totalfee); +// //_logger.Info(() => "微信支付统一下单 发送参数为 "+param+""); +// //统一下单后拿到的xml结果 +// var payResXML = HttpMethods.Post(AppSetting.Load().WechatPayStrings.FirstOrDefault().UnifiedorderURL, param); +// //_logger.Info(() => "微信支付统一下单 返回参数为 " + payResXML + ""); +// var payRes = XDocument.Parse(payResXML); +// var root = payRes.Element("xml"); +// var res = GetPayRequestParam(root); +// //_logger.Info(() => "微信支付统一下单 参数实体为 " + JsonConvert.SerializeObject(res) + ""); +// return res; +// } + + +// /// +// /// 取统一下单的请求参数 +// /// +// /// +// /// +// private string GetUnifiedOrderParam(string openid,string orderNo, string totalfee) +// { +// string appid = AppSetting.Load().WechatStrings.FirstOrDefault().APPID; +// string secret = AppSetting.Load().WechatStrings.FirstOrDefault().SECRET; +// string mch_id = AppSetting.Load().WechatPayStrings.FirstOrDefault().Mch_ID; +// string ip = AppSetting.Load().Configurations.FirstOrDefault().IP; +// string PayResulturl = AppSetting.Load().WechatPayStrings.FirstOrDefault().PayResulturl; + +// string strcode = "益谦文化小程序-微信支付购买";////商品描述交易字段格式根据不同的应用场景按照以下格式:APP——需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。 +// byte[] buffer = Encoding.UTF8.GetBytes(strcode); +// string body = Encoding.UTF8.GetString(buffer, 0, buffer.Length); +// System.Random Random = new System.Random(); +// var dic = new Dictionary +// { +// {"appid", appid}, +// {"mch_id", mch_id}, +// {"nonce_str", GetRandomString(20)/*Random.Next().ToString()*/}, +// {"body",body}, +// {"out_trade_no",orderNo},//商户自己的订单号码 +// {"total_fee",totalfee}, +// {"spbill_create_ip",ip},//服务器的IP地址 +// {"notify_url",PayResulturl},//异步通知的地址,不能带参数 +// {"trade_type","JSAPI" }, +// {"openid",openid} +// }; +// //加入签名 +// dic.Add("sign", GetSignString(dic)); + +// var sb = new StringBuilder(); +// sb.Append(""); +// foreach (var d in dic) +// { +// sb.Append("<" + d.Key + ">" + d.Value + ""); +// } +// sb.Append(""); +// return sb.ToString(); +// } + + +// /// +// /// 获取返回给小程序的支付参数 +// /// +// /// +// /// +// /// +// /// +// private PayRequesEntity GetPayRequestParam(XElement root) +// { +// string appid = AppSetting.Load().WechatStrings.FirstOrDefault().APPID; +// //当return_code 和result_code都为SUCCESS时才有我们要的prepay_id +// if (root.Element("return_code").Value == "SUCCESS" && root.Element("result_code").Value == "SUCCESS") +// { +// var res = new Dictionary +// { +// {"appId", appid}, +// {"timeStamp", Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds).ToString()}, +// {"nonceStr", GetRandomString(20)}, +// {"package", "prepay_id=" + root.Element("prepay_id").Value}, +// {"signType", "MD5"} +// }; +// //在服务器上签名 +// res.Add("paySign", GetSignString(res)); + +// var payEntity = new PayRequesEntity +// { +// package = res["package"], +// nonceStr = res["nonceStr"], +// paySign = res["paySign"], +// signType = res["signType"], +// timeStamp = res["timeStamp"] +// }; +// return payEntity; +// } + +// return new PayRequesEntity(); +// } + + +// /// +// /// 从字符串里随机得到,规定个数的字符串. +// /// +// /// +// /// +// /// +// private static string GetRandomString(int CodeCount) +// { +// string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; +// string[] allCharArray = allChar.Split(','); +// string RandomCode = ""; +// int temp = -1; +// Random rand = new Random(); +// for (int i = 0; i < CodeCount; i++) +// { +// if (temp != -1) +// { +// rand = new Random(temp * i * ((int)DateTime.Now.Ticks)); +// } +// int t = rand.Next(allCharArray.Length - 1); +// while (temp == t) +// { +// t = rand.Next(allCharArray.Length - 1); +// } +// temp = t; +// RandomCode += allCharArray[t]; +// } + +// return RandomCode; +// } + + +// private string GetSignString(Dictionary dic) +// { +// string key = AppSetting.Load().WechatPayStrings.FirstOrDefault().WxPayKey;//商户平台 API安全里面设置的KEY 32位长度 +// dic = dic.OrderBy(d => d.Key).ToDictionary(d => d.Key, d => d.Value);//排序 +// //连接字段 +// var sign = dic.Aggregate("", (current, d) => current + (d.Key + "=" + d.Value + "&")); +// sign += "key=" + key; +// System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); +// sign = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(sign))).Replace("-", null); +// return sign; +// } + + + +// private static Object PostUnifiedOrder(string payUrl, string para) +// { +// string result = string.Empty; +// try +// { +// HttpClient client = new HttpClient(); +// HttpContent httpContent = new StringContent(para); +// httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); +// httpContent.Headers.ContentType.CharSet = "utf-8"; +// HttpResponseMessage hrm = client.PostAsync(payUrl, httpContent).Result; +// return hrm; +// } +// catch (Exception e) +// { +// result = e.Message; +// } +// return result; +// } +//} +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs new file mode 100644 index 0000000..fecb9b2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.Report +{ + public class ReportEnum + { + + } + public class ReportGroupCalculateEnum + { + /// + /// 组内可能多个值 + /// + public const short Common = 0; + /// + /// 组内求平均 + /// + public const short Average = 1; + } + public class ReportSourceTypeEnum + { + /// + /// 实时值 + /// + public const short RealTime = 1; + /// + /// 状态值(目前是根据EquipId获取设备状态值) + /// + public const short Status = 2; + } + //public enum QueryTimeTypeEnum + //{ + // Custom = 0, + // Hour = 1, + // Day = 2, + // Month = 3, + // Year = 4 + //} + public enum ReportEnergyConsumeTypeEnum + { + /// + /// 电 + /// + ElectricPower = 1, + /// + /// 气 + /// + Gas = 2, + /// + /// 水 + /// + Water = 3, + /// + /// 热 + /// + Heat = 4, + /// + /// 碳 + /// + Carbon = 5, + /// + /// 电、气 天燃气立方米*10=能耗单位统一kWh + /// + ElectricPower_Gas = 12 + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs new file mode 100644 index 0000000..b75835a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core +{ + public class CronExpressionHelper + { + /// + /// 获取Cron表达式 + /// + /// 界面表达式 + /// + public static string GetCronExpression(string crondesc) + { + if (string.IsNullOrEmpty(crondesc)) + { + return ""; + } + string cron = ""; + try + { + string[] atr = crondesc.Trim().Split("|"); + switch (atr[0]) + { + //传递字符串 + //标记 月 日 周 天 时 分 秒 + //0 1 2 3 4 5 6 7 + + //使用字符串 + // 秒 分 时 日 月 年 + // 7 6 5 2 1 * + case "1": //每年的x月x日x时x分x秒执行 + cron = $"{atr[7]} {atr[6]} {atr[5]} {atr[2]} {atr[1]} ?"; + break; + case "2"://每季度的倒数x日x时x分x秒执行 + cron = $"{atr[7]} {atr[6]} {atr[5]} L-{Convert.ToInt32(atr[2]) - 1} 3,6,9,12 ?"; + break; + case "3"://每月的x日x时x分x秒执行 + cron = $"{atr[7]} {atr[6]} {atr[5]} {atr[2]} * ?"; + break; + case "4"://每月的倒数x日x时x分x秒执行 + cron = $"{atr[7]} {atr[6]} {atr[5]} L-{Convert.ToInt32(atr[2]) - 1} * ?"; + break; + case "5"://每周的周xx时x分x秒执行 + int a = Convert.ToInt32(atr[3]) % 7 + 1; + cron = $"{atr[7]} {atr[6]} {atr[5]} ? * {a.ToString()}"; + break; + case "6"://每隔x天的x时x分x秒执行 + cron = $"{atr[7]} {atr[6]} {atr[5]} /{atr[4]} * ?"; + break; + case "7"://每隔x时执行 + cron = $"0 0 /{atr[5]} * * ?"; + break; + case "8"://每隔x分执行 + cron = $"0 /{atr[6]} * * * ?"; + break; + case "9"://每隔x秒执行 + cron = $"/{atr[7]} * * * * ?"; + break; + default: + cron = ""; + break; + } + } + catch + { + cron = ""; + } + return cron; + } + + /// + /// 获取Cron表达式的描述 频率描述 + /// + /// + /// + public static string GetCronExpressionDescInfo(string crondesc) + { + if (string.IsNullOrEmpty(crondesc)) + { + return ""; + } + string cron = ""; + try + { + string[] atr = crondesc.Trim().Split("|"); + switch (atr[0]) + { + //传递字符串 + //标记 月 日 周 天 时 分 秒 + //0 1 2 3 4 5 6 7 + + //使用字符串 + // 秒 分 时 日 月 年 + // 7 6 5 2 1 * + + case "1": //每年的x月x日x时x分x秒执行 + cron = $"每年的{atr[1]}月{atr[2]}日{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; + break; + case "2"://每季度的倒数x日x时x分x秒执行 + cron = $"每季度的倒数第{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; + break; + case "3"://每月的x日x时x分x秒执行 + cron = $"每月{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; + break; + case "4"://每月的倒数x日x时x分x秒执行 + cron = $"每月的倒数第{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; + break; + case "5"://每周的周xx时x分x秒执行 + cron = $"每周{atr[3]}的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; + break; + case "6"://每隔x天的x时x分x秒执行 + cron = $"每隔{atr[4]}天执行一次,执行时间点:{atr[5]}时{atr[6]}分{atr[7]}秒"; + break; + case "7"://每隔x时执行 + cron = $"每隔{atr[5]}小时执行一次"; + break; + case "8"://每隔x分执行 + cron = $"每隔{atr[6]}分钟执行一次"; + break; + case "9"://每隔x秒执行 + cron = $"每隔{atr[7]}秒执行一次"; + break; + default: + cron = ""; + break; + } + } + catch + { + cron = ""; + } + return cron; + } + + /// + /// 获取时间单位 + /// + /// + /// + public static string GetUnitTypeName(int? timeunit) + { + string unit = ""; + switch (timeunit) + { + case 1: + unit = "秒"; + break; + case 2: + unit = "分"; + break; + case 3: + unit = "时"; + break; + case 4: + unit = "天"; + break; + case 5: + unit = "月"; + break; + default: + unit = ""; + break; + } + return unit; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs new file mode 100644 index 0000000..1ce1306 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs @@ -0,0 +1,99 @@ +using NRules.Fluent; +using NRules.RuleModel; +using NRules.RuleModel.Builders; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; + +namespace WeiCloud.Core.RulesEngine +{ + public class ExecuterRepository : IRuleRepository, IExecuterRepository + { + private readonly RuleRepository _internalRuleRepository; + + private IRuleSet _ruleSet; + + private List _assemblys; + + public ExecuterRepository() + { + _internalRuleRepository = new RuleRepository(); + _ruleSet = new RuleSet("default"); + _assemblys = new List(); + } + + public IEnumerable GetRuleSets() + { + //合并 + var sets = new List(); + sets.Add(_ruleSet); + sets.AddRange(_internalRuleRepository.GetRuleSets()); + return sets; + } + + /// + /// 清空规则 edit by wt + /// + public void ClearRules() + { + _ruleSet = new RuleSet("default"); + _assemblys = new List(); + } + + public void AddRule(RuleDefinition definition) + { + var builder = new RuleBuilder(); + builder.Name(definition.Name); + foreach (var condition in definition.Conditions) + { + ParsePattern(builder, condition); + } + foreach (var action in definition.Actions) + { + var param = action.Parameters.FirstOrDefault(); + var obj = GetObject(param.Type); + builder.RightHandSide().Action(ParseAction(obj, action, param.Name)); + } + _ruleSet.Add(new[] { builder.Build() }); + } + + + public void AddAssembly(IEnumerable assemblys) + { + _assemblys.AddRange(assemblys); + } + + public void AddAssembly(Assembly assembly) + { + _assemblys.Add(assembly); + } + + internal void LoadAssemblys() + { + _internalRuleRepository.Load(x => x.From(_assemblys)); + } + + + PatternBuilder ParsePattern(RuleBuilder builder, LambdaExpression condition) + { + var parameter = condition.Parameters.FirstOrDefault(); + var type = parameter.Type; + var customerPattern = builder.LeftHandSide().Pattern(type, parameter.Name); + customerPattern.Condition(condition); + return customerPattern; + } + + + LambdaExpression ParseAction(TEntity entity, LambdaExpression action, String param) where TEntity : class, new() + { + return NRulesHelper.AddContext(action as Expression>); + } + + static dynamic GetObject(Type type) + { + return System.Activator.CreateInstance(type); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs new file mode 100644 index 0000000..93872a9 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs @@ -0,0 +1,12 @@ +using System; + +namespace WeiCloud.Core.RulesEngine +{ + public interface IExecuterContainer + { + IExecuterSession CreateSession(IExecuterRepository executerRepository); + + IExecuterSession CreateSession(IExecuterRepository executerRepository, Action initializationAction); + + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs new file mode 100644 index 0000000..ea9d5f2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs @@ -0,0 +1,31 @@ +using NRules.RuleModel; +using System.Collections.Generic; +using System.Reflection; + +namespace WeiCloud.Core.RulesEngine +{ + public interface IExecuterRepository + { + /// + /// 加载运行时的规则 + /// + /// + void AddRule(RuleDefinition definition); + /// + /// 加载预设的规则 + /// + /// + void AddAssembly(IEnumerable assemblys); + /// + /// 加载预设的规则 + /// + /// + void AddAssembly(Assembly assembly); + + IEnumerable GetRuleSets(); + /// + /// 清除规则 + /// + void ClearRules(); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs new file mode 100644 index 0000000..b792b08 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace WeiCloud.Core.RulesEngine +{ + /// + /// 执行器的会话 + /// + public interface IExecuterSession + { + /// + /// 插入需要处理的对象 + /// + /// + void Insert(object fact); + + /// + /// 插入需要处理的对象 + /// + /// + void InsertAll(IEnumerable facts); + + /// + /// 执行,返回命中的规则数目 + /// + /// + int Fire(); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs new file mode 100644 index 0000000..d894468 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs @@ -0,0 +1,33 @@ +using NRules.RuleModel; +using System; +using System.Linq; +using System.Linq.Expressions; + +namespace WeiCloud.Core.RulesEngine +{ + internal class NRulesHelper + { + internal static Expression> AddContext(Expression action) + { + var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) }; + var result = Expression.Lambda>(Expression.Invoke(action, action.Parameters), convertedParameters); + return result; + } + + internal static Expression> AddContext(Expression> action) + { + var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) } + .Concat(action.Parameters).ToArray(); + var result = Expression.Lambda>(action.Body, convertedParameters); + return result; + } + + internal static Expression> AddContext(Expression> action) + { + var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) } + .Concat(action.Parameters).ToArray(); + var result = Expression.Lambda>(action.Body, convertedParameters); + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs new file mode 100644 index 0000000..245995f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs @@ -0,0 +1,26 @@ +using NRules; +using System; + +namespace WeiCloud.Core.RulesEngine +{ + public class NulesExecuterContainer : IExecuterContainer + { + public IExecuterSession CreateSession(IExecuterRepository executerRepository) + { + return CreateSession(executerRepository, null); + } + + public IExecuterSession CreateSession(IExecuterRepository executerRepository, Action initializationAction) + { + var repository = executerRepository as ExecuterRepository; + repository.LoadAssemblys(); + ISessionFactory factory = repository.Compile(); + var session = new NulesExecuterSession(factory.CreateSession()); + if (initializationAction != null) + { + initializationAction(session); + } + return session; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs new file mode 100644 index 0000000..e8939e2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs @@ -0,0 +1,30 @@ +using NRules; +using System.Collections.Generic; + +namespace WeiCloud.Core.RulesEngine +{ + public class NulesExecuterSession : IExecuterSession + { + private readonly ISession _session; + + public NulesExecuterSession(ISession session) + { + _session = session; + } + + public void Insert(object fact) + { + _session.Insert(fact); + } + + public void InsertAll(IEnumerable facts) + { + _session.Insert(facts); + } + + public int Fire() + { + return _session.Fire(); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs new file mode 100644 index 0000000..c61758d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace WeiCloud.Core.RulesEngine +{ + public class RuleDefinition + { + /// + /// 规则的名称 + /// + public String Name { get; set; } + /// + /// 约束条件 + /// + public List Conditions { get; set; } + /// + /// 执行行动 + /// + public List Actions { get; set; } + + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs new file mode 100644 index 0000000..6a37e3d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs @@ -0,0 +1,7 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + public enum Arithmetic + { + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs new file mode 100644 index 0000000..1d67aa7 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs @@ -0,0 +1,41 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + public class Energy + { + /// + /// 项目 + /// + public long? ProjectId { get; set; } + /// + /// 机房 + /// + public long? ConstId { get; set; } + + /// + /// 设备组id + /// + public long? EquGroupId { get; set; } + + /// + /// 设备类型 + /// + public long? EquType { get; set; } + + /// + /// 表达式 + /// + private string ParamDesc { get; set; } + + //初始化操作 + public Energy() + { + //初始化变量 + ParamDesc = ""; + } + + + } + + + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs new file mode 100644 index 0000000..040b6d6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs @@ -0,0 +1,25 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + public static class EquipmentEnum + { + public const string AmmeterTypeCode = "eq128016"; //电表TypeCode + public const string WatterTypeCode = "eq128017"; //水表TypeCode + public const string GasmeterTypeCode = "eq128018";//燃气表TypeCode + public const string HeatTypeCode = "eq128019";//热表TypeCode + + public const string DirectFiredCode = "eq001039";//直燃机TypeCode + + public const string HotAndColdPump = "eq002003";//冷热泵TypeCode + + public const string CoolingPump = "eq002005";//冷热泵TypeCode + } + + /// + /// 总支不平衡 + /// + public static class EnergyTypeEnum + { + public const string TotalMeterTypeCode = "eg0006"; + public const string BranchMeterTypeCode = "eg0007"; + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs new file mode 100644 index 0000000..bcbdded --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs @@ -0,0 +1,7 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + public interface IEntity + { + TKey Id { get; set; } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs new file mode 100644 index 0000000..a13c86e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs @@ -0,0 +1,54 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + /// + /// 约束条件 + /// + public class RuleConditions + { + /// + ///主键id + /// + public long? Id { get; set; } + /// + /// 所属规则 + /// + public long? RuleId { get; set; } + /// + /// 参数1 + /// + public string Param1 { get; set; } + /// + /// 四册运算符号 + /// + public string Arithmetic { get; set; } + /// + /// 参数2 + /// + public string Param2 { get; set; } + /// + /// 比较符号 + /// + public string Compare { get; set; } + /// + /// 比较参数 + /// + public string CParam1 { get; set; } + /// + /// 比较运算符号 + /// + public string CArithmetic1 { get; set; } + /// + /// 比较参数 + /// + public string CParam2 { get; set; } + /// + /// 比较运算符号 + /// + public string CArithmetic2 { get; set; } + /// + /// 比较常量 + /// + public float? Constant { get; set; } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs new file mode 100644 index 0000000..49ffccb --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + /// + /// 规则定义 + /// + public class RuleInfos + { + /// + /// 主键id + /// + public long? Id { get; set; } + public long? ProjectId { get; set; } + public long? ConstId { get; set; } + /// + /// 规则名称 + /// + public string RuleName { get; set; } + /// + /// 设备所属组号 + /// + public long EquGroup { get; set; } + + /// + /// 规则适用项目 + /// + public string[] WithProjects { get; set; } + /// + /// 规则类型 + /// + public RuleTypes RuleType { get; set; } + /// + /// 数据源开始时间 + /// + public DateTime? DataStarTime { get; set; } + /// + /// 数据源截止时间 + /// + public DateTime? DataEndTime { get; set; } + /// + /// 规则自动执行间隔 + /// + public int? Interval { get; set; } + /// + /// 间隔单位 + /// + public int? TimeUnit { get; set; } + /// + /// 执行间隔秒 + /// + public int? Intervals { get; set; } + /// + /// 规则约束条件是否互斥,互斥相当于 or ,否则相当于 and + /// + public bool IsSingle { get; set; } + /// + /// 规则是否启用 + /// + public bool IsUsing { get; set; } + /// + /// 规则描述 + /// + public string RuleDesc { get; set; } + /// + /// 公式表达式 + /// + public string Formula { get; set; } + /// + /// 定时调度Cron + /// + public string Cron { get; set; } + /// + /// 定时调度描述 + /// + public string Crondesc { get; set; } + /// + /// 约束条件 + /// + public List RuleConditionList { get; set; } + + /// + /// 规则参数条件 + /// + public List RuleConditionParamList { get; set; } + + /// + /// 实际执行开始时间 数据的开始时间 + /// + public DateTime? ActualStartTime { get; set; } + /// + /// 实际执行结束时间 数据的结束时间 + /// + public DateTime? ActualEndTime { get; set; } + /// + /// 设备类型 + /// + + public long? EquType { get; set; } + /// + /// 实时参数表达式 + /// + public List RealParamGicExList { get; set; } + /// + /// 实时参数公式 + /// + public List RealFormulaGics { get; set; } + /// + /// 实时参数采集公式解析的设备信息 + /// + public List Equids { get; set; } + /// + /// 设备类型ids + /// + public List EquPTypes { get; set; } + + /// + /// 公式的最终表达式子 用于报警描述 + /// + public string ParamDesc { get; set; } + + /// + /// 能耗分项id + /// + public long? Subentryid { get; set; } + + /// + /// 时间间隔 cron的时间周期 + /// + public int Timeperiod { get; set; } = 0; + } + + /// + /// 实时参数公式 + /// + public class RealFormulaGic + { + public long Id { get; set; } + public string EquName { get; set; } + public string Formula { get; set; } + + public string Paramname { get; set; } + public long? Rid { get; set; } + } + + /// + /// 规则的时间区间 + /// + public class RuleTimeSection + { + /// + /// 返回结果 + /// + public bool result { get; set; } + /// + /// 开始时间 + /// + public DateTime? startTime { get; set; } + /// + /// 结束时间 + /// + public DateTime? endTime { get; set; } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs new file mode 100644 index 0000000..f6a21c1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs @@ -0,0 +1,19 @@ +namespace WeiCloud.Core.RulesEngine.RulesModels +{ + public class RuleTypes + { + public long? Id { get; set; } + public string TypeName { get; set; } + + public long? ParentId { get; set; } + + public string EqType { get; set; } + + public string ParamIds { get; set; } + public long? Fautype { get; set; } + + public long? Fauclass { get; set; } + + public string Energytypes { get; set; } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs b/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs new file mode 100644 index 0000000..320e2da --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs @@ -0,0 +1,82 @@ +using Newtonsoft.Json; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.InfoModels; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core.Schedule +{ + public static class ScheduleItemConvert + { + public static TaskMessageHubModel TaskMessageToJobSchedulerConfig(this JobSchedulerConfigItem input) + { + TaskMessageHubModel jobConfigItem = new TaskMessageHubModel + { + JobName = input.JobName, + JobGroup = input.JobGroup, + TriggerName = input.TriggerName, + TriggerGroup = input.TriggerGroup, + IsEnable = input.IsEnable, + Id = input.Id + }; + + jobConfigItem.JobDataMapKey = input.JobDataMapKey; + jobConfigItem.Concurrent = input.Concurrent; + + jobConfigItem.StartAt = input.StartAt; + jobConfigItem.EndAt = input.EndAt; + jobConfigItem.SimpleScheduleIn = input.SimpleScheduleIn; + jobConfigItem.SimpleScheduleCount = input.SimpleScheduleCount; + jobConfigItem.CronExpression = input.CronExpression; + jobConfigItem.IntervalTime = input.IntervalTime; + jobConfigItem.Priority = input.Priority; + jobConfigItem.ServiceName = input.ServiceName; + jobConfigItem.IntervalUnit = input.IntervalUnit; + jobConfigItem.TaskName = input.TaskName; + jobConfigItem.AssemblyItem = input.AssemblyItem; + jobConfigItem.IsDelete = input.IsDeleted; + return jobConfigItem; + } + public static JobSchedulerConfig TaskMessageToJobSchedulerConfig(this TaskMessageHubModel input, JobSchedulerConfig jobConfigItem) + { + if (jobConfigItem == null) + { + jobConfigItem = new JobSchedulerConfig + { + JobName = input.JobName, + JobGroup = input.JobGroup, + TriggerName = input.TriggerName, + TriggerGroup = input.TriggerGroup, + Id = UidGenerator.Uid() + }; + } + else + { + input.JobName = jobConfigItem.JobName; + input.JobGroup = jobConfigItem.JobGroup; + input.TriggerName = jobConfigItem.TriggerName; + input.TriggerGroup = jobConfigItem.TriggerGroup; + input.IsEnable = jobConfigItem.IsEnable != null && (bool)jobConfigItem.IsEnable == true ? (byte)1 : (byte)0; + } + + jobConfigItem.JobDataMapKey = input.JobDataMapKey; + jobConfigItem.Concurrent = input.Concurrent == 1; + + jobConfigItem.StartAt = input.StartAt; + jobConfigItem.EndAt = input.EndAt; + jobConfigItem.SimpleScheduleIn = input.SimpleScheduleIn; + jobConfigItem.SimpleScheduleCount = input.SimpleScheduleCount; + jobConfigItem.CronExpression = input.CronExpression; + jobConfigItem.IntervalTime = input.IntervalTime; + jobConfigItem.Priority = input.Priority; + jobConfigItem.ServiceName = input.ServiceName; + jobConfigItem.IsEnable = input.IsEnable == 1; + jobConfigItem.IntervalUnit = input.IntervalUnit; + jobConfigItem.TaskName = input.TaskName; + if (input.AssemblyItem != null) + jobConfigItem.AssemblyItem = JsonConvert.SerializeObject(input.AssemblyItem); + else + jobConfigItem.AssemblyItem = string.Empty; + return jobConfigItem; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs new file mode 100644 index 0000000..6eb9420 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs @@ -0,0 +1,135 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services.CarbonEmission +{ + /// + /// 碳排放计算公式 + /// + public class CarbonEmissionService : ICarbonEmissionService + { + private readonly WeiCloudDBUserCenterContext _weiCloudDBUser; + public CarbonEmissionService(WeiCloudDBUserCenterContext weiCloudDBUser) + { + _weiCloudDBUser = weiCloudDBUser; + } + /* + 1、电碳排放tCO2=碳排放因子×用电量(kWh)/1000;各区域电网碳排放因子见右表 + 2、天然气碳排放tCO2=天然气用量(万m3)×低位热值×44/12×单位热值含碳量×碳氧化率 + 低位热值=389.3(GJ/万Nm3) + 单位热值含碳量=0.0153(tC/GJ) + 碳氧化率=99% + 3、外购热力碳排放tCO2=热力碳排放因子0.11×用热量GJ + 4、总碳排放量=电碳排放+天然气碳排放+外购热力碳排放 + */ + /// + /// 碳排放计算公式 + /// + /// + /// + /// + /// + public async Task GetValue(double ammeterDWSum, double gasDWSum, long projectId) + { + var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); + var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new + { + t.Paraname, + t.Realvalue + }).ToListAsync(); + + double carbonEmissionFactor = 0; + if (sysConfigs.Count() == 1) + { + carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); + } + else if (sysConfigs.Count() == 2) + { + carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); + } + var sumCO2 = ammeterDWSum * carbonEmissionFactor / 1000 + (gasDWSum / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; + return sumCO2; + } + /// + /// 碳排放计算公式 + /// + /// + /// + /// + /// + /// + public async Task GetValue(double ammeterDWSum, double gasDWSum, string cityCode, List sysConfigs) + { + double carbonEmissionFactor = 0; + if (sysConfigs.Count() == 1) + { + carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); + } + else if (sysConfigs.Count() == 2) + { + carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == cityCode).Realvalue); + } + var sumCO2 = ammeterDWSum * carbonEmissionFactor / 1000 + (gasDWSum / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; + return sumCO2; + } + /// + /// 碳排放系数 电 + /// + /// + /// + public async Task GetValue_Elect(long projectId) + { + var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); + var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new + { + t.Paraname, + t.Realvalue + }).ToListAsync(); + double carbonEmissionFactor = 0; + if (sysConfigs.Count() == 1) + { + carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); + } + else if (sysConfigs.Count() == 2) + { + carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); + } + var sumCO2 = carbonEmissionFactor / 1000 ; + return sumCO2; + } + /// + /// 碳排放系数 气 + /// + /// + /// + public async Task GetValue_Gas(long projectId) + { + var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); + var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new + { + t.Paraname, + t.Realvalue + }).ToListAsync(); + + double carbonEmissionFactor = 0; + if (sysConfigs.Count() == 1) + { + carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); + } + else if (sysConfigs.Count() == 2) + { + carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); + } + var sumCO2 =(1 / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; + return sumCO2; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs new file mode 100644 index 0000000..18efa30 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services.CarbonEmission +{ + public interface ICarbonEmissionService + { + Task GetValue(double ammeterDWSum, double gasDWSum, long projectId); + Task GetValue(double ammeterDWSum, double gasDWSum, string cityCode, List sysConfigs); + Task GetValue_Elect(long projectId); + Task GetValue_Gas(long projectId); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs new file mode 100644 index 0000000..2defde9 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs @@ -0,0 +1,213 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Core.BaseCore; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.DataQuality; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class ConstrInfoGainCoreService : Grain, IConstrInfoGainCoreService + { + private readonly WeiCloudDBContext _context; + private readonly WeiCloudDBUserCenterContext _userContext; + private readonly IListService _listService; + private readonly IDictionaryService _dictionaryService; + private readonly ILogger _logger; + public ConstrInfoGainCoreService(WeiCloudDBContext context, WeiCloudDBUserCenterContext userContext, IListService listService, IDictionaryService dictionaryService, ILogger logger) + { + _context = context; + _userContext = userContext; + _listService = listService; + _dictionaryService = dictionaryService; + _logger = logger; + } + /// + /// 批量redis获取建筑物 + /// + /// 建筑物集合 + public async Task> GetAllConstructionInfoRedis() + { + //ConstructionInfo construction = new ConstructionInfo(); + //var result = _dictionaryService.GetValue(construction.GetType().Name); + //var list = result.Values.ToList(); + //return await Task.FromResult(list); + return await _context.ConstructionInfo.TagWith("SubDB").AsNoTracking().ToListAsync(); + } + + public async Task GetConstModelById(long id) + { + //ConstructionInfo constInfo = new ConstructionInfo(); + //constInfo = _dictionaryService.GetValue(constInfo.GetType().Name)[id.ToString()]; + //return await Task.FromResult(constInfo); + return _context.ConstructionInfo.TagWith("SubDB").FirstOrDefault(t => t.Id == id); + } + public async Task> GetConstByKeys(string[] keys) + { + //List consts = new List(); + //ConstructionInfo c = new ConstructionInfo(); + //consts = _dictionaryService.GetValue(c.GetType().Name, keys).Select(d => d.Value).ToList(); + //if (consts != null) + //{ + // consts = consts.Where(d => d != null && d.Id > 0).ToList(); + //} + var ids = keys.Select(t => long.Parse(t)).ToList(); + return _context.ConstructionInfo.Where(t => ids.Contains(t.Id)).TagWith("SubDB").AsNoTracking().ToList(); + } + private List GetConstTreeByParentId(long parentId, List constList) + { + List conSmpleList = new List(); + conSmpleList = (from c in constList + where c.Parentid == parentId + orderby c.Constinfo + select new ConstructionInfoTreeNew + { + Id = c.Id, + Label = c.Constinfo, + Constcode = c.Constcode, + Parentid = c.Parentid, + ConstType = c.Consttype, + Children = GetConstTreeByParentId(c.Id, constList) + }).ToList(); + return conSmpleList; + } + /// + /// 查询建筑物树结构 + /// + /// + /// + /// + /// + public async Task> GetConstTreeByProjectId(long projectId, int isUsing, int? level) + { + try + { + //1.根据用户的建筑物权限 ConstantIds + var currentUser = CurrentContext.GetContext(); + //2.根据项目id 以及1中的建筑物ids 从 redis中获取要过滤的建筑物信息 + //var data = _dictionaryService.GetValue("ConstructionInfo").Values.Where(op => op.Projectid == projectId && op.Isusing == 1); + var query = _context.ConstructionInfo.Where(op => op.Projectid == projectId && op.Isusing == 1); + + if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) + { + query = query.Where(op => currentUser.ConstIds.Contains(op.Id)); + } + + if (isUsing >= 0) + { + query = query.Where(o => o.Isusing == isUsing); + } + if (level == 1) + { + query = query.Where(o => o.Parentid == 0); + } + //if (show >=0) + //{ + // data = data.Where(t => t.Isshow == show); + //} + //3.对建筑物信息 进行排序展现 + var data1 = await query.OrderBy(o => o.Constinfo).AsNoTracking().ToListAsync(); + //4.递归组成树根据parentid=0找到一级列表 + var conSmpleList = (from c in data1 + where c.Parentid == 0 + orderby c.Constinfo + select new ConstructionInfoTreeNew + { + Id = c.Id, + Label = c.Constinfo, + Constcode = c.Constcode, + Parentid = c.Parentid, + ConstType = c.Consttype, + Children = GetConstTreeByParentId(c.Id, data1) + }).ToList(); + return await Task.FromResult(conSmpleList); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetConstTreeByProjectIdAsync", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return await Task.FromResult(new List()); + } + /// + /// 查询建筑物树结构 + /// + /// + /// + public async Task> GetConstEquipsTreeByProjectId(long projectId) + { + try + { + //1.根据用户的建筑物权限 ConstantIds + var currentUser = CurrentContext.GetContext(); + //2.根据项目id 以及1中的建筑物ids 从 redis中获取要过滤的建筑物信息 + //var data = _dictionaryService.GetValue("ConstructionInfo").Values.Where(op => op.Projectid == projectId && op.Isusing == 1); + var query = _context.ConstructionInfo.Where(op => op.Projectid == projectId && op.Isusing == 1); + + if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) + { + query = query.Where(op => currentUser.ConstIds.Contains(op.Id)); + } + + //3.对建筑物信息 进行排序展现 + var data1 = await query.OrderBy(o => o.Constinfo).AsNoTracking().ToListAsync(); + + var equipInfos = await _context.EquipmentInfo.Where(t => t.Projectid == projectId && t.State == 1).AsNoTracking().ToListAsync(); + + + //4.递归组成树根据parentid=0找到一级列表 + var conSmpleList = (from c in data1 + where c.Parentid == 0 + orderby c.Constinfo + select new ConstInfoEquipTreeNewModel + { + Id = c.Id, + Label = c.Constinfo, + ConstCode = c.Constcode, + ParentId = c.Parentid, + ConstType = c.Consttype, + Equips = equipInfos.Where(t => t.Constid == c.Id).Select(t => new ConstInfoEquipEquipModel + { + Id = t.Id, + EquipName = t.Eqname + }).ToList(), + Children = GetConstTreeByParentId(c.Id, data1, equipInfos) + }).ToList(); + return await Task.FromResult(conSmpleList); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetConstTreeByProjectIdAsync", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return await Task.FromResult(new List()); + } + private List GetConstTreeByParentId(long parentId, List constList, List equipInfos) + { + List conSmpleList = new List(); + conSmpleList = (from c in constList + where c.Parentid == parentId + orderby c.Constinfo + select new ConstInfoEquipTreeNewModel + { + Id = c.Id, + Label = c.Constinfo, + ConstCode = c.Constcode, + ParentId = c.Parentid, + ConstType = c.Consttype, + Equips = equipInfos.Where(t => t.Constid == c.Id).Select(t => new ConstInfoEquipEquipModel + { + Id = t.Id, + EquipName = t.Eqname + }).ToList(), + Children = GetConstTreeByParentId(c.Id, constList, equipInfos) + }).ToList(); + return conSmpleList; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs new file mode 100644 index 0000000..09e97ed --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DataQuality; + +namespace WeiCloud.Core.Services.DataStream +{ + public interface IProjectParamMethodRuleCoreService + { + Task>> GetBindNewCodeNumsV02(Dictionary paramConfigIdDic, List paramConfigs = null, List realMapParamConfigs = null); + Task GetNewCodeNum(long qualityMethodId); + Task GetNewParamGroupCodeNum(long qualityTypeId); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs new file mode 100644 index 0000000..05464ea --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.DataStreamModels; + +namespace WeiCloud.Core.Services.DataStream +{ + public interface ISubscribePointCoreService + { + Task> SubscribePoint(long projectId, List pointIds, string clientId = "", bool isValueChanged = false); + /// + /// 订阅主题 项目所有点位 + /// + /// + /// + /// + /// + Task> SubscribePointAll(long projectId, string clientId = "", bool isValueChanged = false); + Task> SubscribePointHeartbeat(string clientId = ""); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs new file mode 100644 index 0000000..97c64af --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.DataStream +{ + public interface ITimeSeqService + { + Task> QueryEquipRealDataDoc(DateTime queryTime, long projectId, List equipIds); + Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds); + Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, long realDataId, bool isRepaired = false); + Task> QueryRealDataItemByRealIds(DateTime queryTime, List realDataIds); + Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, List realDataIds, bool isMore = false); + Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1); + //Task>> RecoverHistoryData(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs new file mode 100644 index 0000000..14533b1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs @@ -0,0 +1,202 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DataQuality; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Services.DataStream +{ + public class ProjectParamMethodRuleCoreService : IProjectParamMethodRuleCoreService + { + private readonly ILogger _logger; + private readonly WeiCloundDBDataQualityContext _weiCloudDataQualityDBContext; + public ProjectParamMethodRuleCoreService(ILogger logger, WeiCloundDBDataQualityContext weiCloudDataQualityDBContext) + { + _logger = logger; + _weiCloudDataQualityDBContext = weiCloudDataQualityDBContext; + } + /// + /// 生成新code + /// + /// + /// + public async Task GetNewCodeNum(long qualityMethodId) + { + long num = 1; + long i = 1; + try + { + var existingCodes = await _weiCloudDataQualityDBContext.ParamConfig.Where(t => t.QualityMethodId == qualityMethodId && t.IsDeleted == false).AsNoTracking().Select(t => t.Code).ToListAsync(); + + if (existingCodes.Count() > 0) + { + var codeNums = new List { }; + foreach (var existingCode in existingCodes) + { + try + { + codeNums.Add(int.Parse(existingCode.Split("-").Last())); + } + catch (Exception) + { + } + } + codeNums = codeNums.OrderBy(t => t).ToList(); + while (true) + { + if (!codeNums.Any(t => t == i)) + { + break; + } + ++i; + } + } + num = i; + } + catch (Exception ex) + { + Random rd = new Random(); + num = rd.Next(10000, 99999); + _logger.LogError(new LoggerWarp(actionName: "GetNewCodeNum", ex: ex).GetMessage()); + } + return num; + } + /// + /// 绑定时生成新code + /// + /// key方法规则Id、参数Code个数 + /// + /// + /// + public async Task>> GetBindNewCodeNumsV02(Dictionary paramConfigIdDic, List paramConfigs = null, List realMapParamConfigs = null) + { + var paramConfigIds = paramConfigIdDic.Select(t => t.Key).ToList(); + if (paramConfigs == null || paramConfigs.Count() == 0) + { + paramConfigs = await _weiCloudDataQualityDBContext.ParamConfig.AsNoTracking().Where(t => paramConfigIds.Contains(t.Id)).Select(t => new ParamConfig + { + Code = t.Code, + Id = t.Id + }).ToListAsync(); + } + else + { + paramConfigs = paramConfigs.Where(t => paramConfigIds.Contains(t.Id)).ToList(); + } + + if (realMapParamConfigs == null || realMapParamConfigs.Count() == 0) + { + realMapParamConfigs = await _weiCloudDataQualityDBContext.ParamConfig.Where(t => paramConfigIds.Contains(t.ReferId) && t.IsDeleted == false).AsNoTracking().ToListAsync(); + } + else + { + realMapParamConfigs = realMapParamConfigs.Where(t => paramConfigIds.Contains(t.ReferId)).ToList(); + } + + Dictionary> resultItems = new Dictionary> { }; + + foreach (var paramConfigDicItem in paramConfigIdDic) + { + var paramConfig = paramConfigs.FirstOrDefault(t => t.Id == paramConfigDicItem.Key); + var nums = new List { }; + + + #region 计算 + var existingCodes = realMapParamConfigs.Where(t => t.ReferId == paramConfig.Id).Select(t => t.Code).ToList(); + + long i = 1; + + var codeNums = new List { }; + if (existingCodes.Count() > 0) + { + foreach (var existingCode in existingCodes) + { + try + { + codeNums.Add(int.Parse(existingCode.Split("-").Last())); + } + catch (Exception) + { + } + } + codeNums = codeNums.OrderBy(t => t).ToList(); + } + while (nums.Count() <= paramConfigDicItem.Value) + { + try + { + if (!codeNums.Any(t => t == i) && !nums.Any(t => t == i)) + { + nums.Add(i); + } + ++i; + } + catch (Exception ex) + { + } + } + #endregion + var numStrs = new List { }; + foreach (var num in nums) + { + numStrs.Add($"{paramConfig.Code}-{num}"); + } + resultItems.Add(paramConfig.Id, numStrs); + } + + return resultItems; + } + + + /// + /// 生成新code + /// + /// + /// + public async Task GetNewParamGroupCodeNum(long qualityTypeId) + { + long num = 1; + long i = 1; + try + { + var existingCodes = await _weiCloudDataQualityDBContext.ParamGroup.Where(t => t.GroupTypeId == qualityTypeId && t.IsDeleted == false).AsNoTracking().Select(t => t.Code).ToListAsync(); + + if (existingCodes.Count() > 0) + { + var codeNums = new List { }; + foreach (var existingCode in existingCodes) + { + try + { + codeNums.Add(int.Parse(existingCode.Split("-").Last())); + } + catch (Exception) + { + } + } + codeNums = codeNums.OrderBy(t => t).ToList(); + while (true) + { + if (!codeNums.Any(t => t == i)) + { + break; + } + ++i; + } + } + num = i; + } + catch (Exception ex) + { + Random rd = new Random(); + num = rd.Next(10000, 99999); + _logger.LogError(new LoggerWarp(actionName: "GetNewCodeNum", ex: ex).GetMessage()); + } + return num; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs new file mode 100644 index 0000000..8cbef3f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs @@ -0,0 +1,175 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; +using System.Net.Http.Headers; +using WeiCloud.Entity.LogicModels.DataStreamModels; +using NPOI.Util; + +namespace WeiCloud.Core.Services.DataStream +{ + public class SubscribePointCoreService : ISubscribePointCoreService + { + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + private readonly IHttpClientFactory _httpClientFactory; + private readonly IServiceScopeFactory _serviceScopeFactory; + public SubscribePointCoreService(IHttpClientFactory httpClientFactory, IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration) + { + _logger = logger; + _configuration = configuration; + _httpClientFactory = httpClientFactory; + _serviceScopeFactory = serviceScopeFactory; + } + /// + /// 订阅主题 + /// + /// + /// 点位 + /// + /// 值变化时推送 + /// + public async Task> SubscribePoint(long projectId, List pointIds, string clientId = "", bool isValueChanged = false) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + string dbRealDataResultStr = string.Empty; + try + { + if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "SubscribeMQTT:ApiUrl为空!"; + return result; + } + var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePoint"; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(15); + if (string.IsNullOrEmpty(clientId)) + { + clientId = _configuration["SubscribeMQTT:TopicName"]; + } + var body = JsonConvert.SerializeObject(new + { + ProjectId = projectId, + PointIds = pointIds, + ClientId = clientId, + IsValueChanged = isValueChanged + }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var httpResponse = await client.PostAsync(apiUrl, byteContent); + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + Console.WriteLine($"点位订阅:{dbRealDataResultStr}"); + result = JsonConvert.DeserializeObject>(dbRealDataResultStr); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("点位订阅:{0} {1}", dbRealDataResultStr, pointIds.Join(","))).GetNlogMessage()); + } + return result; + } + + + /// + /// 订阅主题 项目所有点位 + /// + /// + /// + /// + /// + public async Task> SubscribePointAll(long projectId, string clientId = "", bool isValueChanged = false) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + string dbRealDataResultStr = string.Empty; + try + { + if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "SubscribeMQTT:ApiUrl为空!"; + return result; + } + var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePointAll"; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(15); + if (string.IsNullOrEmpty(clientId)) + { + clientId = _configuration["SubscribeMQTT:TopicName"]; + } + var body = JsonConvert.SerializeObject(new + { + ProjectId = projectId, + ClientId = clientId, + IsValueChanged = isValueChanged + }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var httpResponse = await client.PostAsync(apiUrl, byteContent); + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + Console.WriteLine($"点位订阅:{dbRealDataResultStr}"); + result = JsonConvert.DeserializeObject>(dbRealDataResultStr); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePointAll", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); + } + return result; + } + + /// + /// 定时心跳 + /// + /// + /// + public async Task> SubscribePointHeartbeat(string clientId = "") + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + string dbRealDataResultStr = string.Empty; + try + { + if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "SubscribeMQTT:ApiUrl为空!"; + return result; + } + if (string.IsNullOrEmpty(clientId)) + { + clientId = _configuration["SubscribeMQTT:TopicName"]; + } + var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePointHeartbeat?clientId=" + clientId; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(5); + var httpResponse = await client.GetAsync(apiUrl); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + } + result = JsonConvert.DeserializeObject>(dbRealDataResultStr); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("点位订阅:{0}", dbRealDataResultStr)).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs new file mode 100644 index 0000000..7c1c1c6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs @@ -0,0 +1,607 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoDB.Driver.Linq; +using Newtonsoft.Json; +using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; +using WeiCloud.Entity.Models; +using WeiCloud.Utils.Mongo; + +namespace WeiCloud.Core.Services.DataStream +{ + public class TimeSeqService : ITimeSeqService + { + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + private readonly IHttpClientFactory _httpClientFactory; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IOptions> _changeTime; + public TimeSeqService(IHttpClientFactory httpClientFactory, IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration, IOptions> changeTime) + { + _logger = logger; + _configuration = configuration; + _httpClientFactory = httpClientFactory; + _serviceScopeFactory = serviceScopeFactory; + _changeTime = changeTime; + } + /// + /// 根据时间查询实时数据 + /// + /// + /// + /// + /// + /// + public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, long realDataId, bool isRepaired = false) + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + string dbRealDataResultStr = string.Empty; + try + { + var timeDBApiQueryUrl = _configuration["TimeDBApiQueryUrl"]; + //var timeDBApiUrl = _configuration["TimeDBApiUrl"]; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromMinutes(5); + var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, Id = realDataId, IsRepaired = isRepaired }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/data/QueryRealDataItem", byteContent); + var httpResponse = await client.PostAsync(timeDBApiQueryUrl, byteContent); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + } + result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};{1}", ex.Message, realDataId.ToString())).GetNlogMessage()); + } + return result; + } + + /// + /// 根据参数Id查询当前时刻值 + /// + /// + /// + /// + public async Task> QueryRealDataItemByRealIds(DateTime queryTime, List realDataIds) + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + string dbRealDataResultStr = string.Empty; + try + { + var timeDBApiQueryUrl = _configuration["TimeDBApiQueryByTimeRealIdsUrl"]; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromMinutes(3); + var body = JsonConvert.SerializeObject(new { time = queryTime, RealIds = realDataIds }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/data/QueryRealDataItem", byteContent); + var httpResponse = await client.PostAsync(timeDBApiQueryUrl, byteContent); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + } + result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + if (result != null && result.Data != null) + { + return result.Data; + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItemByRealIds", string.Format("抛出了异常信息: {0};{1}", ex.Message, realDataIds.ToString())).GetNlogMessage()); + } + return new List { }; + } + + public async Task> QueryEquipRealDataDoc(DateTime queryTime, long projectId, List equipIds) + { + var result = new List { }; + try + { + var startTime = queryTime.AddMinutes(-6); + //var startTime = queryTime.AddHours(-1); + var endTime = queryTime.AddMinutes(6); + using var scope = _serviceScopeFactory.CreateScope(); + var userCenterContext = scope.ServiceProvider.GetRequiredService(); + var projectInfo = userCenterContext.ProjectInfo.FirstOrDefault(t => t.Id == projectId); + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) + .Options; + using var _contextDB = new WeiCloudDBContext(contextOptions); + + var equipInfos = await _contextDB.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().Select(t => new + { + t.Id, + t.Eqtype + }).ToListAsync(); + var equipTypeIds = equipInfos.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + + var equipTypes = await userCenterContext.EquipmentType.Where(t => equipTypeIds.Contains(t.Id)).Select(t => new { t.Id, t.Tablename }).AsNoTracking().ToListAsync(); + var mongoUtil = scope.ServiceProvider.GetRequiredService(); + var db = mongoUtil.GetClient().GetDatabase("RealDataDB"); + + foreach (var equipType in equipTypes) + { + var collection = db.GetCollection(equipType.Tablename); + var _equipInfos = equipInfos.Where(t => t.Eqtype == equipType.Id); + if (_equipInfos.Count() == 0) + { + continue; + } + + var filter = Builders.Filter; + //filter.Gt("CreateTime", queryTime); + //filter.In("EquiId", _equipInfos.Select(t => t.Id).ToArray()); + var _equipIds = _equipInfos.Select(t => t.Id).ToArray(); + //_equipIds = new long[] { 495360044170798 }; + //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).ToListAsync(); + var sort = Builders.Sort; + var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")).ToListAsync(); + //var docs = collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")); + + foreach (var doc in docs) + { + var equipIdDoc = doc.GetValue("EquipId"); + try + { + long equipId = equipIdDoc.ToLong(); + //if (!long.TryParse(equipIdDoc.AsString, out equipId)) + //{ + // continue; + //} + //if (!result.Any(t => t.EquipId == equipIdDoc.AsInt64)) + if (!result.Any(t => t.EquipId == equipId)) + { + try + { + var createTimeDoc = doc.GetValue("CreateTime"); + var updateTimeDoc = doc.GetValue("UpdateTime"); + var docParams = doc.Where(t => t.Name != "_id" + && t.Name != "CreateTime" + && t.Name != "EquipId" + && t.Name != "CreateTime" + && t.Name != "UpdateTime").ToList(); + var item = new EquipParamRealDataModel + { + EquipId = equipId, + CreateTime = createTimeDoc.ToLocalTime(), + UpdateTime = updateTimeDoc.ToLocalTime(), + Params = new Dictionary { } + //Params = doc.Where(t => t.Name != "_id" && t.Name != "CreateTime" && t.Name != "EquipId" && t.Name != "CreateTime" && t.Name != "UpdateTime").ToDictionary(t => t.Name, t => t.Value.AsNullableDouble) + }; + foreach (var docParam in docParams) + { + if (docParam.Value.IsDouble) + { + item.Params[docParam.Name] = docParam.Value.ToDouble(); + } + else if (docParam.Value.IsInt32) + { + item.Params[docParam.Name] = docParam.Value.AsInt32; + } + else if (docParam.Value.IsInt64) + { + item.Params[docParam.Name] = docParam.Value.AsInt64; + } + else if (docParam.Value.IsDecimal128) + { + item.Params[docParam.Name] = (double)docParam.Value.ToDecimal(); + } + } + + result.Add(item); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData-Doc1", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData-Doc2", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData", string.Format("抛出了异常信息: {0};{1}", ex.Message, equipIds.Join(","))).GetNlogMessage()); + } + return result; + } + + public async Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds) + { + var result = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var userCenterContext = scope.ServiceProvider.GetRequiredService(); + var projectInfo = userCenterContext.ProjectInfo.FirstOrDefault(t => t.Id == projectId); + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) + .Options; + using var _contextDB = new WeiCloudDBContext(contextOptions); + + var equipInfos = await _contextDB.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().Select(t => new + { + t.Id, + t.Eqtype + }).ToListAsync(); + var equipTypeIds = equipInfos.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + + var equipTypes = await userCenterContext.EquipmentType.Where(t => equipTypeIds.Contains(t.Id)).Select(t => new { t.Id, t.Tablename }).AsNoTracking().ToListAsync(); + var mongoUtil = scope.ServiceProvider.GetRequiredService(); + var db = mongoUtil.GetClient().GetDatabase("RealDataDB"); + + foreach (var equipType in equipTypes) + { + var collection = db.GetCollection(equipType.Tablename); + var _equipInfos = equipInfos.Where(t => t.Eqtype == equipType.Id); + if (_equipInfos.Count() == 0) + { + continue; + } + + var filter = Builders.Filter; + //filter.Gt("CreateTime", queryTime); + //filter.In("EquiId", _equipInfos.Select(t => t.Id).ToArray()); + var _equipIds = _equipInfos.Select(t => t.Id).ToArray(); + //_equipIds = new long[] { 495360044170798 }; + //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).ToListAsync(); + var sort = Builders.Sort; + //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")).ToListAsync(); + var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Ascending("CreateTime")).ToListAsync(); + + foreach (var doc in docs) + { + var equipIdDoc = doc.GetValue("EquipId"); + + var item = result.FirstOrDefault(t => t.EquipId == equipIdDoc.AsInt64); + if (item == null) + { + item = new EquipIntervalParamRealDataModel { EquipId = equipIdDoc.AsInt64, Items = new List { } }; + result.Add(item); + } + var itemDic = doc.Where(t => t.Name != "_id" && t.Name != "CreateTime" && t.Name != "EquipId" && t.Name != "CreateTime" && t.Name != "UpdateTime").ToDictionary(t => t.Name, t => t.Value.AsNullableDouble); + var createTimeDoc = doc.GetValue("CreateTime"); + var updateTimeDoc = doc.GetValue("UpdateTime"); + item.Items.Add(new EquipRangeParamRealDataItemModel + { + EquipId = equipIdDoc.AsInt64, + CreateTime = createTimeDoc.ToLocalTime(), + UpdateTime = updateTimeDoc.ToLocalTime(), + Params = itemDic + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData", string.Format("抛出了异常信息: {0};{1}", ex.Message, equipIds.Join(","))).GetNlogMessage()); + } + return result; + } + public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, List realDataIds, bool isMore = false) + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + string dbRealDataResultStr = string.Empty; + try + { + var timeDBApiUrl = _configuration["TimeDBApiUrl"]; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromMinutes(3); + var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds, IsMore = isMore }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + } + result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + /// + /// 获取区间值,缺值默认 + /// + /// + /// + /// + /// + /// + /// + /// + public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1) + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + string dbRealDataResultStr = string.Empty; + try + { + var times = new List { }; + var _startTime = startTime; + while (_startTime < endTime) + { + times.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddSeconds(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddMinutes(interval); + } + } + var timeDBApiUrl = _configuration["TimeDBApiUrl"]; + ApiResult> resultDataStream = new ApiResult>(); + //要替换日期的历史数据 2023-12-15 + var test = _changeTime.Value; + + //var ds = _configuration["SpecialHistoricalCurveDate1:SearchDate"]; + + //var dse = _configuration["SpecialHistoricalCurveDate1:ActualityDate"]; + var specialHistoricalCon = _configuration.GetSection("SpecialHistoricalCurveDate").Get(); + //var changeTimesP = JsonConvert.DeserializeObject >(_configuration["SpecialHistoricalCurveDate"]); + var changeTimes = new List(); + if (specialHistoricalCon != null && specialHistoricalCon.Length > 0) + { + foreach (var e in specialHistoricalCon) + { + changeTimes.Add(new SpecialHistoricalCurveDate { SearchDate = e.SearchDate, ActualityDate = e.ActualityDate }); + } + } + List dates = new List(); + List dateTimeNew = new List();//重组后的时间段 + if (changeTimes != null && changeTimes.Count > 0) + { + var dateStart = startTime.Date; + var dateEnd = endTime.Date; + bool isNeedChange = false;//是否需要替换某个日期的历史数据 + //dates.Add(dateStart); + var t = dateStart; + while (t <= dateEnd) + { + dates.Add(t); + t = t.AddDays(1); + } + foreach (var d in changeTimes) + { + DateTime sDate = Convert.ToDateTime(d.SearchDate); + DateTime aDate = Convert.ToDateTime(d.ActualityDate); + if (sDate >= dateStart && sDate <= dateEnd) + { + isNeedChange = true; + dates.Add(aDate.Date); + dates.Remove(sDate.Date); + } + } + if (!isNeedChange)//没有要替换日期的数据 + { + resultDataStream = await GetRealHistory(realDataIds, timeDBApiUrl, startTime, endTime); + } + else//有要替换日期的数据 + { + dates = dates.Distinct().OrderBy(d => d).ToList(); + int j = 0; + for (int i = 0; i < dates.Count; i++) + { + + if (i == 0) + { continue; } + if (i != 0 && dates[i] == dates[i - 1].AddDays(1)) + { + if (i == dates.Count - 1) + { + DateItem tie = new DateItem(); + tie.Start = dates[j]; + tie.End = dates[i].AddHours(23).AddMinutes(59).AddSeconds(59); + dateTimeNew.Add(tie); + } + continue; + } + DateItem tiem = new DateItem(); + tiem.Start = dates[j]; + tiem.End = dates[i - 1].AddHours(23).AddMinutes(59).AddSeconds(59); + dateTimeNew.Add(tiem); + j = i; + if (i == dates.Count - 1) + { + DateItem tim = new DateItem(); + tim.Start = dates[i]; + tim.End = dates[i].AddHours(23).AddMinutes(59).AddSeconds(59); + dateTimeNew.Add(tim); + } + } + if (dateTimeNew == null || dateTimeNew.Count == 0)//说明都连续没有断 + { + DateItem tiem = new DateItem(); + tiem.Start = dates.First(); + tiem.End = dates.Last(); + dateTimeNew.Add(tiem); + } + dateTimeNew.FirstOrDefault().Start = dateTimeNew.FirstOrDefault().Start.AddHours(startTime.Hour).AddMinutes(startTime.Minute).AddSeconds(startTime.Second); + dateTimeNew.LastOrDefault().End = dateTimeNew.LastOrDefault().End.Date.AddHours(endTime.Hour).AddMinutes(endTime.Minute).AddSeconds(endTime.Second); + List list = new List();//不同时间段的数据集合 + List list1 = new List();//不同时间段的数据集合 + foreach (var s in dateTimeNew) + { + //var client = _httpClientFactory.CreateClient(); + //client.Timeout = TimeSpan.FromMinutes(3); + //var body = JsonConvert.SerializeObject(new { StartTime = s.Start, EndTime = s.End != DateTime.MinValue ? s.End : DateTime.Now, RealIds = realDataIds }); + //var buffer = Encoding.UTF8.GetBytes(body); + //var byteContent = new ByteArrayContent(buffer); + //byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); + //if (httpResponse.StatusCode == HttpStatusCode.OK) + //{ + // dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + //} + //var resultDataStream1 = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + var resultDataStream1 = await GetRealHistory(realDataIds, timeDBApiUrl, s.Start, s.End); + var data = resultDataStream1.Data; + if (data == null || data.Count == 0) + { continue; } + var tt = s.Start.Date; + while (tt <= s.End.Date) + { + foreach (var g in changeTimes) + { + DateTime sDate = Convert.ToDateTime(g.SearchDate).Date; + DateTime aDate = Convert.ToDateTime(g.ActualityDate).Date; + if (tt != aDate)//找到要替换的数据 + { + continue; + } + foreach (var l in data) + { + if (l.Items == null || l.Items.Count == 0) + { continue; } + var cData = l.Items.Where(d => d.Time.Date == aDate).ToList(); + if (cData == null || cData.Count == 0) + { continue; } + var ccdata = cData.Select(d => new EquipParamHistoryItemModel { Value = d.Value, Time = sDate.AddHours(d.Time.Hour).AddMinutes(d.Time.Minute).AddSeconds(d.Time.Second) }).ToList(); + l.Items = l.Items.Where(d => d.Time.Date != aDate).ToList(); + l.Items = l.Items.Union(ccdata).ToList(); + } + } + tt = tt.AddDays(1); + } + list = list.Union(data).ToList(); + } + if (list != null && list.Count > 0) + { + var saData = list.Select(d => d.Id).Distinct().ToList(); + foreach (var s in saData) + { + EquipParamHistoryModel nn = new EquipParamHistoryModel(); + List ll = new List(); + nn.Id = s; + var llItem = list.Where(d => d.Id == s).ToList(); + foreach (var te in llItem) + { + ll = ll.Union(te.Items).ToList(); + } + nn.Items = ll.Distinct().ToList(); + list1.Add(nn); + } + } + resultDataStream.Data = list1; + } + } + else//原来逻辑 + { + //var client = _httpClientFactory.CreateClient(); + //client.Timeout = TimeSpan.FromMinutes(3); + //var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime =endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds }); + //var buffer = Encoding.UTF8.GetBytes(body); + //var byteContent = new ByteArrayContent(buffer); + //byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); + //if (httpResponse.StatusCode == HttpStatusCode.OK) + //{ + // dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + //} + //resultDataStream = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + resultDataStream = await GetRealHistory(realDataIds, timeDBApiUrl, startTime, endTime); + } + if (resultDataStream != null && resultDataStream.Data.Count() > 0) + { + foreach (var point in resultDataStream.Data) + { + if (point.Items == null || point.Items.Count() == 0) + { + continue; + } + var items = new List { }; + foreach (var time in times) + { + var sTime = time.AddMinutes(-1); + var pointItem = point.Items.LastOrDefault(t => t.Time > sTime && t.Time <= time);//取最近值 + + EquipParamHistoryItemModel _pointItem = new EquipParamHistoryItemModel { Time = time }; + if (pointItem != null) + { + _pointItem.Value = pointItem.Value; + } + else + { + pointItem = point.Items.FirstOrDefault(t => t.Time > time && t.Time <= time.AddMinutes(1));//取后面个值 + if (pointItem != null) + { + _pointItem.Value = pointItem.Value; + } + } + if (_pointItem != null) + { + if (_pointItem.Value != null) + { + _pointItem.Value = Math.Round(_pointItem.Value.GetValueOrDefault(), 2); + } + items.Add(_pointItem); + } + } + result.Data.Add(new EquipParamHistoryModel + { + Id = point.Id, + Items = items + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + private async Task>> GetRealHistory(List realDataIds, string timeDBApiUrl, DateTime startTime, DateTime endTime) + { + string dbRealDataResultStr = string.Empty; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromMinutes(3); + var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds }); + var buffer = Encoding.UTF8.GetBytes(body); + var byteContent = new ByteArrayContent(buffer); + byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); + } + var result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); + return result; + } + + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs new file mode 100644 index 0000000..e997c27 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.Context.AirDB; + +namespace WeiCloud.Core.Services +{ + public class EnergySaveDwCoreService : IEnergySaveDwCoreService + { + private readonly WeiCloudAirDBContext _context; + private readonly ILogger _logger; + + public EnergySaveDwCoreService(WeiCloudAirDBContext context, ILogger logger) + { + _context = context; + _logger = logger; + } + + public async Task GetProEneSaveDWNow(long? project, DateTime dateTime) + { + DateTime now = DateTimeTools.GetSysDateTimeNow(); + DateTime yearfristday = DateTimeTools.GetYearFirstDay(); + try + { + var data = await _context.TbEnergySaveDw.Where(m => m.Parm002 == project).ToListAsync(); + //parm002 :项目id parm003:存储时间 + var result = (from m in data + where m.Parm002 == project && m.Parm003 >= yearfristday && m.Parm003 <= now + group m by m.Parm004 into g + select new + { + //003累计节能 + sum = (g.Max(a => a.ProParm003) - g.Min(a => a.ProParm003)) + }).Sum(a => a.sum); + return result.ToDouble(); + + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProEneSaveDWNow ", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + return await Task.FromResult(-1); + } + + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs new file mode 100644 index 0000000..66e4f56 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; + +namespace WeiCloud.Core.Services +{ + public class EquipInfoCoreService : IEquipInfoCoreService + { + private readonly WeiCloudDBContext _context; + private readonly ILogger _logger; + public EquipInfoCoreService(WeiCloudDBContext context, ILogger logger) + { + _context = context; + _logger = logger; + } + /// + /// 查询设备信息 + /// + /// + /// + public async Task> GetEquipmentInfos(long projectId) + { + var equipmentInfos = await _context.EquipmentInfo.Where(t => t.Projectid == projectId && t.State == 1).AsNoTracking().ToListAsync(); + return equipmentInfos; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs new file mode 100644 index 0000000..558056e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs @@ -0,0 +1,207 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common.EquipPart; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.EquipPart; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core.Services.EquipPart +{ + public class EquipPartCoreService : IEquipPartCoreService + { + private readonly ILogger _logger; + private readonly WeiCloudDBContext _dbContext; + private readonly WeiCloudDBUserCenterContext _dbUserCenterContext; + public EquipPartCoreService(ILogger logger, WeiCloudDBContext dbContext, WeiCloudDBUserCenterContext dbUserCenterContext) + { + _logger = logger; + _dbContext = dbContext; + _dbUserCenterContext = dbUserCenterContext; + } + /// + /// 消息通知,更新审批状态(对工作流) + /// + /// + /// + public async Task> ApproveItem(ApproveItemModel input) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = true }; + try + { + if (input.Status != (short)EquipPartApproveState.Applied + && input.Status != (short)EquipPartApproveState.Approved + && input.Status != (short)EquipPartApproveState.Refuse + && input.Status != (short)EquipPartApproveState.Completed) + {//其他不用处理 + _logger.LogWarning(new NlogMessageHelper("ApproveItem", "").GetNlogMessage().ToString()); + return result; + } + if (input.OrderId <= 0 || input.ApproverUserId <= 0) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "OrderId必填"; + return result; + } + var equipPartApply = _dbContext.EtEquipPartApply.FirstOrDefault(t => t.Id == input.ApplyId && t.OrderId == input.OrderId); + if (equipPartApply == null) + { + result.Code = RequestBackStatuEnum.notexist.Value; + result.Msg = "申请单不存在"; + return result; + } + var approverUser = _dbUserCenterContext.Users.FirstOrDefault(t => t.Id == input.ApproverUserId); + + using var dbContextTrans = _dbContext.Database.BeginTransaction(); + try + { + var lastEtEquipPartApplyState = _dbContext.EtEquipPartApplyState.OrderByDescending(t => t.CreateTime).AsNoTracking().FirstOrDefault(t => t.EquipPartApplyId == equipPartApply.Id); + if (lastEtEquipPartApplyState != null) + { + if (lastEtEquipPartApplyState.Status == (short)EquipPartApproveState.Completed + || lastEtEquipPartApplyState.Status == (short)EquipPartApproveState.Refuse) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "申请单已经审批完成!不需要处理"; + return result; + } + } + var approverName = ""; + if (input.Status != (short)EquipPartApproveState.Applied) + { + approverName = approverUser == null ? "" : approverUser?.Userfullname; + } + _dbContext.EtEquipPartApplyState.Add(new EtEquipPartApplyState + { + Id = UidGenerator.Uid(), + EquipPartApplyId = equipPartApply.Id, + Status = input.Status, + ApproverId = input.ApproverUserId, + ApproverName = approverName, + CreateTime = DateTime.Now + }); + if (input.Status == (short)EquipPartApproveState.Completed || input.Status == (short)EquipPartApproveState.Refuse) + {//已完成或者拒绝 + var equipPartApplyDetails = await _dbContext.EtEquipPartApplyDetail.Where(t => t.EquipPartApplyId == equipPartApply.Id).ToListAsync(); + var warehouseIds = equipPartApplyDetails.Select(t => t.WarehouseId).Distinct().ToList(); + var equipPartIds = equipPartApplyDetails.Select(t => t.EquipPartId).Distinct().ToList(); + + var equipPartStocks = _dbContext.EtEquipPartStock.Where(t => warehouseIds.Contains(t.WarehouseId) && equipPartIds.Contains(t.EquipPartId) && t.IsDeleted == false).ToList(); + _logger.LogWarning(new NlogMessageHelper("ApproveItem原始", message: $"{JsonConvert.SerializeObject(equipPartStocks)}").GetNlogMessage().ToString()); + + if (equipPartApply.Type == (short)EquipPartApplyEnum.In && input.Status == (short)EquipPartApproveState.Completed) + {//入库,通过,加库存 + foreach (var equipPartApplyDetail in equipPartApplyDetails) + { + var equipPartStock = equipPartStocks.FirstOrDefault(t => t.WarehouseId == equipPartApplyDetail.WarehouseId && t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); + if (equipPartStock == null) + { + equipPartStock = new EtEquipPartStock + { + Id = UidGenerator.Uid(), + WarehouseId = equipPartApplyDetail.WarehouseId, + EquipPartId = equipPartApplyDetail.EquipPartId, + Brand = equipPartApplyDetail.Brand, + Batch = equipPartApplyDetail.Batch, + BrandModel = equipPartApplyDetail.BrandModel, + CreateTime = DateTime.Now, + Creator = equipPartApply.ApplyUserId + }; + _dbContext.EtEquipPartStock.Add(equipPartStock); + } + else + { + _dbContext.Entry(equipPartStock).State = EntityState.Modified; + _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; + } + _logger.LogWarning(new NlogMessageHelper("ApproveItem入库", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); + equipPartStock.Quantity += equipPartApplyDetail.Quantity; + equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; + equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; + } + } + else if (equipPartApply.Type == (short)EquipPartApplyEnum.Out && input.Status == (short)EquipPartApproveState.Refuse) + {//出库,拒绝,归还库存 + foreach (var equipPartApplyDetail in equipPartApplyDetails) + { + var equipPartStock = equipPartStocks.FirstOrDefault(t => t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); + if (equipPartStock == null) + { + continue; + } + else + { + _dbContext.Entry(equipPartStock).State = EntityState.Modified; + _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; + } + _logger.LogWarning(new NlogMessageHelper("ApproveItem出库", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); + equipPartStock.Quantity += equipPartApplyDetail.Quantity; + equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; + equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; + } + } + else if (equipPartApply.Type == (short)EquipPartApplyEnum.LentOut) + {//外借,拒绝或者完成,结果都是归还数量 + foreach (var equipPartApplyDetail in equipPartApplyDetails) + { + var equipPartStock = equipPartStocks.FirstOrDefault(t => t.WarehouseId == equipPartApplyDetail.WarehouseId && t.EquipPartId == equipPartApplyDetail.EquipPartId + && t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); + if (equipPartStock == null) + { + continue; + } + + _dbContext.Entry(equipPartStock).State = EntityState.Modified; + _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; + _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; + + _logger.LogWarning(new NlogMessageHelper("ApproveItem外借", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); + equipPartStock.Quantity = equipPartStock.Quantity + equipPartApplyDetail.Quantity; + _logger.LogWarning(new NlogMessageHelper("ApproveItem外借", message: $"现有有数量:{equipPartStock.Quantity}").GetNlogMessage().ToString()); + equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; + equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; + } + } + } + _dbContext.SaveChanges(); + dbContextTrans.Commit(); + } + catch (Exception ex) + { + dbContextTrans.Rollback(); + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper("ApproveItem", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper("ApproveItem", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + finally + { + _logger.LogWarning(new NlogMessageHelper("ApproveItem", message: JsonConvert.SerializeObject(input)).GetNlogMessage().ToString()); + } + return result; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs new file mode 100644 index 0000000..bba7530 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.EquipPart; + +namespace WeiCloud.Core.Services.EquipPart +{ + public interface IEquipPartCoreService + { + Task> ApproveItem(ApproveItemModel input); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs new file mode 100644 index 0000000..ce92b9a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs @@ -0,0 +1,1961 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using NewLife.Log; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Core.Calculation; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.SystemDiagnosis; +using WeiCloud.Utils; + +namespace WeiCloud.Core.EquipStatistics +{ + public class EquipStatisticsService : IEquipStatisticsService + { + private readonly ILogger _logger; + private readonly IDictionaryService _dictionaryService; + private readonly WeiCloudDBUserCenterContext _userCenterContext; + public EquipStatisticsService(ILogger logger, IDictionaryService dictionaryService, WeiCloudDBUserCenterContext userCenterContext) + { + _logger = logger; + _dictionaryService = dictionaryService; + _userCenterContext = userCenterContext; + } + /// + /// 能效计算 + /// + /// + /// 有效设备 + /// 全部设备 + /// + /// + /// + /// + /// + public async Task> GetEquipEfficiencyV04(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) + { + var result = new List { }; + try + { + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + //var time1 = timeList[i].AddMinutes(-3); + var time1 = timeList[i]; + //var time2 = timeList[i + 1]; + var time2 = time1.AddSeconds(10); + + + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + var _ammeterHistorys = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + //AmParm027 = t.Max(m => m.AmParm027) + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) + { + //ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); + ammeterConsum = _ammeterHistorys.Sum(t => t.Value); + } + + //瞬时流量 + //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new + var _gasMeterHistorys = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + //AmParm027 = t.Max(m => m.AmParm027) + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) + { + //gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); + gasMeterConsum = _gasMeterHistorys.Sum(t => t.Value); + } + + //var _heatMeterHistorys11 = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).ToList(); + //瞬时热流量 + /* + * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 + */ + //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new + var _heatMeterHistorys = heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + //AmParm027 = t.Max(m => m.AmParm027) + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) + { + //heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); + heatMeterConsum = _heatMeterHistorys.Sum(t => t.Value); + } + + double r = 0; + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + + public async Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) + { + var result = new List { }; + try + { + var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); + + ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + + var mainEquipmentTypes = equipmentTypes.Where(t => t.Typecode == EquipTypeEnum.DirectFiredUnitCode + || t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode + || t.Typecode == EquipTypeEnum.FCCCode + || t.Typecode == EquipTypeEnum.CoolingTower).ToList(); + + var mainEquipmentTypeIds = mainEquipmentTypes.Select(t => t.Id).Distinct().ToList(); + + var mainEquipmentInfos = equipmentInfos.Where(t => t.Eqtype != null && mainEquipmentTypeIds.Contains((long)t.Eqtype)).ToList(); + var mainEquipmentInfoIds = mainEquipmentInfos.Select(t => t.Id).Distinct().ToList(); + + + var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + + bool isSys = false; + if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) + && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) + { + isSys = true; + } + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + //var time1 = timeList[i].AddMinutes(-3); + var time1 = timeList[i]; + //var time2 = timeList[i + 1]; + var time2 = time1.AddSeconds(10); + + if (!isSys && equipmentRunningTimesHistorysCloseds != null && equipmentRunningTimesHistorysCloseds.Count() > 0) + { + var _equipmentRunningTimesHistorysCloseds = equipmentRunningTimesHistorysCloseds.Where(t => mainEquipmentInfoIds.Contains(t.EquipId) && ((time1 >= t.StartTime && time1 <= t.EndTime) || (time2 >= t.StartTime && time2 < t.EndTime))).ToList(); + foreach (var _equipmentRunningTimesHistorysClosed in _equipmentRunningTimesHistorysCloseds) + { + ammeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + gasMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + heatMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + waterMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + } + } + + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.AmParm027 == null || (t.AmParm027 >= 0 && t.AmParm027 <= 50))).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //AmParm027 = t.Max(m => m.AmParm027) + //AmParm027 = t.LastOrDefault()?.AmParm027 + AmParm027 = t.FirstOrDefault()?.AmParm027 + }).ToList(); + if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) + { + //ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); + ammeterConsum = _ammeterHistorys.Average(t => t.AmParm027 ?? 0); + } + + //瞬时流量 + //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new + var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.GmParm001 == null || t.GmParm001 >= 0)).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //Parm002 = t.Max(m => m.Parm002) + //GmParm001 = t.LastOrDefault()?.GmParm001 + GmParm001 = t.FirstOrDefault()?.GmParm001 + }).ToList(); + if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) + { + //gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); + gasMeterConsum = _gasMeterHistorys.Average(t => t.GmParm001 ?? 0); + } + + //var _heatMeterHistorys11 = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).ToList(); + //瞬时热流量 + /* + * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 + */ + //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new + var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //HmParm001 = t.Max(m => m.HmParm001) + //HmParm001 = t.LastOrDefault()?.HmParm001 + HmParm001 = t.FirstOrDefault()?.HmParm001 + }).ToList(); + if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) + { + //heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); + heatMeterConsum = _heatMeterHistorys.Average(t => t.HmParm001 ?? 0); + } + + double r = 0; + if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) + && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) + { + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) + { + r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) + { + r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); + } + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + public async Task> GetEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys) + { + var result = new List { }; + try + { + var timeList = new List { }; + var _startTime = startTime; + while (_startTime <= endTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + else if (intervalUnit == 4) + { + _startTime = _startTime.AddMonths((int)interval); + } + else + { + break; + } + } + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + var time1 = timeList[i]; + var time2 = timeList[i + 1]; + + + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + if (ammeterHistorys.Count() > 0) + { + ammeterConsum = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() + }).Average(t => t.Value); + //ammeterConsum = ammeterHistorys.Last().Value.GetValueOrDefault() - ammeterHistorys.First().Value.GetValueOrDefault(); + } + if (gasMeterHistorys.Count() > 0) + { + //gasMeterConsum = gasMeterHistorys.Last().Value.GetValueOrDefault() - gasMeterHistorys.First().Value.GetValueOrDefault(); + gasMeterConsum = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() + }).Average(t => t.Value); + } + + if (heatMeterHistorys.Count() > 0) + { + //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); + heatMeterConsum += heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() + }).Average(t => t.Value); + } + //if (coolMeterHistorys.Count() > 0) + //{ + // //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); + // heatMeterConsum += coolMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new + // { + // Id = t.Key, + // Value = t.Last().Value.GetValueOrDefault() + // }).Average(t => t.Value); + //} + + + double r = 0; + if (label == "系统") + { + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (label == "主机") + { + r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (label == "泵" || label == "塔") + { + r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); + } + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + public async Task> GetEnergyEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List coolMeterHistorys) + { + var result = new List { }; + try + { + var timeList = new List { }; + var _startTime = startTime; + while (_startTime <= endTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + else if (intervalUnit == 4) + { + _startTime = _startTime.AddMonths((int)interval); + } + else + { + break; + } + } + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + var time1 = timeList[i]; + var time2 = timeList[i + 1]; + + + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + if (ammeterHistorys.Count() > 0) + { + ammeterConsum = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() + }).Sum(t => t.Value); + //ammeterConsum = ammeterHistorys.Last().Value.GetValueOrDefault() - ammeterHistorys.First().Value.GetValueOrDefault(); + } + if (gasMeterHistorys.Count() > 0) + { + //gasMeterConsum = gasMeterHistorys.Last().Value.GetValueOrDefault() - gasMeterHistorys.First().Value.GetValueOrDefault(); + gasMeterConsum = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() + }).Sum(t => t.Value); + } + + if (heatMeterHistorys.Count() > 0) + { + //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); + heatMeterConsum += heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() + }).Sum(t => t.Value); + } + if (coolMeterHistorys.Count() > 0) + { + //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); + heatMeterConsum += coolMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new + { + Id = t.Key, + Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() + }).Sum(t => t.Value); + } + + + double r = 0; + if (label == "系统") + { + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (label == "主机") + { + r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (label == "泵" || label == "塔") + { + r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); + } + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + + /// + /// 根据累计值计算能效 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetEquipEfficiencyByCumulative(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) + { + var result = new List { }; + try + { + var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); + + ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + + var mainEquipmentTypes = equipmentTypes.Where(t => t.Typecode == EquipTypeEnum.DirectFiredUnitCode + || t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode + || t.Typecode == EquipTypeEnum.FCCCode + || t.Typecode == EquipTypeEnum.CoolingTower).ToList(); + + var mainEquipmentTypeIds = mainEquipmentTypes.Select(t => t.Id).Distinct().ToList(); + + var mainEquipmentInfos = equipmentInfos.Where(t => t.Eqtype != null && mainEquipmentTypeIds.Contains((long)t.Eqtype)).ToList(); + var mainEquipmentInfoIds = mainEquipmentInfos.Select(t => t.Id).Distinct().ToList(); + + + var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + var time1 = timeList[i].AddMinutes(-3); + var time2 = timeList[i + 1]; + + if (equipmentRunningTimesHistorysCloseds != null && equipmentRunningTimesHistorysCloseds.Count() > 0) + { + var _equipmentRunningTimesHistorysCloseds = equipmentRunningTimesHistorysCloseds.Where(t => mainEquipmentInfoIds.Contains(t.EquipId) && ((time1 >= t.StartTime && time1 <= t.EndTime) || (time2 >= t.StartTime && time2 <= t.EndTime))).ToList(); + foreach (var _equipmentRunningTimesHistorysClosed in _equipmentRunningTimesHistorysCloseds) + { + ammeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + gasMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + heatMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + waterMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); + } + } + + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0 && t.AmParm027 <= 50).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + MinAmParm029 = t.Min(m => m.AmParm029 ?? 0), + MaxAmParm029 = t.Max(m => m.AmParm029 ?? 0) + }).ToList(); + if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) + { + ammeterConsum = (double)_ammeterHistorys.Sum(t => t.MaxAmParm029 - t.MinAmParm029); + } + + //瞬时流量 + var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + MaxGmParm001 = t.Max(m => m.GmParm001 ?? 0), + MinGmParm001 = t.Min(m => m.GmParm001 ?? 0) + }).ToList(); + if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) + { + gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.MaxGmParm001 - t.MinGmParm001); + } + + + //瞬时热流量 + /* + * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 + */ + var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + MaxHmParm001 = t.Max(m => m.HmParm002 ?? 0), + MinHmParm001 = t.Min(m => m.HmParm002 ?? 0) + }).ToList(); + if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) + { + heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.MaxHmParm001 - t.MinHmParm001); + } + + double r = 0; + if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) + && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) + { + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) + { + r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) + { + r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); + } + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + + /// + /// 能效计算 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// 间隔单位1-分,2-时,3-日,4-月 + /// + public async Task> GetEquipEfficiency(DateTime startTime, DateTime endTime, List equipmentInfos, List equipmentInfoAlls + , List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys + , List heatMeterHistorys, double interval, int intervalUnit) + { + var result = new List { }; + try + { + var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); + + ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); + + + var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var timeList = new List { }; + var _startTime = startTime; + while (_startTime <= endTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + else if (intervalUnit == 4) + { + _startTime = _startTime.AddMonths((int)interval); + } + else + { + break; + } + } + for (var i = 0; i < timeList.Count(); i++) + { + if (i + 1 >= timeList.Count()) + { + break; + } + if (timeList[i] >= DateTime.Now) + { + break; + } + var time1 = timeList[i].AddMinutes(-3); + var time2 = timeList[i + 1]; + double ammeterConsum = 0; + double gasMeterConsum = 0; + double heatMeterConsum = 0; + + //总功率(瞬时) + /* + * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 + */ + + + //var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0 && t.AmParm027 <= 50).GroupBy(t => new + var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //AmParm027 = t.Max(m => m.AmParm027) + AmParm027 = t.LastOrDefault()?.AmParm027 + }).ToList(); + if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) + { + ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); + } + + //瞬时流量 + var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //Parm002 = t.Max(m => m.Parm002) + GmParm001 = t.LastOrDefault()?.GmParm001 + }).ToList(); + if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) + { + gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); + } + + + //瞬时热流量 + /* + * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 + */ + var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new + { + EquipId = t.Parm002 ?? 0 + }).Select(t => new + { + EquipId = t.Key.EquipId, + //HmParm001 = t.Max(m => m.HmParm001) + HmParm001 = t.LastOrDefault()?.HmParm001 + }).ToList(); + if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) + { + heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); + } + + double r = 0; + if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) + && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) + { + r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) + { + r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); + } + else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) + { + r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); + } + if (r > 5000) + {//自个决定>5000的不要了 + continue; + } + result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + + /// + /// 能效计算 + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetEquipEfficiency(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); + var equipmentGroupShipAlls = new List { }; + var equipmentGroupShips = new List { }; + var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); + var isSys = 0; + if (groupParent.Order == 0) + {//默认是系统,查询所有设备 + isSys = 1; + //var allEqGroupIds = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).AsNoTracking().Select(t => t.Id).ToListAsync(); + //equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + } + else + { + isSys = 0; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + } + equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); + var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); + + #region 正常设备 + //var equipIdsNormal = await CheckEquipsState(equipIds); + //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); + //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + #endregion + + + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var endTime = startTime.AddDays(1); + + var timeList = new List { };//时间间隔 + var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); + while (_startTime <= endTime && _startTime <= nowTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + } + if (timeList.Count() == 1) + { + timeList.Add(nowTime); + } + //电气热冷 + List energyCodes = new List { "EP", "LJ", "HE", "CO" }; + + var epIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "EP").Select(t => t.Id).ToList(); + var ljIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "LJ").Select(t => t.Id).ToList(); + var heIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && (t.ParamCode == "HE" || t.ParamCode == "CO")).Select(t => t.Id).ToList(); + + var ammeterHistorys = await _context.DsPointHistory.Where(t => epIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + + var gasMeterHistorys = await _context.DsPointHistory.Where(t => ljIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + var heatMeterHistorys = await _context.DsPointHistory.Where(t => heIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + + //var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); + //var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); + //var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); + //var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); + + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + var minDate = timeList.Min(t => t); + var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + List equipmentRunningTimesHistorysClosed = null; + if (equipmentRunningTimesHistorys.Count() > 0) + { + equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + { + EquipId = t.Parm003, + StartTime = t.Starttime, + EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + }).ToList(); + } + + + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipEfficiencyDiagnosisItemModel + { + Id = equipGroup.Id, + Name = equipGroup.Eqgroupname, + EnergyEfficiencys = new List { } + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (isSys == 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); + _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + var efficiencys = await GetEquipEfficiencyV04(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); + if (efficiencys != null && efficiencys.Count() > 0) + { + foreach (var efficiency in efficiencys) + { + var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; + + item.EnergyEfficiencys.Add(_energyEfficiencyItem); + } + } + #region 计算能耗 + var _ammeterHistoryValues = ammeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) + { + //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); + item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); + } + + var _heatMeterHistoryValues = heatMeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) + { + //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); + item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value ?? 0 }).ToList(); + } + + + var _gasMeterHistoryValues = gasMeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) + { + //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); + item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); + } + #endregion + if (item.EnergyEfficiencys != null && equipGroup.Eqgroupname.Contains("直燃机")) + { + //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 + item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); + } + items.Add(item); + } + return items; + } + + /// + /// 能效计算 + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetEquipEfficiencyV2(List groupIds, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var groupParent = await _context.EpgProDataSetGroupItem.FirstOrDefaultAsync(t => groupIds.Contains(t.Id)); + // var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); + var equipmentGroupShipAlls = new List { }; + var equipmentGroupShips = new List { }; + var equipGroups = await _context.EpgProDataSetGroupItem.Where(t => groupIds.Contains(t.ParentId)).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); + var isSys = 0; + if (groupParent.Order == 0) + {//默认是系统,查询所有设备 + isSys = 1; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EpgProDataSetGroupItemMapEquip.Where(t => equipGroupIds.Contains(t.ProDataSetGroupItemId)).AsNoTracking().ToListAsync(); + } + else + { + isSys = 0; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EpgProDataSetGroupItemMapEquip.Where(t => equipGroupIds.Contains(t.ProDataSetGroupItemId)).AsNoTracking().ToListAsync(); + } + equipIds = equipmentGroupShipAlls.Select(t => t.EquipId).Distinct().ToList(); + var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var endTime = startTime.AddDays(1); + + var timeList = new List { };//时间间隔 + var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); + while (_startTime <= endTime && _startTime <= nowTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + } + if (timeList.Count() == 1) + { + timeList.Add(nowTime); + } + //电气热冷 + List energyCodes = new List { "EP", "LJ", "HE", "CO" }; + + var epIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "EP").Select(t => t.Id).ToList(); + var ljIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "LJ").Select(t => t.Id).ToList(); + var heIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && (t.ParamCode == "HE" || t.ParamCode == "CO")).Select(t => t.Id).ToList(); + + var ammeterHistorys = await _context.DsPointHistory.Where(t => epIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + + var gasMeterHistorys = await _context.DsPointHistory.Where(t => ljIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + var heatMeterHistorys = await _context.DsPointHistory.Where(t => heIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); + + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + var minDate = timeList.Min(t => t); + var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + List equipmentRunningTimesHistorysClosed = null; + if (equipmentRunningTimesHistorys.Count() > 0) + { + equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + { + EquipId = t.Parm003, + StartTime = t.Starttime, + EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + }).ToList(); + } + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipEfficiencyDiagnosisItemModel + { + Id = equipGroup.Id, + Name = equipGroup.Name, + EnergyEfficiencys = new List { } + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (isSys == 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.ProDataSetGroupItemId == equipGroup.Id).ToList(); + _equipIds = _equipmentGroupShips.Select(t => t.EquipId).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.EquipId).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + var efficiencys = await GetEquipEfficiencyV04(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); + if (efficiencys != null && efficiencys.Count() > 0) + { + foreach (var efficiency in efficiencys) + { + var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; + + item.EnergyEfficiencys.Add(_energyEfficiencyItem); + } + } + #region 计算能耗 + var _ammeterHistoryValues = ammeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) + { + item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); + } + + var _heatMeterHistoryValues = heatMeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) + { + item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value ?? 0 }).ToList(); + } + + + var _gasMeterHistoryValues = gasMeterHistorys.GroupBy(t => t.Id).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) + }).ToList(); + if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) + { + item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); + } + #endregion + if (item.EnergyEfficiencys != null && equipGroup.Name.Contains("直燃机")) + { + //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 + item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); + } + items.Add(item); + } + return items; + } + + public async Task> GetEquipEfficiency_bak(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); + var equipmentGroupShipAlls = new List { }; + var equipmentGroupShips = new List { }; + var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); + var isSys = 0; + if (groupParent.Order == 0) + {//默认是系统,查询所有设备 + isSys = 1; + //var allEqGroupIds = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).AsNoTracking().Select(t => t.Id).ToListAsync(); + //equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + } + else + { + isSys = 0; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); + } + equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); + var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); + + #region 正常设备 + //var equipIdsNormal = await CheckEquipsState(equipIds); + //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); + //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + #endregion + + + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var endTime = startTime.AddDays(1); + + var timeList = new List { };//时间间隔 + var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); + while (_startTime <= endTime && _startTime <= nowTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + else if (intervalUnit == 3) + { + _startTime = _startTime.AddDays(interval); + } + } + if (timeList.Count() == 1) + { + timeList.Add(nowTime); + } + + + var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + + var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); + var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); + var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); + var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); + + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + var minDate = timeList.Min(t => t); + var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + List equipmentRunningTimesHistorysClosed = null; + if (equipmentRunningTimesHistorys.Count() > 0) + { + equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + { + EquipId = t.Parm003, + StartTime = t.Starttime, + EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + }).ToList(); + } + + + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipEfficiencyDiagnosisItemModel + { + Id = equipGroup.Id, + Name = equipGroup.Eqgroupname, + EnergyEfficiencys = new List { } + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (isSys == 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); + _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + var efficiencys = await GetEquipEfficiency(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, waterMeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); + if (efficiencys != null && efficiencys.Count() > 0) + { + foreach (var efficiency in efficiencys) + { + var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; + + item.EnergyEfficiencys.Add(_energyEfficiencyItem); + } + } + #region 计算能耗 + var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.AmParm029 != null && t.AmParm029 > 0).ToList(); + var _ammeterHistoryValues = _ammeterHistorys.GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) + }).ToList(); + if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) + { + //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); + item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.HmParm002 != null && t.HmParm002 > 0).ToList(); + var _heatMeterHistoryValues = _heatMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) + }).ToList(); + if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) + { + //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); + item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + var _waterMeterHistorys = waterMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.WmParm003 != null && t.WmParm003 > 0).ToList(); + var _waterMeterHistoryValues = _waterMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) + }).ToList(); + if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) + { + //item.TotalWaterValue = _waterMeterHistoryValues.Sum(t => t.Value); + item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.GmParm002 != null && t.GmParm002 > 0).ToList(); + var _gasMeterHistoryValues = _gasMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) + }).ToList(); + if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) + { + //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); + item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + #endregion + if (item.EnergyEfficiencys != null && equipGroup.Eqgroupname.Contains("直燃机")) + { + //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 + item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); + } + items.Add(item); + } + return items; + } + /// + /// 目前支持一天 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> GetEquipConsume(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var groupParent = equipmentGroups.FirstOrDefault(t => t.Id == groupId); + var equipmentGroupShipAlls = new List { }; + + var equipGroups = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).ToList(); + var isSys = 0; + if (groupParent.Order == 0) + {//默认是系统,查询所有设备 + isSys = 1; + //var allEqGroupIds = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).Select(t => t.Id).ToList(); + //equipmentGroupShipAlls = equipmentGroupShips.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).ToList(); + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); + } + else + { + isSys = 0; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); + } + equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); + var equipInfoAlls = equipmentInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + var equipTypeAlls = equipmentTypeAlls.Where(t => t.Isusing == 1).ToList(); + + #region 正常设备 + //var equipIdsNormal = await CheckEquipsState(equipIds); + //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); + //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + #endregion + + + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var startTime1 = startTime.AddHours(1); + var endTime = startTime.AddDays(1).AddHours(-1); + var endTime1 = startTime.AddDays(1); + if (date.ToString("yyyy-MM-dd") == nowTime.ToString("yyyy-MM-dd")) + { + endTime = nowTime.AddHours(-1); + endTime1 = nowTime; + } + + var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + + //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + + //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); + //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); + //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); + //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); + + //var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); + //var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); + //var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); + //var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); + + + var ammeterHistoryValues = await ammeterHistoryQuery.Where(t => t.AmParm029 != null && t.AmParm029 > 0).GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) + }).AsNoTracking().ToListAsync(); + var waterMeterHistoryValues = await waterMeterHistoryQuery.Where(t => t.WmParm003 != null && t.WmParm003 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) + }).AsNoTracking().ToListAsync(); + var gasMeterHistoryValues = await gasMeterHistoryQuery.Where(t => t.GmParm002 != null && t.GmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) + }).AsNoTracking().ToListAsync(); + var heatMeterHistoryValues = await heatMeterHistoryQuery.Where(t => t.HmParm002 != null && t.HmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + { + EquipId = t.Key, + Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) + }).AsNoTracking().ToListAsync(); + + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + //var minDate = timeList.Min(t => t); + //var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + //var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + //List equipmentRunningTimesHistorysClosed = null; + //if (equipmentRunningTimesHistorys.Count() > 0) + //{ + // equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + // { + // EquipId = t.Parm003, + // StartTime = t.Starttime, + // EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + // }).ToList(); + //} + + + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipConsumeDiagnosisItemModel + { + Id = equipGroup.Id, + Name = equipGroup.Eqgroupname + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (isSys == 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); + _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + #region 计算能耗 + //var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.AmParm029 != null && t.AmParm029 > 0).ToList(); + //var _ammeterHistoryValues = _ammeterHistorys.GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) + //}).ToList(); + var _ammeterHistoryValues = ammeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) + { + //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); + item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.HmParm002 != null && t.HmParm002 > 0).ToList(); + //var _heatMeterHistoryValues = _heatMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) + //}).ToList(); + var _heatMeterHistoryValues = heatMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) + { + //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); + item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + //var _waterMeterHistorys = waterMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.WmParm003 != null && t.WmParm003 > 0).ToList(); + //var _waterMeterHistoryValues = _waterMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) + //}).ToList(); + var _waterMeterHistoryValues = waterMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) + { + //item.TotalWaterValue = _waterMeterHistoryValues.Sum(t => t.Value); + item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.GmParm002 != null && t.GmParm002 > 0).ToList(); + //var _gasMeterHistoryValues = _gasMeterHistorys.GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) + //}).ToList(); + var _gasMeterHistoryValues = gasMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) + { + //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); + item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + } + #endregion + items.Add(item); + } + return items; + } + + public async Task> GetEquipConsume_V02(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var groupParent = equipmentGroups.FirstOrDefault(t => t.Id == groupId); + var equipmentGroupShipAlls = new List { }; + + var equipGroups = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).ToList(); + var isSys = 0; + if (groupParent.Order == 0) + {//默认是系统,查询所有设备 + isSys = 1; + //var allEqGroupIds = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).Select(t => t.Id).ToList(); + //equipmentGroupShipAlls = equipmentGroupShips.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).ToList(); + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); + } + else + { + isSys = 0; + var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); + equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); + } + equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); + var equipInfoAlls = equipmentInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + var equipTypeAlls = equipmentTypeAlls.Where(t => t.Isusing == 1).ToList(); + + #region 正常设备 + //var equipIdsNormal = await CheckEquipsState(equipIds); + //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); + //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + #endregion + + + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var startTime1 = startTime.AddHours(1); + var endTime = startTime.AddDays(1).AddHours(-1); + var endTime1 = startTime.AddDays(1); + if (date.ToString("yyyy-MM-dd") == nowTime.ToString("yyyy-MM-dd")) + { + endTime = nowTime.AddHours(-1); + endTime1 = nowTime; + } + + //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); + + //var ammeterHistoryValues = await ammeterHistoryQuery.Where(t => t.AmParm029 != null && t.AmParm029 > 0).GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) + //}).AsNoTracking().ToListAsync(); + //var waterMeterHistoryValues = await waterMeterHistoryQuery.Where(t => t.WmParm003 != null && t.WmParm003 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) + //}).AsNoTracking().ToListAsync(); + //var gasMeterHistoryValues = await gasMeterHistoryQuery.Where(t => t.GmParm002 != null && t.GmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) + //}).AsNoTracking().ToListAsync(); + //var heatMeterHistoryValues = await heatMeterHistoryQuery.Where(t => t.HmParm002 != null && t.HmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new + //{ + // EquipId = t.Key, + // Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) + //}).AsNoTracking().ToListAsync(); + + #endregion + + #region DW + var timeIds = await _airDBContext.Times.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime1).AsNoTracking().Select(t => t.Id).ToListAsync(); + var ammeterDws = await _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new + { + Parm002 = t.Parm002 ?? 0, + AmParm003 = t.AmParm003 ?? 0 + }).AsNoTracking().ToListAsync(); + var waterMeterDws = await _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new + { + Parm002 = t.Parm002 ?? 0, + WmParm002 = t.WmParm002 ?? 0 + }).AsNoTracking().ToListAsync(); + var gasMeterDws = await _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new + { + Parm002 = t.Parm002 ?? 0, + GmParm002 = t.GmParm002 ?? 0 + }).AsNoTracking().ToListAsync(); + var heatMeterDws = await _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new + { + Parm002 = t.Parm002 ?? 0, + HmParm001 = t.HmParm001 ?? 0 + }).AsNoTracking().ToListAsync(); + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + //var minDate = timeList.Min(t => t); + //var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + //var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + //List equipmentRunningTimesHistorysClosed = null; + //if (equipmentRunningTimesHistorys.Count() > 0) + //{ + // equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + // { + // EquipId = t.Parm003, + // StartTime = t.Starttime, + // EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + // }).ToList(); + //} + + + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipConsumeDiagnosisItemModel + { + Id = equipGroup.Id, + Name = equipGroup.Eqgroupname + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (isSys == 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); + _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + #region 计算能耗 + + var _ammeterDws = ammeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new + { + Parm002 = t.Key, + AmParm003 = t.Sum(s => s.AmParm003) + }).ToList(); + if (_ammeterDws != null && _ammeterDws.Count() > 0) + { + item.AmmeterEquipConsumes = _ammeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.AmParm003 }).ToList(); + } + + //var _ammeterHistoryValues = ammeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + //if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) + //{ + // item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + //} + + var _heatMeterDws = heatMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new + { + Parm002 = t.Key, + HmParm001 = t.Sum(s => s.HmParm001) + }).ToList(); + if (_heatMeterDws != null && _heatMeterDws.Count() > 0) + { + item.HeatEquipConsumes = _heatMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.HmParm001 }).ToList(); + } + + //var _heatMeterHistoryValues = heatMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + //if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) + //{ + // item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + //} + + var _waterMeterDws = waterMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new + { + Parm002 = t.Key, + WmParm002 = t.Sum(s => s.WmParm002) + }).ToList(); + if (_waterMeterDws != null && _waterMeterDws.Count() > 0) + { + item.WaterEquipConsumes = _waterMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.WmParm002 }).ToList(); + } + + //var _waterMeterHistoryValues = waterMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + //if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) + //{ + // item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + //} + + var _gasMeterDws = gasMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new + { + Parm002 = t.Key, + GmParm002 = t.Sum(s => s.GmParm002) + }).ToList(); + if (_gasMeterDws != null && _gasMeterDws.Count() > 0) + { + item.GasEquipConsumes = _gasMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.GmParm002 }).ToList(); + } + + //var _gasMeterHistoryValues = gasMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); + //if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) + //{ + // item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); + //} + #endregion + items.Add(item); + } + return items; + } + + /// + /// + /// + /// + /// + /// 1-分钟,2-小时 + /// + /// + /// + /// + public async Task> GetEquipEfficiencyAndConsum(long projectId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) + { + var items = new List { }; + + var equipIds = new List { }; + + var equipmentGroupShips = new List { }; + var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.EnergyEfficiencyConsumZone && t.Projectid == projectId).OrderBy(t => t.Order).AsNoTracking().TagWith("SubDB").ToListAsync(); + var equipGroupIds = equipGroups.Select(t => t.Id).ToList(); + + var equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().TagWith("SubDB").ToListAsync(); + + equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); + var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().TagWith("SubDB").ToListAsync(); + //var equipTypeAlls = await _context.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); + var equipTypeAlls = _dictionaryService.GetValue(typeof(EquipmentType).Name).Values.Where(t => t.Isusing == 1).ToList(); + + + + var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); + + //防止无法判断组的设备类型 + var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); + var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); + #region 历史表查询 + + var nowTime = DateTime.Now; + var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 + var endTime = startTime.AddDays(1); + + var timeList = new List { };//时间间隔 + var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); + while (_startTime <= endTime && _startTime <= nowTime) + { + timeList.Add(_startTime); + if (intervalUnit == 1) + { + _startTime = _startTime.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _startTime = _startTime.AddHours(interval); + } + } + if (timeList.Count() == 1) + { + timeList.Add(nowTime); + } + + + var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); + + var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); + var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); + var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); + var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); + + #endregion + + #region 设备历史状态 + equipmentGroupShips = equipmentGroupShipAlls; + var minDate = timeList.Min(t => t); + var maxDate = timeList.Max(t => t); + //设备历史状态,关机状态 + var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); + + List equipmentRunningTimesHistorysClosed = null; + if (equipmentRunningTimesHistorys.Count() > 0) + { + equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed + { + EquipId = t.Parm003, + StartTime = t.Starttime, + EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) + }).ToList(); + } + + + #endregion + + foreach (var equipGroup in equipGroups) + { + var item = new EquipEfficiencyAndConsumModel + { + Id = equipGroup.Id, + Name = equipGroup.Eqgroupname, + EnergyEfficiencys = new List { } + }; + var _equipInfoAlls = new List { }; + var _equipIds = new List { }; + if (equipGroups.IndexOf(equipGroup) > 0) + { + var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + else + {//系统,所有设备 + _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 + _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); + } + var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); + + var efficiencys = await GetEquipEfficiency(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, waterMeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); + if (efficiencys != null && efficiencys.Count() > 0) + { + foreach (var efficiency in efficiencys) + { + item.EnergyEfficiencys.Add(new EquipEfficiencyAndConsumItemModel { Time = efficiency.Time, Efficiency = Math.Round(efficiency.Value, 2) }); + } + } + items.Add(item); + } + return items; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs new file mode 100644 index 0000000..706aca7 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.SystemDiagnosis; + +namespace WeiCloud.Core.EquipStatistics +{ + public interface IEquipStatisticsService + { + Task> GetEnergyEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List coolMeterHistorys); + Task> GetEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys); + //Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); + + Task> GetEquipEfficiencyByCumulative(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); + Task> GetEquipEfficiency(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); + + Task> GetEquipEfficiencyV2(List groupIds, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); + Task> GetEquipEfficiencyAndConsum(long projectId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); + + Task> GetEquipConsume(long equipId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); + Task> GetEquipConsume_V02(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); + Task> GetEquipEfficiencyV04(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); + Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); + Task> GetEquipEfficiency(DateTime startTime, DateTime endTime, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, double interval, int intervalUnit); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs new file mode 100644 index 0000000..2770ec1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.LogicModels; + +namespace WeiCloud.Core.Services +{ + public interface IConstrInfoGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task> GetAllConstructionInfoRedis(); + Task GetConstModelById(long id); + Task> GetConstByKeys(string[] keys); + Task> GetConstTreeByProjectId(long projectId, int isUsing, int? level); + Task> GetConstEquipsTreeByProjectId(long projectId); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs new file mode 100644 index 0000000..70a3613 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Services +{ + public interface IEnergySaveDwCoreService + { + /// + /// 项目到目前为止的节能量 + /// + /// + /// + /// + Task GetProEneSaveDWNow(long? project, DateTime dateTime); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs new file mode 100644 index 0000000..2438453 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; + +namespace WeiCloud.Core.Services +{ + public interface IEquipInfoCoreService + { + Task> GetEquipmentInfos(long projectId); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs new file mode 100644 index 0000000..ec0f66b --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Services +{ + public interface INlogCoreService + { + Task PostNlogsParam(string actionName, int? type, string oldValue, string newValue, string message, long operatorId = 0, string operatorName = ""); + + Task> UpdateOrAndNlogs(List nlogs); + Task> UpdateOrAndNlogs(CmdNlogBoNew item); + Task> UpdateOrAndNlog(CmdNlogBoNew item); + Task> GetIPHomePlaces(List ips); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs new file mode 100644 index 0000000..9552529 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public interface IPermissionsGainCoreService + { + Task> GetAllPermissionsRedis(); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs new file mode 100644 index 0000000..8d1c3db --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Services +{ + public interface IProjectDWCoreService + { + Task GetCurrentEnergyYear(long? projectid, DateTime dateTime); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs new file mode 100644 index 0000000..4ece86d --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; + +namespace WeiCloud.Core.Services +{ + public interface IProjectInfoGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task> GetAllEquipRedis(); + Task GetEquipModel(long equipId); + Task> GetEquipListByKeys(string[] keys); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs new file mode 100644 index 0000000..fbd4032 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.InfoModels; +using WeiCloud.Entity.LogicModels.SysModule; + +namespace WeiCloud.Core.Services +{ + public interface IPublicFunctionService: WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task>> GetProjectListByRole(CurrentUser user); + Task> GetWeatherByProId(long proiectId); + Task>> Get7DaysWeatherByProId(long proiectId); + Task> GetWeatherByProIdNow(long proiectId); + Task>> GetEngeryType(); + Task>> GetAirQuantityType(); + Task>> GetTimeSpanData(); + Task> GetProjectBaseInfo(long projectid); + Task>> GetProjectMenuSysModule(string roleCode, long projectId, long parentId, long? modelType = 0); + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs new file mode 100644 index 0000000..7210223 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Services +{ + public interface IRealDataAnalyzeCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task>> GetEquCommStatusAsync(List equids); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs new file mode 100644 index 0000000..117bd83 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public interface IStandarParamsCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task GetStandarParam(int id); + Task> GetStandarParam(); + Task> GetStandarParamByAllKes(string[] keys); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs new file mode 100644 index 0000000..ab684aa --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace WeiCloud.Core.Services +{ + public interface ISteamHeatCalculateService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task CalculateSteamHeat(double steamFlow, double steamOutTemperature, double waterInTemperature); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs new file mode 100644 index 0000000..3b07d06 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.ProConfiguration.Service +{ + public interface IUserGroupsGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task PushUserGroupsToRedis(UserGroups userGroups); + Task deleteUserGroupsInfo(string[] keys); + Task GetUserGroupsModelById(long id); + Task> GetAllUserGroupsRedis(); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs new file mode 100644 index 0000000..3626e51 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public interface IUserProjectPermissionsCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task GetCurrentUserPermission(string userId); + Task> GetAllGroupPressRedis(); + Task GetCurrentUserPermission(string userRoleId, string userGroupId); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs new file mode 100644 index 0000000..72fcc4f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; + +namespace WeiCloud.Core.Services +{ + public interface IUserProjectPressRedisTreeCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task GetProIdAndConstPressTreeByUserId(long userId); + Task GetUserRolePress(); + Task GetUserRolePress(long? userId, string code); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs new file mode 100644 index 0000000..216c102 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.Users; + +namespace WeiCloud.Core.Services +{ + public interface IUsersCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task GetUsersById(long id); + Task GetUsersByName(string name); + Task GetAdmin(); + Task GetUsersByIdV02(long id); + Task> GetChildDeptUsers(List userGroups, long deptId); + Task GetUserInfoByJwt(string token); + Task> GetUserIdsByProjectId(long projectId); + Task ChangeUserPassword(long userId, string newPwd); + UserInfoJwtViewModel GetUserInfoByJwtStr(string token); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs new file mode 100644 index 0000000..2f15fbf --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public interface IUsersGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey + { + Task GetUserModelById(long id); + Task PushUserToRedis(Users users); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs new file mode 100644 index 0000000..7e4a2c5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.DataModels; + +namespace WeiCloud.Core.Services +{ + public interface IWorkflowService + { + Task SaveWorkflowAsync(WorkOrderAggregateDto dto); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs new file mode 100644 index 0000000..666b2b5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.IotDS; + +namespace WeiCloud.Core.Services.Iot +{ + public interface IIotService + { + Task>> GetIoTDeviceControl(GetIoTDeviceControlModel input); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs new file mode 100644 index 0000000..e5377e0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs @@ -0,0 +1,73 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.IotDS; + +namespace WeiCloud.Core.Services.Iot +{ + public class IotService : IIotService + { + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + public IotService(IServiceScopeFactory serviceScopeFactory, ILogger logger, WeiCloudDBContext weiCloudDBContext, WeiCloudDBUserCenterContext weiCloudDBUserCenterContext) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger ?? throw new ArgumentNullException(nameof(_logger)); + } + /// + /// 查看参数下控记录 + /// + /// + public async Task>> GetIoTDeviceControl(GetIoTDeviceControlModel input) + { + var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var currentContext = scope.ServiceProvider.GetRequiredService().GetContext(); + if (currentContext == null || string.IsNullOrEmpty(currentContext.Token)) + { + result.Code = RequestBackStatuEnum.unauthorized.Value; + return result; + } + var configuration = scope.ServiceProvider.GetRequiredService(); + var httpClientFactory = scope.ServiceProvider.GetRequiredService(); + var message = JsonConvert.SerializeObject(input); + using (HttpContent httpContent = new StringContent(message)) + { + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + var url = $"{configuration["Iot:BaseUrl"]}api/IotDeviceProperty/GetIoTDeviceControl"; + using (var httpClient = new HttpClient()) + { + httpClient.DefaultRequestHeaders.Add("Authorization", currentContext.Token); + httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8"); + HttpResponseMessage responseMessage = await httpClient.PostAsync(url, httpContent); + if (responseMessage.IsSuccessStatusCode) + { + var responseStr = await responseMessage.Content.ReadAsStringAsync(); + result = JsonConvert.DeserializeObject>>(responseStr); + } + } + } + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {0};", "GetIotDevices", ex.Message)).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs new file mode 100644 index 0000000..ef12d47 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs @@ -0,0 +1,10 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.JobTask; + +namespace WeiCloud.Core.Services.Job +{ + public interface IJobManagerCoreService + { + Task GetJob(string jobName, bool isDeleted = false); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs new file mode 100644 index 0000000..c5fbb80 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs @@ -0,0 +1,58 @@ +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.JobTask; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; + +namespace WeiCloud.Core.Services.Job +{ + public class JobManagerCoreService : IJobManagerCoreService + { + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + public JobManagerCoreService(IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + _configuration = configuration; + } + /// + /// 获取任务 + /// + /// + /// + /// + public async Task GetJob(string jobName, bool isDeleted = false) + { + JobTaskModel result = null; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var _httpClientFactory = scope.ServiceProvider.GetRequiredService(); + var apiUrl = $"{_configuration["JobTaskApiUrl"]}{"/api/Job/QueryJob"}?jobName={jobName}&isDeleted={isDeleted}"; + var client = _httpClientFactory.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(3); + var httpResponse = await client.GetAsync(apiUrl); + var responseBody = string.Empty; + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + responseBody = await httpResponse.Content.ReadAsStringAsync(); + } + result = JsonConvert.DeserializeObject(responseBody); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(System.Reflection.MethodBase.GetCurrentMethod().Name, string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs new file mode 100644 index 0000000..431663f --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; +using WeiCloud.Core.EventBus; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Services.Message +{ + public interface IMessageService + { + Task> SendMsg(ProduceMsgModel faultMsg); + Task> UserOnlineSendOffline(long userId); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs new file mode 100644 index 0000000..d5f4b33 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs @@ -0,0 +1,14 @@ +using System.Threading.Tasks; +using WeiCloud.Core.EventBus; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.MsgCenter; + +namespace WeiCloud.Core.Services.Message +{ + public interface IMsgCenterCoreService + { + Task> ResendInternalMsg(long userId); + Task> SendMsg(MsgTempateEventDto input); + Task> TenantSendMsg(InternalTenantSendMsgDto input); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs new file mode 100644 index 0000000..4f06427 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs @@ -0,0 +1,459 @@ +using DotNetCore.CAP; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Msg.Core.UniPush; +using Newtonsoft.Json; +using StackExchange.Redis; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Core.AliYunSms; +using WeiCloud.Core.EventBus; +using WeiCloud.Core.MsgSocket; +using WeiCloud.Core.Services.Tenement; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core.Services.Message +{ + public class MessageService : IMessageService + { + private readonly ILogger _logger; + private readonly UniPushInstance _uniPushInstance; + private readonly WeiCloudDBUserCenterContext _userDBContext; + private readonly ISmsHelperService _smsHelperService; + private readonly ICapPublisher _capPublisher; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly IConfiguration _configuration; + public MessageService(ICapPublisher capPublisher, UniPushInstance uniPushInstance, WeiCloudDBUserCenterContext userDBContext, ILogger logger, ISmsHelperService smsHelperService, IServiceScopeFactory serviceScopeFactory,IConfiguration configuration) + { + _uniPushInstance = uniPushInstance; + _userDBContext = userDBContext; + _logger = logger; + _smsHelperService = smsHelperService; + _capPublisher = capPublisher; + _serviceScopeFactory = serviceScopeFactory; + _configuration = configuration; + } + /// + /// 发送消息 + /// + /// + /// + public async Task> SendMsg(ProduceMsgModel faultMsg) + { + var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = true }; + try + { + if (faultMsg == null) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Data = false; + return result; + } + if (faultMsg.UserIds == null || faultMsg.UserIds.Count() == 0) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Data = false; + return result; + } + if (faultMsg.SendTypes == null || faultMsg.SendTypes.Count() == 0) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Data = false; + return result; + } + var users = await _userDBContext.Users.Where(t => faultMsg.UserIds.Contains(t.Id)).Select(t => new + { + t.Id, + t.Userfullname, + t.Phone + }).AsNoTracking().ToListAsync(); + + long sendMsgId = UidGenerator.Uid(); + var payLoad = JsonConvert.SerializeObject(new + { + projectId = faultMsg.ProjectId, + id = faultMsg.Id, + type = 1, + MsgType = faultMsg.MsgType, + MainId = faultMsg.MainId, + msg = sendMsgId + }); + _userDBContext.SendMsgs.Add(new SendMsgs + { + Id = sendMsgId, + Title = faultMsg.Title, + Content = faultMsg.Content, + Payload = payLoad, + ProduceContent = JsonConvert.SerializeObject(faultMsg), + CreateTime = DateTime.Now + }); + List? userMapClients = null; + if (faultMsg.SendTypes.Contains((int)SendTypeMeta.AppMsg)) + { + userMapClients = await _userDBContext.UserMapClient.Where(t => faultMsg.UserIds.Contains(t.UserId)).Select(t => new UserMapClient + { + UserId = t.UserId, + ClientId = t.ClientId, + ServerId = t.ServerId, + ClientType = t.ClientType + }).ToListAsync(); + } + + foreach (var userId in faultMsg.UserIds) + { + try + { + if (faultMsg.SendTypes.Contains((int)SendTypeMeta.AppMsg))//app端 + { + UniPushResModel pushResult = null; + var _userMapClients = userMapClients.Where(t => t.UserId == userId && !string.IsNullOrEmpty(t.ClientId) && t.ClientType == (short)SendTypeMeta.AppMsg).ToList(); + var userMapClient = _userMapClients.FirstOrDefault(t => !string.IsNullOrEmpty(t.ServerId)); + if (userMapClient != null && !string.IsNullOrEmpty(userMapClient.ServerId) && !string.IsNullOrEmpty(userMapClient.ClientId)) + { + var instance = _uniPushInstance.Instance(userMapClient.ServerId); + if (instance != null) + { + pushResult = await instance.Push(new MsgPushEntity + { + ClientIds = _userMapClients.Select(t => t.ClientId).ToList(), + Body = faultMsg.Content, + Title = faultMsg.Title, + PlayLoad = payLoad, + ClickType = 5, + }); + } + } + _userDBContext.SendUserMsg.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = userId, + MsgId = sendMsgId, + IsSend = (pushResult != null && pushResult.Code == 200), + SendType = (short)SendTypeMeta.AppMsg, + IsRead = 0, + MsgType = faultMsg.MsgType, + EmergencyType = faultMsg.EmergencyType, + MainId = faultMsg.MainId, + ProjectId = faultMsg.ProjectId, + CreateTime = DateTime.Now + }); + } + if (faultMsg.SendTypes.Contains((int)SendTypeMeta.PcMsg)) //PC端 + { + //后续再写 + /*var pcClienIds = userMapClientInfos.Where(ui => ui.ClientType == (short)SendTypeMeta.PcMsg).Select(ui => ui.ClientId).Distinct().ToList(); + foreach (var pcClienId in pcClienIds) + { + try + { + *//* await _msgHub.Clients.Client(pcClienId).SendAsync("ReceiveFaultMsg", new MsgPushModel + { + MsgId = sendMsgId, + Title = faultMsg.Title, + Body = !string.IsNullOrEmpty(faultMsg.Content) && faultMsg.Content.Length > 20 ? faultMsg.Content.Substring(0, 20) : faultMsg.Content, + ClientId = pcClienId, + Type = 1, + PlayLoad = faultMsg.Extend + });*//* + } + catch (Exception ex) + { + _logger.LogError(ex, "ActionName:" + this.GetType().FullName); + Console.WriteLine(ex.Message); + } + }*/ + + bool isSend = false; + using (var scope = _serviceScopeFactory.CreateScope()) + { + var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); + var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); + var keys = await msgWebSocketClientInstance.GetClientIds(userId, faultMsg.SubscribeAction, faultMsg.SubscribeFilter); + //Console.WriteLine($"发送:{userId}" + JsonConvert.SerializeObject(keys)); + + if (keys != null && keys.Any()) + { + _logger.LogWarning($"{userId}发送消息,客户端Keys:{JsonConvert.SerializeObject(keys)} {faultMsg.Content}"); + foreach (var key in keys) + { + await myWebSocketHandler.SendMessageAsync(key, faultMsg.Content); + } + isSend = true; + } + } + _userDBContext.SendUserMsg.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = userId, + MsgId = sendMsgId, + IsSend = isSend, + SendType = (short)SendTypeMeta.PcMsg, + IsRead = 0, + MsgType = faultMsg.MsgType, + EmergencyType = faultMsg.EmergencyType, + MainId = faultMsg.MainId, + CreateTime = DateTime.Now, + ProjectId = faultMsg.ProjectId + }); + } + if (faultMsg.SendTypes.Contains((int)SendTypeMeta.SMSMsg)) + { + + var title = faultMsg.Title; + if (faultMsg.Title.Length > 20) + { + title = faultMsg.Title.Substring(0, 20); + } + if (!string.IsNullOrEmpty(title)) + { + title = title.Replace(".", "_");//替换特殊字符 + } + + var content = faultMsg.Content; + if (content.Length > 20) + { + content = content.Substring(0, 20); + } + if (!string.IsNullOrEmpty(content)) + { + content = content.Replace(".", "_");//替换特殊字符 + } + var equname = faultMsg.ProjectShortName + "_" + faultMsg.EquName; + + if (equname.Length > 20) + { + equname = equname.Substring(0, 20); + } + if (!string.IsNullOrEmpty(equname)) + { + equname = equname.Replace(".", "_");//替换特殊字符 + } + + //短信发送 + var user = users.Where(x => x.Id == userId).FirstOrDefault(); + if (user != null) + { + if (!string.IsNullOrEmpty(user.Phone)) + { + bool isSend = false; + //发送短信 + string msg = ""; + switch (faultMsg.MsgType) + { + case 0: + msg = "{\"Code\":\"" + content + "\"}"; + break; + case 1://工单 您有新的工单待处理,状态:${status},工单摘要:${remark},请及时处理。 + + msg = "{\"status\":\"" + title + "\",\"remark\":\"" + content + "\"}"; + break; + case 2://知识库 + msg = "{\"Code\":\"" + content + "\"}"; + break; + case 3://报警 您有新的报警,设备名称:${eqname},报警摘要:${remark},请及时处理。 + /* var equname = await _dbContext.QueryFirstAsync("SELECT `eqname` FROM `EquipmentInfo` WHERE `id` =" + faultMsg.EquId); + var projectShortName = await _dbContext.QueryFirstAsync("SELECT `shortname` FROM `ProjectInfo` WHERE `id` =" + faultMsg.ProjectId); + equname = projectShortName + "_" + projectShortName;*/ + + + if (string.IsNullOrEmpty(equname)) + { + equname = "暂无"; + } + //var contet1 = faultMsg.Content; + //if (faultMsg.Content.Length > 20) + //{ + // contet1 = faultMsg.Content.Substring(0, 20); + //} + + msg = "{\"eqname\":\"" + equname + "\",\"remark\":\"" + content + "\"}"; + break; + case 4: //计划管理 + //msg = "{\"Code\":\"" + faultMsg.Content + "\"}"; + break; + case 5: //智能诊断 + //var equname1 = faultMsg.ProjectShortName; + + //if (equname1.Length > 20) + //{ + // equname1 = equname1.Substring(0, 20); + //} + //var contet2 = faultMsg.Content; + //if (faultMsg.Content.Length > 20) + //{ + // contet2 = faultMsg.Content.Substring(0, 20); + //} + + msg = "{\"eqname\":\"" + equname + "\",\"remark\":\"" + content + "\"}"; + break; + default: + break; + } + _logger.LogWarning($"短信下发 {msg}"); + if (!string.IsNullOrEmpty(msg)) + { + //SmsResposeModel smsResposeModel = _smsHelperService.SendSms(user.Phone, msg, faultMsg.MsgType); + + //if (smsResposeModel.Code == "OK") + //{ + // isSend = true; + //} + //else if (smsResposeModel.Code == "MonthLimitControl" || smsResposeModel.Code == "DayLimitControl") + //{ + + // _logger.LogError($"短信下发失败 {smsResposeModel.Message} {smsResposeModel.Code}"); + //} + //else + //{ + // _logger.LogError($"短信下发失败 {smsResposeModel.Message} {smsResposeModel.Code}"); + //} + //if (faultMsg.MsgType == 3) + //{ + // //下发电话通知 + // //尊敬的客户,项目{pname},设备{eqname}产生{warning}报警 + // // var callmsg = "{\"pname\":\"" + faultMsg.ProjectShortName + "\",\"eqname\":\"" + faultMsg.EquName + "\",\"warning\":\"" + faultMsg.Content + "\"}"; + // // _callHelperService.SendFaultCall(user.Phone, callmsg); + //} + await SendFaultMsg(user.Phone, equname, content); + } + _userDBContext.SendUserMsg.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = userId, + MsgId = sendMsgId, + IsSend = isSend, + SendType = (short)SendTypeMeta.SMSMsg, + IsRead = 0, + MsgType = faultMsg.MsgType, + EmergencyType = faultMsg.EmergencyType, + MainId = faultMsg.MainId, + CreateTime = DateTime.Now, + ProjectId = faultMsg.ProjectId + }); + } + } + } + } + catch (Exception ex) + { + _logger.LogError($"{this.GetType().FullName}-->>{userId}SendMsg抛出异常:{ex.Message} {ex.Source} {ex.StackTrace}"); + } + } + await _userDBContext.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"SendMsg抛出异常:{ex.Message} {ex.Source} {ex.StackTrace} {ex.InnerException}").GetNlogMessage().ToString()); + } + return result; + } + private async Task SendFaultMsg(string phone, string equip, string content) + { + try + { + var accessKey = _configuration["EmpTenantEMS:PrepaidAccessKey"]; + var accessSecret = _configuration["EmpTenantEMS:PrepaidAccessSecret"]; + var url = _configuration["EmpTenantEMS:Url"]; + var msgTemplateId = _configuration["EmpTenantEMS:MsgTemplateId"]; + using var scope = _serviceScopeFactory.CreateScope(); + var tenantEMSService = scope.ServiceProvider.GetRequiredService(); + await tenantEMSService.SendHttpRequest(new Entity.LogicModels.Tenant.TenantSendMsgDto + { + MsgTemplateId = msgTemplateId, + PhoneNums = new List { phone }, + Fields = new Dictionary + { + { "eqname", equip }, + { "remark", content } + } + }, accessKey, accessSecret, url); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("SendFaultMsg", ex).GetNlogMessage()); + } + } + /// + /// 用户上线发送离线消息 + /// + /// + /// + public async Task> UserOnlineSendOffline(long userId) + { + var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = true }; + try + { + var invalidTime = DateTime.Now.AddDays(-5); + var sendUserMsgs = await _userDBContext.SendUserMsg.Where(t => t.UserId == userId && t.SendType == (short)SendTypeMeta.AppMsg && t.IsSend == false && t.CreateTime >= invalidTime).OrderBy(t => t.CreateTime).ToListAsync(); + if (sendUserMsgs.Count() == 0) + { + return result; + } + var msgIds = sendUserMsgs.Select(t => t.MsgId).ToList(); + var sendMsgs = await _userDBContext.SendMsgs.Where(t => msgIds.Contains(t.Id)).Select(t => new + { + t.Id, + t.Title, + t.Content, + t.Payload + }).ToListAsync(); + if (sendMsgs.Count() == 0) + { + return result; + } + var userMapClients = await _userDBContext.UserMapClient.Where(t => t.UserId == userId).Select(t => new + { + t.UserId, + t.ClientId, + t.ServerId, + t.ClientType + }).ToListAsync(); + var userIds = new List { userId }; + foreach (var sendMsg in sendMsgs) + { + var clientIds = userMapClients.Where(t => t.UserId == userId && !string.IsNullOrEmpty(t.ClientId) && t.ClientType == (short)SendTypeMeta.AppMsg).Select(t => t.ClientId).ToList(); + + if (clientIds.Count() > 0) + { + var instance = _uniPushInstance.Instance(userMapClients.FirstOrDefault().ServerId); + if (instance != null) + { + var pushResult = await instance.Push(new MsgPushEntity + { + ClientIds = clientIds, + Body = sendMsg.Content, + Title = sendMsg.Title, + PlayLoad = sendMsg.Payload, + ClickType = 5 + }); + if (pushResult != null && pushResult.Code == 200) + { + var sendUserMsg = sendUserMsgs.FirstOrDefault(t => t.MsgId == sendMsg.Id); + if (sendUserMsg != null) + { + _userDBContext.Entry(sendUserMsg).State = EntityState.Modified; + _userDBContext.Entry(sendUserMsg).Property(o => o.IsSend).IsModified = false; + _userDBContext.Entry(sendUserMsg).Property(o => o.UpdateTime).IsModified = false; + sendUserMsg.IsSend = true; + sendUserMsg.UpdateTime = DateTime.Now; + } + } + } + } + } + await _userDBContext.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs new file mode 100644 index 0000000..6b5d97a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs @@ -0,0 +1,476 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Core.AliYunSms; +using WeiCloud.Core.Common; +using WeiCloud.Core.EnumTools; +using WeiCloud.Core.EventBus; +using WeiCloud.Core.Filters; +using WeiCloud.Core.MsgSocket; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.MsgCenter; +using WeiCloud.Entity.LogicModels.Tenant; +using WeiCloud.Utils.Common; + +namespace WeiCloud.Core.Services.Message +{ + public class MsgCenterCoreService : IMsgCenterCoreService + { + private readonly ILogger _logger; + private readonly WeiCloudDBUserCenterContext _userCenterContext; + private readonly IServiceScopeFactory _serviceScopeFactory; + + private readonly ITenantAccessContextProvider _contextProvider; + public MsgCenterCoreService(ILogger logger, WeiCloudDBUserCenterContext userCenterContext, IServiceScopeFactory serviceScopeFactory, ITenantAccessContextProvider contextProvider) + { + _logger = logger; + _userCenterContext = userCenterContext; + _serviceScopeFactory = serviceScopeFactory; + _contextProvider = contextProvider; + } + /// + /// 发送消息 + /// + /// + /// + public async Task> SendMsg(MsgTempateEventDto input) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + if (input.UserIds == null || !input.UserIds.Any()) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, "用户ID不能为空").GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "用户ID不能为空"; + return result; + } + + + var users = await _userCenterContext.Users.Where(t => input.UserIds.Contains(t.Id)).Select(t => new + { + t.Phone, + t.Id + }).Distinct().ToListAsync(); + + var msgTemplate = _userCenterContext.MsgTemplate.Where(t => t.Id == input.MsgTempateId).AsNoTracking().Select(t => new + { + t.Id, + t.Name, + t.MsgClassId, + t.TemplateType, + t.TemplateContent, + t.IsEnableVoice, + t.VoiceContent, + t.MsgProviderId, + t.Code + }).FirstOrDefault(); + if (msgTemplate == null) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{input.MsgTempateId}消息模板不存在").GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "消息模板不存在"; + return result; + } + + var msgTemplateContent = await GetMsgContentByField(msgTemplate.TemplateContent, input.Fields, msgTemplate.TemplateType, msgTemplate.MsgClassId); + + var sendMsg = new SendMsgs + { + Id = UidGenerator.Uid(), + Title = input.Title, + Content = msgTemplateContent, + Payload = JsonConvert.SerializeObject(input), + CreateTime = DateTime.Now, + MsgTemplateId = msgTemplate.Id + }; + var sendUserMsgs = new List { }; + + + if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.SMS) + { + var phoneNums = users.Where(t => !string.IsNullOrWhiteSpace(t.Phone)).Select(t => t.Phone).Distinct().ToList(); + var msgProvider = _userCenterContext.MsgProvider.Where(t => t.Id == msgTemplate.MsgProviderId && t.ServiceApply == (short)MsgServiceApplyEnum.SMS).AsNoTracking().FirstOrDefault(); + if (msgProvider == null) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "短信服务商不存在"; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{msgTemplate.MsgProviderId}短信服务商不存在").GetNlogMessage().ToString()); + return result; + } + var msgProviderConfig = JsonConvert.DeserializeObject(msgProvider.Extend); + await SendEMS(phoneNums, msgTemplateContent, msgTemplate.MsgClassId, msgProviderConfig); + foreach (var user in users) + { + sendUserMsgs.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = user.Id, + MsgId = sendMsg.Id, + IsSend = true, + SendType = (short)SendTypeMeta.SMSMsg, + IsRead = 0, + CreateTime = DateTime.Now + }); + } + } + else if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.Internal) + { + var pushMethod = $"{msgTemplate.Code}_method"; + var userIds = users.Select(t => t.Id).ToList(); + var resultSendInternalMsg = await SendInternalMsg(sendMsg.Id, userIds, pushMethod, msgTemplateContent, input.Extend, input.Title); + if (resultSendInternalMsg.Code == RequestBackStatuEnum.success.Value && resultSendInternalMsg.Data != null && resultSendInternalMsg.Data.Any()) + { + sendUserMsgs.AddRange(resultSendInternalMsg.Data); + } + } + _userCenterContext.SendMsgs.Add(sendMsg); + _userCenterContext.SendUserMsg.AddRange(sendUserMsgs); + await _userCenterContext.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"SendMsg:{JsonConvert.SerializeObject(input)}").GetNlogMessage().ToString()); + } + return result; + } + /// + /// 发送消息 + /// + /// + /// + public async Task> TenantSendMsg(InternalTenantSendMsgDto input) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + var msgTemplate = _userCenterContext.MsgTemplate.Where(t => t.Id == input.MsgTemplateId).AsNoTracking().Select(t => new + { + t.Id, + t.Name, + t.MsgClassId, + t.TemplateType, + t.TemplateContent, + t.IsEnableVoice, + t.VoiceContent, + t.MsgProviderId, + t.Code + }).FirstOrDefault(); + if (msgTemplate == null) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{input.MsgTemplateId}消息模板不存在").GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "消息模板不存在"; + return result; + } + + var msgTemplateContent = await GetMsgContentByField(msgTemplate.TemplateContent, input.Fields, msgTemplate.TemplateType, msgTemplate.MsgClassId); + var tenantAccess = _contextProvider.Current; + var sendMsg = new SendMsgs + { + Id = UidGenerator.Uid(), + Title = input.Title, + Content = msgTemplateContent, + Payload = JsonConvert.SerializeObject(input), + CreateTime = DateTime.Now, + MsgTemplateId = msgTemplate.Id + }; + if (string.IsNullOrEmpty(sendMsg.Title)) + {//如果标题为空,则使用模板名称作为标题 + sendMsg.Title = msgTemplate.Name; + } + if (tenantAccess != null) + { + sendMsg.TenantId = tenantAccess.Id; + } + var sendUserMsgs = new List { }; + + if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.SMS) + { + if (input.PhoneNums == null || !input.PhoneNums.Any()) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "手机号码不能为空"; + return result; + } + var msgProvider = _userCenterContext.MsgProvider.Where(t => t.Id == msgTemplate.MsgProviderId && t.ServiceApply == (short)MsgServiceApplyEnum.SMS).AsNoTracking().FirstOrDefault(); + if (msgProvider == null) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "短信服务商不存在"; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{msgTemplate.MsgProviderId}短信服务商不存在").GetNlogMessage().ToString()); + return result; + } + var msgProviderConfig = JsonConvert.DeserializeObject(msgProvider.Extend); + await SendEMS(input.PhoneNums, msgTemplateContent, msgTemplate.MsgClassId, msgProviderConfig); + foreach (var phone in input.PhoneNums) + { + sendUserMsgs.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = 0, + Phone = phone, + MsgId = sendMsg.Id, + IsSend = true, + SendType = (short)SendTypeMeta.SMSMsg, + IsRead = 0, + CreateTime = DateTime.Now + }); + } + } + _userCenterContext.SendMsgs.Add(sendMsg); + _userCenterContext.SendUserMsg.AddRange(sendUserMsgs); + await _userCenterContext.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"SendMsg:{JsonConvert.SerializeObject(input)}").GetNlogMessage().ToString()); + } + return result; + } + private async Task GetMsgContentByField(string orgMsgTemplateContent, JToken fields, short templateType, string msgClassId) + { + var msgTemplateContent = orgMsgTemplateContent; + if (fields != null && !string.IsNullOrWhiteSpace(msgTemplateContent)) + { + var msgPropertys = await _userCenterContext.MsgProperty.Where(t => t.MsgClassId == msgClassId).AsNoTracking().Select(t => new + { + t.Name, + t.Field + }).ToListAsync(); + foreach (var msgProperty in msgPropertys) + { + if (msgTemplateContent.Contains($"${{{msgProperty.Name}}}")) + { + if (fields[msgProperty.Field] != null) + { + var value = fields[msgProperty.Field]; + if (templateType == (short)MsgServiceApplyEnum.SMS) + { + if (value.ToString().Length > 20) + { + value = value.ToString().Substring(0, 20); + } + msgTemplateContent = msgTemplateContent.Replace($"${{{msgProperty.Name}}}", value.ToString()); + } + else + { + msgTemplateContent = msgTemplateContent.Replace($"${{{msgProperty.Name}}}", value.ToString()); + } + } + } + } + } + return msgTemplateContent; + } + private string GetInternalMsgContent(string title, string msgContent, string extend) + { + return $"{{\"title\":\"{title}\",\"content\":\"{msgContent}\",\"extend\":{extend}}}"; + } + /// + /// 发送消息-短信 + /// + /// + /// + /// + /// + /// + private async Task> SendEMS(List phoneNums, string msgContent, string msgClassId, MsgSMSDto msgProviderConfig) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var smsHelperService = scope.ServiceProvider.GetRequiredService(); + + var sign = msgProviderConfig.Signs.FirstOrDefault(); + foreach (var phoneNumber in phoneNums) + { + SmsResposeModel? smsResposeModel = null; + try + { + smsResposeModel = smsHelperService.SendSms(phoneNumber, sign.SignName, sign.TemplateCode, msgContent, msgProviderConfig.ApiKey, msgProviderConfig.SecretKey, msgProviderConfig.Url); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.InnerException, ex.StackTrace)).GetNlogMessage().ToString()); + } + finally + { + var smsRespose = string.Empty; + if (smsResposeModel != null) + { + smsRespose = JsonConvert.SerializeObject(smsResposeModel); + } + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{phoneNumber}发送短信{smsRespose}").GetNlogMessage().ToString()); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{phoneNums.Join(",")}发送成功{msgContent}").GetNlogMessage().ToString()); + } + return result; + } + private async Task>> SendInternalMsg(long sendMsgId, List userIds, string pushMethod, string msgContent, object extend, string title) + { + var sendUserMsgs = new List { }; + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = sendUserMsgs }; + try + { + //var sendContent = $"{{\"title\":\"{title}\",\"content\":\"{msgContent}\",\"extend\":{JsonConvert.SerializeObject(extend)}}}"; + var sendContent = GetInternalMsgContent(title, msgContent, JsonConvert.SerializeObject(extend)); + using var scope = _serviceScopeFactory.CreateScope(); + var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); + var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); + foreach (var userId in userIds) + { + var isSend = false; + var keys = await msgWebSocketClientInstance.GetClientIds(userId, pushMethod, string.Empty); + Console.WriteLine($"发送:{userId}" + JsonConvert.SerializeObject(keys)); + if (keys != null && keys.Any()) + { + foreach (var key in keys) + { + await myWebSocketHandler.SendMessageAsync(key, sendContent); + } + isSend = true; + } + + sendUserMsgs.Add(new SendUserMsg + { + Id = UidGenerator.Uid(), + UserId = userId, + MsgId = sendMsgId, + IsSend = isSend, + SendType = (short)SendTypeMeta.PcMsg, + IsRead = 0, + CreateTime = DateTime.Now + }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + } + finally + { + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{userIds.Join(",")}发送成功{msgContent}").GetNlogMessage().ToString()); + } + return result; + } + /// + /// 重发消息 + /// + /// + /// + public async Task> ResendInternalMsg(long userId) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + var payloads = await (from sum in _userCenterContext.SendUserMsg + join sm in _userCenterContext.SendMsgs on sum.MsgId equals sm.Id + join mt in _userCenterContext.MsgTemplate on sm.MsgTemplateId equals mt.Id + where sum.UserId == userId && sum.IsSend == false && mt.TemplateType == (short)MsgTemplateTypeEnum.Internal + && sum.CreateTime >= DateTime.Now.AddDays(-3) && sum.Retries <= 10 + orderby sum.CreateTime ascending + select new + { + sm.Payload, + MsgTemplateId = mt.Id, + SendUserMsgId = sum.Id, + mt.TemplateContent, + mt.TemplateType, + mt.MsgClassId, + mt.Code + }).ToListAsync(); + if (!payloads.Any()) + { + return result; + } + + using var scope = _serviceScopeFactory.CreateScope(); + var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); + var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); + + var sendUserMsgIds = payloads.Select(t => t.SendUserMsgId).ToList(); + var sendUserMsgs = await _userCenterContext.SendUserMsg.Where(t => sendUserMsgIds.Contains(t.Id)).ToListAsync(); + + foreach (var payload in payloads) + { + try + { + MsgTempateEventDto msg = JsonConvert.DeserializeObject(payload.Payload); + var msgContent = await GetMsgContentByField(payload.TemplateContent, msg.Fields, payload.TemplateType, payload.MsgClassId); + var extend = string.Empty; + if (msg.Extend != null) + { + extend = JsonConvert.SerializeObject(msg.Extend); + } + var sendContent = GetInternalMsgContent(msg.Title, msgContent, extend); + var pushMethod = $"{payload.Code}_method"; + var isSend = false; + var keys = await msgWebSocketClientInstance.GetClientIds(userId, pushMethod, string.Empty); + + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{userId}重新发送站内消息{JsonConvert.SerializeObject(keys)}").GetNlogMessage().ToString()); + if (keys != null && keys.Any()) + { + foreach (var key in keys) + { + await myWebSocketHandler.SendMessageAsync(key, sendContent); + } + isSend = true; + } + var sendUserMsg = sendUserMsgs.FirstOrDefault(t => t.Id == payload.SendUserMsgId); + _userCenterContext.SendUserMsg.Attach(sendUserMsg); + _userCenterContext.Entry(sendUserMsg).Property(u => u.UpdateTime).IsModified = true; + _userCenterContext.Entry(sendUserMsg).Property(u => u.Retries).IsModified = true; + if (isSend) + { + _userCenterContext.Entry(sendUserMsg).Property(u => u.IsSend).IsModified = true; + sendUserMsg.IsSend = isSend; + } + sendUserMsg.UpdateTime = DateTime.Now; + sendUserMsg.Retries += 1; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + await _userCenterContext.SaveChangesAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + result.Code = RequestBackStatuEnum.fail.Value; + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs new file mode 100644 index 0000000..d72ef6a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs @@ -0,0 +1,41 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Msg.Core.Model; +using Msg.Core.UniPush; +using System; +using System.Collections.Concurrent; +using System.Linq; + +namespace WeiCloud.Core.Services.Message +{ + public class UniPushInstance + { + private readonly ConcurrentDictionary instances = new ConcurrentDictionary(); + + private readonly UniPushGeTui _uniPushGeTui; + private readonly ILogger _logger; + public UniPushInstance(UniPushGeTui uniPushGeTui, ILogger logger) + { + _uniPushGeTui = uniPushGeTui; + _logger = logger; + } + public UniPushUtilV02 Instance(string appName) + { + var instance = instances.GetOrAdd(appName, key => + { + try + { + var pushConfig = _uniPushGeTui.Configs.FirstOrDefault(t => t.AppName == appName); + var instance = new UniPushUtilV02(_uniPushGeTui.Url, pushConfig.AppId, pushConfig.AppKey, pushConfig.MasterSecret, pushConfig.TTL); + return instance; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return null; + }); + return instance; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs new file mode 100644 index 0000000..3440279 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.SysModule; + +namespace WeiCloud.Core.Services +{ + public interface IModuleManagerCoreService + { + Task> GetProjectSysModule(List projectIds); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs new file mode 100644 index 0000000..5b7ad5b --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public interface IModuleMenuCoreService + { + Task> GetProjectMenusLevel1(List projectIds, List sysModuleIds); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs new file mode 100644 index 0000000..134af7a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs @@ -0,0 +1,52 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.SysModule; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public class ModuleManagerCoreService : IModuleManagerCoreService + { + private readonly WeiCloudDBUserCenterContext _context; + private readonly IDictionaryService _dictionaryService; + private readonly ILogger _logger; + + public ModuleManagerCoreService(WeiCloudDBUserCenterContext context, ILogger logger, IDictionaryService dictionaryService) + { + _context = context; + _logger = logger; + _dictionaryService = dictionaryService; + } + /// + /// 项目获取所有模块 + /// + /// + /// + public async Task> GetProjectSysModule(List projectIds) + { + var query = from sm in _context.SysModule + join psm in _context.ProjectSysModule on sm.Id equals psm.Sysmoduleid + into tmp + from smpsm in tmp.DefaultIfEmpty() + where sm.Sysid == 0 || (sm.Sysid == 2 && smpsm.Isenable == true && projectIds.Contains(smpsm.Projectid)) + select new ProjectSysModuleModel + { + SysModuleId = sm.Id, + SysModuleName = sm.Name, + ProjectId = smpsm == null ? 0 : smpsm.Projectid, + PackageName = sm.Packagename, + ActiveRule = sm.Activerule, + SysId = sm.Sysid, + Order = smpsm == null ? (short)0 : smpsm.Order, + SysModelType = sm.Sysmodeltype + }; + var items = await query.OrderBy(t => t.Order).ToListAsync(); + return items; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs new file mode 100644 index 0000000..4eaf781 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs @@ -0,0 +1,44 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel.Design; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public class ModuleMenuCoreService: IModuleMenuCoreService + { + private readonly WeiCloudDBUserCenterContext _context; + private readonly ILogger _logger; + + public ModuleMenuCoreService(WeiCloudDBUserCenterContext context, ILogger logger) + { + _context = context; + _logger = logger; + } + /// + /// 一级菜单 + /// + /// + /// + /// + public async Task> GetProjectMenusLevel1(List projectIds, List sysModuleIds) + { + var projectMenusQuery = _context.ProjectMenu.Where(t => t.Isusing == 1 && t.Parentid == 0); //_context.ProjectMenu.Where(t => t.Isusing == 1 && t.Projectid == projectId && sysModuleIds.Contains(t.Sysmoduleid) && t.Parentid == 0); + if (projectIds != null && projectIds.Count() > 0) + { + projectMenusQuery = projectMenusQuery.Where(t => projectIds.Contains(t.Projectid)); + } + if (sysModuleIds != null && sysModuleIds.Count() > 0) + { + projectMenusQuery = projectMenusQuery.Where(t => sysModuleIds.Contains(t.Sysmoduleid)); + } + return await projectMenusQuery.ToListAsync(); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs new file mode 100644 index 0000000..3936b5c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.Context.AirDB; + +namespace WeiCloud.Core +{ + public interface IMsgService + { + Task PushFaultMsg(TbFaultHistory tbFaultHistory); + Task PushNoticeInfoMsg(SendInfoGic info); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs new file mode 100644 index 0000000..40e3940 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs @@ -0,0 +1,163 @@ +using Microsoft.Extensions.Logging; +using WeiCloud.Core.EventBus; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core; +using WeiCloud.Entity; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.UserCenter; +using Microsoft.Extensions.Configuration; + +namespace WeiCloud.Core +{ + public class MsgService : IMsgService + { + private readonly ILogger _logger; + private readonly IDictionaryService _dictionaryService; + + private readonly IPublisherService _publisherService; + public MsgService(ILogger logger, IDictionaryService dictionaryService, IConfiguration configuration, IPublisherService publisherService) + { + _logger = logger; + _dictionaryService = dictionaryService; + + _publisherService = publisherService; + } + public async Task PushFaultMsg(TbFaultHistory tbFaultHistory) + { + try + { + if (tbFaultHistory.Projectid == null) + { + return; + } + var projectInfo = _dictionaryService.GetValue(typeof(ProjectInfo).Name)[tbFaultHistory.Projectid.ToString()]; + + var userCache = _dictionaryService.GetValue(typeof(Users).Name); + var userCacheKeys = userCache.Keys; + var users = new List { }; + + foreach (var userCacheKey in userCacheKeys) + { + var user = userCache[userCacheKey]; + if (user.Isusing == 1) + { + users.Add(user); + } + } + if (users.Count() == 0) + { + return; + } + + var userIds = new List { }; + var userGroupCache = _dictionaryService.GetValue(typeof(UserGroups).Name); + var userGroupCacheKeys = userGroupCache.Keys; + foreach (var userGroupCacheKey in userGroupCacheKeys) + { + var userGroup = userGroupCache[userGroupCacheKey]; + if (userGroup.Isusing == 1 && userGroup.Ownerid == projectInfo.Ownerid) + { + var _userIds = users.Where(t => (t.UniClientId == null || t.UniClientId == "0") && t.Usergroup != null && t.Usergroup == userGroup.Id).Select(t => t.Id).ToList(); + if (_userIds.Count() > 0) + { + userIds.AddRange(_userIds); + } + } + } + if (userIds.Count() == 0) + { + return; + } + userIds = userIds.Distinct().ToList(); + + + var equip = _dictionaryService.GetValue("EquipmentInfo", new string[] { tbFaultHistory.Eqid.ToString() }).FirstOrDefault().Value; + + var msgObj = new ProduceMsgModel + { + EquId = tbFaultHistory.Eqid, + Id = tbFaultHistory.Id, + Title = "设备报警", + Content = tbFaultHistory.Faudesc, + ProjectId = tbFaultHistory.Projectid, + //UserIds = users.Select(t => t.Id).Distinct().ToList(), + UserIds = userIds, + SendTypes = new List { (int)SendTypeMeta.PcMsg }, + MsgTopic = "", + EmergencyType = 0, + MainId = tbFaultHistory.Id, + MsgType = 3, + ProjectName = projectInfo.Projectname, + ProjectShortName = projectInfo.Shortname, + EquName = equip.Eqname + }; + await _publisherService.PublishNoticeMsg(msgObj); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("PushFaultMsg", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); + } + } + public async Task PushNoticeInfoMsg(SendInfoGic info) + { + List userIdList = new List(); + try + { + string[] userId = info.UserId.Split(','); + if (userId != null && userId.Count() > 0) + { + foreach (var s in userId) + { + if (!string.IsNullOrEmpty(s)) + { + var id = long.Parse(s); + if (id > 0) + { + userIdList.Add(id); + } + } + } + } + + if (userIdList.Count == 0) + { + return; + } + userIdList = userIdList.Distinct().ToList(); + var projectInfo = _dictionaryService.GetValue(typeof(ProjectInfo).Name, new String[] { info.ProjectId.ToString() }).FirstOrDefault().Value; + + var msgObj = new ProduceMsgModel + { + EquId = 0, + Id = info.Id, + Title = info.Title, + Content = info.Message, + ProjectId = info.ProjectId, + //UserIds = users.Select(t => t.Id).Distinct().ToList(), + UserIds = userIdList, + //SendTypes = new List { (int)SendTypeMeta.AppMsg, (int)SendTypeMeta.PcMsg } + SendTypes = info.SendType, + EmergencyType = 0, + MainId = info.Id, + MsgType = 4, + ProjectName = projectInfo.Projectname, + ProjectShortName = projectInfo.Projectname, + EquName = "" + }; + await _publisherService.PublishNoticeMsg(msgObj); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("PushNoticeInfoMsg 推送异常", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs new file mode 100644 index 0000000..3bb10ee --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs @@ -0,0 +1,299 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils.Common; +using WeiCloud.Entity.Context.UserCenter; +using Microsoft.Extensions.DependencyInjection; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.InfoModels; +using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.JsonPatch.Internal; +using NPOI.XSSF.UserModel; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using System.Net.Http; +using Newtonsoft.Json; + +namespace WeiCloud.Core.Services +{ + public class NlogCoreService : WeiCloud.Core.BaseCore.Grain, INlogCoreService + { + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ILogger _logger; + public NlogCoreService(IServiceScopeFactory serviceScopeFactory, ILogger logger) + { + _serviceScopeFactory = serviceScopeFactory; + _logger = logger; + } + //获取内网IP + private IPAddress GetInternalIP() + { + NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); + + foreach (NetworkInterface adapter in nics) + { + foreach (var uni in adapter.GetIPProperties().UnicastAddresses) + { + if (uni.Address.AddressFamily == AddressFamily.InterNetwork) + { + return uni.Address; + } + } + } + return null; + } + /// + /// 日志写入数据库 + /// + /// 日志实体 + /// 操作结果值 + public async Task PostNlogsParam(string actionName, int? type, string oldValue, string newValue, string message, long operatorId = 0, string operatorName = "") + { + var result = true; + long userId = operatorId; + string userName = operatorName; + if (userId == 0) + { + var currentUser = CurrentContext.GetContext(); + userId = currentUser.UserId; + userName = currentUser.UserName; + } + if (string.IsNullOrEmpty(userName)) + { + userName = "无"; + } + Nlog log = new Nlog(); + try + { + log.Id = UidGenerator.Uid(); + log.MachineIp = GetInternalIP().ToString(); + log.CreateUserId = userId; + log.CreateTime = DateTime.Now;//创建时间 + log.ActionName = actionName; + log.LogType = type; + log.OldParmValue = oldValue; + log.NewParmValue = newValue; + log.Message = message; + log.CreateUserName = userName; + using var scope = _serviceScopeFactory.CreateScope(); + var _context = scope.ServiceProvider.GetRequiredService(); + _context.Nlog.Add(log); + //数据库中更新用户状态 + await _context.SaveChangesAsync(); + } + catch (Exception ex) + { + result = false; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " PostNlogsParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + /// + /// + /// + /// + /// + public async Task> UpdateOrAndNlogs(List nlogs) + { + var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value }; + if (nlogs == null || nlogs.Count() == 0) + { + return result; + } + using var scope = _serviceScopeFactory.CreateScope(); + var configuration = scope.ServiceProvider.GetRequiredService(); + var _context = scope.ServiceProvider.GetRequiredService(); + long userId = 0; + string userName = string.Empty; + string remoteIPAddress = string.Empty; + var nlog = nlogs.FirstOrDefault(t => t.CreateUserId > 0); + var currentUser = CurrentContext.GetContext(); + remoteIPAddress = currentUser.RemoteIPAddress; + if (nlog == null) + { + try + { + userId = currentUser.UserId; + userName = currentUser.UserName; + } + catch (Exception ex) + { + _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}"); + } + } + else + { + userId = nlog.CreateUserId; + userName = nlog.CreateUserName; + } + + try + { + foreach (var item in nlogs) + { + var log = new Nlog() + { + Id = item.Id == 0 ? UidGenerator.Uid() : item.Id, + ActionName = item.ActionName, + CreateUserId = userId, + CreateUserName = userName ?? "", + MachineIp = remoteIPAddress, + ProjectId = item.ProjectId, + EquipId = item.EquipId, + Message = item.Message, + LogType = item.LogType, + Parameter = item.Parameter, + OldParmValue = item.OldParmValue, + NewParmValue = item.NewParmValue, + CreateTime = DateTime.Now, + TerminalType = item.TerminalType, + EndDateTime = item.EndDateTime, + IphomePlace = item.IphomePlace, + }; + _context.Add(log); + } + var sqlint = _context.SaveChanges(); + result.Code = sqlint > 0 ? RequestBackStatuEnum.success.Value : RequestBackStatuEnum.fail.Value; + result.Data = sqlint; + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = ex.Message; + _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}--InnerEx:{ex.InnerException}"); + } + return result; + } + public async Task> UpdateOrAndNlogs(CmdNlogBoNew item) + { + var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value }; + using var scope = _serviceScopeFactory.CreateScope(); + var _context = scope.ServiceProvider.GetRequiredService(); + try + { + + var nlog = new Nlog() + { + Id = item.Id == 0 ? UidGenerator.Uid() : item.Id, + ActionName = item.ActionName, + CreateUserId = item.CreateUserId, + CreateUserName = item.CreateUserName, + MachineIp = item.MachineIp, + ProjectId = item.ProjectId, + EquipId = item.EquipId, + Message = item.Message, + LogType = item.LogType, + Parameter = item.Parameter, + OldParmValue = item.OldParmValue, + NewParmValue = item.NewParmValue, + CreateTime = DateTime.Now, + TerminalType = item.TerminalType, + EndDateTime = item.EndDateTime, + IphomePlace = item.IphomePlace, + }; + _context.Add(nlog); + var sqlint = _context.SaveChanges(); + result.Code = sqlint > 0 ? RequestBackStatuEnum.success.Value : RequestBackStatuEnum.fail.Value; + result.Data = sqlint; + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = ex.Message; + _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}"); + } + return result; + } + /// + /// 添加日志 + /// + /// + /// + public async Task> UpdateOrAndNlog(CmdNlogBoNew item) + { + var result = await UpdateOrAndNlogs(new List { item }); + return result; + } + public async Task> GetIPHomePlaces(List ips) + { + var ipHomePlaceDic = new Dictionary { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var configuration = scope.ServiceProvider.GetRequiredService(); + var httpCilent = scope.ServiceProvider.GetRequiredService(); + var requestIPHomePlaceUrl = configuration["SysLog:IPHomePlace"]; + var userCenterDB = scope.ServiceProvider.GetRequiredService(); + var ipHomePlaces = await userCenterDB.IphomePlace.Where(t => ips.Contains(t.Ipaddress)).AsNoTracking().ToListAsync(); + var newIphomePlaces = new List { }; + foreach (var ip in ips) + { + if (string.IsNullOrEmpty(ip) || newIphomePlaces.Any(t => t.Ipaddress == ip)) + { + continue; + } + var ipHomePlace = ipHomePlaces.FirstOrDefault(t => t.Ipaddress == ip); + if (ipHomePlace == null && !string.IsNullOrEmpty(requestIPHomePlaceUrl)) + { + #region 获取归属IP地址 + try + { + var apiUrl = requestIPHomePlaceUrl + $"?query={ip}&co=&resource_id=6006&oe=utf8"; + var client = httpCilent.CreateClient(); + client.Timeout = TimeSpan.FromSeconds(1); + var httpResponse = await client.GetAsync(apiUrl); + var responseBody = string.Empty; + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + responseBody = await httpResponse.Content.ReadAsStringAsync(); + var responseBodyObj = JsonConvert.DeserializeObject(responseBody); + if (responseBodyObj != null && responseBodyObj.data != null && responseBodyObj.data.Count() > 0) + { + newIphomePlaces.Add(new IphomePlace + { + Ipaddress = ip, + HomePlace = responseBodyObj.data.FirstOrDefault().location + }); + ipHomePlaceDic.TryAdd(ip, responseBodyObj.data.FirstOrDefault().location); + } + } + } + catch (Exception) + { + } + #endregion + } + else + { + ipHomePlaceDic.TryAdd(ip, ipHomePlace.HomePlace); + } + } + if (newIphomePlaces.Count > 0) + { + userCenterDB.IphomePlace.AddRange(newIphomePlaces); + await userCenterDB.SaveChangesAsync(); + } + } + catch (Exception ex) + { + _logger.LogError($"{this.GetType().FullName}-->>抛出异常:ex:{ex.Message}"); + } + return ipHomePlaceDic; + } + } +} +internal class IpHomePlaceModel +{ + public List data { get; set; } +} +internal class IpHomePlaceDataModel +{ + public string location { get; set; } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs new file mode 100644 index 0000000..77e80ef --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs @@ -0,0 +1,100 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Utils.RedisUtil; + +namespace WeiCloud.Core.Services.Permission +{ + public class FunPermissionCoreService : WeiCloud.Core.BaseCore.Grain, IFunPermissionCoreService + { + private readonly WeiCloudDBUserCenterContext _context; + private readonly IStringService _stringService; + private readonly ILogger _logger; + public FunPermissionCoreService(IStringService stringService, WeiCloudDBUserCenterContext context, ILogger logger) + { + _logger = logger; + _context = context; + _stringService = stringService; + } + + /// + /// 获取当前人角色权限 + /// + /// + public async Task> GetCurrentUserFunPermissions() + { + var currentUser = CurrentContext.GetContext(); + List result = null; + try + { + result = _stringService.Get>(string.Format(FamilyDecorationEnum.RoleFunPermissionCacheKey, currentUser.RoleId)); + if (result == null) + { + result = await _context.RoleFunPermission.Where(t => t.RoleId == currentUser.RoleId).AsNoTracking().Select(t => t.FunPermissionId).ToListAsync(); + _stringService.Set(string.Format(FamilyDecorationEnum.RoleFunPermissionCacheKey, currentUser.RoleId), result, 3600); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return result; + } + /// + /// 获取用户的权限 + /// + /// + public async Task GetCurrentUserFun(long projectId, string path) + { + var currentUser = CurrentContext.GetContext(); + List funIds = new List(); + long result = 1; + try + { + if (projectId == 0) + { + var prof = await _context.ProjectFunPermission.Where(d => d.Address.Contains(path)).FirstOrDefaultAsync(); + if (prof != null) + { + projectId = prof.ProjectId; + } + } + //查询当前用户的菜单 + //var data = await (from f in _context.ProjectFunPermission join p in _context.ProjectMenu on f.MenuId equals p.Menuid where p.Projectid == projectId && f.Address == path select f).ToListAsync(); + var data = await (from f in _context.ProjectFunPermission where f.ProjectId == projectId && f.Address == path select f).ToListAsync(); + if (data == null || data.Count == 0)//菜单没有设置权限 + { + return 1; + } + funIds = data.Select(d => d.Id).ToList(); + //查找角色的功能权限是否存在 + var pr = await (from r in _context.RoleFunPermission + join p in _context.ProjectFunPermission on r.FunPermissionId equals p.Id + where r.RoleId == currentUser.RoleId && funIds.Contains(p.Id) && p.Address == path + select p).ToListAsync(); + if (pr != null && pr.Count > 0) + { + result = 1; + } + else + { + result = 0; + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs new file mode 100644 index 0000000..a4cfd4a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; + +namespace WeiCloud.Core.Services.Permission +{ + public interface IFunPermissionCoreService + { + Task> GetCurrentUserFunPermissions(); + Task GetCurrentUserFun(long projectId,string path); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs new file mode 100644 index 0000000..152c391 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class PermissionsGainCoreService: IPermissionsGainCoreService + { + private readonly IListService _listService; + private readonly IDictionaryService _dictionaryService; + public PermissionsGainCoreService(IListService listService, IDictionaryService dictionaryService) + { + _listService = listService; + _dictionaryService = dictionaryService; + } + /// + /// 获取全部权限清单 + /// + /// + public async Task> GetAllPermissionsRedis() + { + Permissions press = new Permissions(); + var result = _dictionaryService.GetValue(press.GetType().Name); + var list = result.Values.ToList(); + return await Task.FromResult(list); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs new file mode 100644 index 0000000..9d8dd3c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Text; + +namespace WeiCloud.Core.Services +{ + public static class PredicateBuilder + { + public static Expression> True() { return x => true; } + + public static Expression> False() { return x => false; } + + public static Expression> Or( + this Expression> expr1, + Expression> expr2) + { + var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); + return Expression.Lambda>( + Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); + } + + public static Expression> And( + this Expression> expr1, + Expression> expr2) + { + var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); + return Expression.Lambda>( + Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters); + } + } + +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs new file mode 100644 index 0000000..c5b363a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.SafetyFirePro; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.ProjectAlarm; + +namespace WeiCloud.Core.Services.ProAlarm +{ + public interface IProAlarmService + { + Task> ArrearsAlarm(string msg, long ammeterId, short state, DateTime alarmTime); + Task> SaveAlarm(List inputs); + Task> SaveEnergyAduitAlarm(long optionId, string msg, DateTime alarmTime); + Task> SaveFaultAlarm(List tbFaultHistorys); + Task> SaveSafetyFireProtectFaultAlarm(List faultHistorys); + Task> TestSaveFaultAlarm(DateTime startTime, DateTime endTime, long projectId); + Task> UpdateAlarmState(long id, short state); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs new file mode 100644 index 0000000..c5d479a --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs @@ -0,0 +1,418 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Org.BouncyCastle.Tls; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.SafetyFirePro; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.ProjectAlarm; +using WeiCloud.Entity.Models.Sysconfig; +using WeiCloud.Utils.Common; +namespace WeiCloud.Core.Services.ProAlarm +{ + public class ProAlarmService : IProAlarmService + { + private readonly WeiCloudDBContext _dbContext; + private readonly ILogger _logger; + private readonly IServiceScopeFactory _serviceScopeFactory; + public ProAlarmService(WeiCloudDBContext dbContext, ILogger logger, IServiceScopeFactory serviceScopeFactory) + { + _dbContext = dbContext; + _logger = logger; + _serviceScopeFactory = serviceScopeFactory; + } + /// + /// 保存报警信息 + /// + /// + /// + public async Task> SaveAlarm(List inputs) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + if (inputs == null || !inputs.Any()) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "没有需要保存的报警信息"; + return result; + } + var mapIds = inputs.Select(t => t.MapId).ToList(); + var exitProAlarms = await _dbContext.ProAlarm.Where(t => mapIds.Contains(t.MapId)).ToListAsync(); + foreach (var input in inputs) + { + var proAlarm = exitProAlarms.FirstOrDefault(t => t.MapId == input.MapId); + if (proAlarm == null) + { + proAlarm = new WeiCloud.Entity.Context.DB.ProAlarm + { + Id = UidGenerator.Uid(), + AlarmType = input.AlarmType, + AlarmLevel = input.AlarmLevel, + Theme = input.Theme, + Content = input.Content, + AlarmTime = input.AlarmTime, + State = input.State, + MapId = input.MapId, + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + AlarmProcessedTime = input.ProcessTime + }; + await _dbContext.ProAlarm.AddAsync(proAlarm); + } + else + { + // 更新已存在的报警信息 + proAlarm.Theme = input.Theme; + proAlarm.Content = input.Content; + proAlarm.UpdateTime = DateTime.Now; + proAlarm.AlarmProcessedTime = input.ProcessTime; + proAlarm.State = input.State; + _dbContext.Attach(proAlarm).State = EntityState.Modified; + _dbContext.Entry(proAlarm).Property(t => t.Theme).IsModified = true; + _dbContext.Entry(proAlarm).Property(t => t.Content).IsModified = true; + _dbContext.Entry(proAlarm).Property(t => t.UpdateTime).IsModified = true; + _dbContext.Entry(proAlarm).Property(t => t.AlarmProcessedTime).IsModified = true; + _dbContext.Entry(proAlarm).Property(t => t.State).IsModified = true; + } + await _dbContext.SaveChangesAsync(); + } + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); + } + return result; + } + /// + /// 更新报警状态 + /// + /// + /// + /// + public async Task> UpdateAlarmState(long id, short state) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + var proAlarm = await _dbContext.ProAlarm.FirstOrDefaultAsync(t => t.MapId == id); + if (proAlarm == null) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "未找到对应的报警信息"; + return result; + } + proAlarm.State = state; + proAlarm.UpdateTime = DateTime.Now; + _dbContext.Attach(proAlarm).State = EntityState.Modified; + _dbContext.Entry(proAlarm).Property(t => t.State).IsModified = true; + await _dbContext.SaveChangesAsync(); + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); + } + return result; + } + /// + /// 保存故障报警信息-- 设备报警 + /// + /// + /// + public async Task> SaveFaultAlarm(List tbFaultHistorys) + { + var fauClassIds = tbFaultHistorys.Select(t => t.Fauclass ?? 0).Distinct().ToList(); + var faultClasss = await _dbContext.TbFaultClass.Where(t => fauClassIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + var alarms = new List { }; + var faultIds = tbFaultHistorys.Select(t => t.Id).ToList(); + var faultHandles = await _dbContext.TbFaultHandle.Where(t => t.Faultid != null && faultIds.Contains((long)t.Faultid)).Select(t => new + { + t.Faultid, + t.Handletime + }).ToListAsync(); + foreach (var tbFaultHistory in tbFaultHistorys) + { + var faultClass = faultClasss.FirstOrDefault(t => t.Id == tbFaultHistory.Fauclass.GetValueOrDefault()); + var alarmLevel = (short)ProAlarmLevelEnum.Warning; + if (faultClass != null) + { + if (faultClass.Classname.Contains("重大")) + { + alarmLevel = (short)ProAlarmLevelEnum.Critical; + } + else if (faultClass.Classname.Contains("严重")) + { + alarmLevel = (short)ProAlarmLevelEnum.Major; + } + else if (faultClass.Classname.Contains("一般")) + { + alarmLevel = (short)ProAlarmLevelEnum.Minor; + } + else if (faultClass.Classname.Contains("轻微")) + { + alarmLevel = (short)ProAlarmLevelEnum.Warning; + } + } + var state = (short)ProAlarmStatus.Unhandled; + if (tbFaultHistory.Status == 1) + { + state = (short)ProAlarmStatus.Unhandled; + } + else if (tbFaultHistory.Status == 2) + { + state = (short)ProAlarmStatus.NoActionRequired; + } + else if (tbFaultHistory.Status == 3) + { + state = (short)ProAlarmStatus.InProgress; + } + else if (tbFaultHistory.Status == 4 || tbFaultHistory.Status == 5) + { + state = (short)ProAlarmStatus.Completed; + } + else if (tbFaultHistory.Status == 6) + { + state = (short)ProAlarmStatus.FalseAlarm; + } + var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto + { + AlarmType = "Fault_Alarm", + AlarmLevel = alarmLevel, + Theme = "故障报警", + Content = tbFaultHistory.Faudesc, + AlarmTime = tbFaultHistory.Createtime.GetValueOrDefault(), + State = state, + MapId = tbFaultHistory.Id + }; + + var handleTime = faultHandles.FirstOrDefault(t => t.Faultid == tbFaultHistory.Id); + if (handleTime != null && handleTime.Handletime.HasValue) + { + alarm.ProcessTime = handleTime.Handletime.Value; + state = (short)ProAlarmStatus.Completed; + } + alarms.Add(alarm); + } + var result = await SaveAlarm(alarms); + return result; + } + /// + /// 保存欠费报警信息 + /// + /// + /// + /// 1-报警、2-已处理 + /// + /// + public async Task> ArrearsAlarm(string msg, long ammeterId, short state, DateTime alarmTime) + { + var alarms = new List { }; + var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto + { + AlarmType = "Arrears_Warning", + AlarmLevel = (short)ProAlarmLevelEnum.Major, + Theme = "欠费报警", + Content = msg, + AlarmTime = alarmTime, + //State = (short)ProAlarmStatus.Unhandled, + MapId = ammeterId + }; + if (state == 1) + { + alarm.State = (short)ProAlarmStatus.Unhandled; + } + else if (state == 2) + { + alarm.State = (short)ProAlarmStatus.Completed; + alarm.ProcessTime = DateTime.Now; + } + alarms.Add(alarm); + var result = await SaveAlarm(alarms); + return result; + } + /// + /// 保存能源体检报警信息 + /// + /// + /// + /// + /// + public async Task> SaveEnergyAduitAlarm(long optionId, string msg, DateTime alarmTime) + { + var alarms = new List { }; + var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto + { + AlarmType = "Physical_Warning", + AlarmLevel = (short)ProAlarmLevelEnum.Major, + Theme = "能源体检", + Content = msg, + AlarmTime = alarmTime, + MapId = optionId + }; + alarm.State = (short)ProAlarmStatus.NoActionRequired; + alarm.ProcessTime = alarmTime; + alarms.Add(alarm); + var result = await SaveAlarm(alarms); + return result; + } + /// + /// 保存安消报警信息 + /// + /// + /// + public async Task> SaveSafetyFireProtectFaultAlarm(List faultHistorys) + { + if (!faultHistorys.Any()) + { + return new ApiResult + { + Code = RequestBackStatuEnum.fail.Value, + Msg = "没有需要保存的安消报警信息" + }; + } + using var scope = _serviceScopeFactory.CreateScope(); + var safetyFireProContext = scope.ServiceProvider.GetRequiredService(); + //"AlarmLevel,AlarmStatus,AlarmAcceptRes" + var alarmLevelKey = "AlarmLevel"; + var alarmStatusKey = "AlarmStatus"; + var alarmAcceptResKey = "AlarmAcceptRes"; + //报警枚举 + var axSysConfigs = await safetyFireProContext.AxSysConfig.Where(t => t.Key == alarmLevelKey || t.Key == alarmStatusKey || t.Key == alarmAcceptResKey).AsNoTracking().Select(t => new + { + t.Key, + t.KeyMemo, + t.Value + }).ToListAsync(); + var dictionary = new Dictionary>(); + foreach (var axSysConfig in axSysConfigs) + { + dictionary.Add(axSysConfig.Key, JsonConvert.DeserializeObject>(axSysConfig.Value)); + } + + var alarms = new List { }; + + foreach (var faultHistory in faultHistorys) + { + dictionary.TryGetValue(alarmLevelKey, out var alarmLevelList); + var alarmLevel = (short)ProAlarmLevelEnum.Warning; + if (alarmLevelList != null) + { + var axAlarmLevel = alarmLevelList.FirstOrDefault(t => t.Key == faultHistory.Level); + if (axAlarmLevel != null) + { + if (axAlarmLevel.Value.Contains("重大") || axAlarmLevel.Value.Contains("紧急")) + { + alarmLevel = (short)ProAlarmLevelEnum.Critical; + } + else if (axAlarmLevel.Value.Contains("重要")) + { + alarmLevel = (short)ProAlarmLevelEnum.Major; + } + else if (axAlarmLevel.Value.Contains("一般")) + { + alarmLevel = (short)ProAlarmLevelEnum.Minor; + } + else if (axAlarmLevel.Value.Contains("轻微")) + { + alarmLevel = (short)ProAlarmLevelEnum.Warning; + } + } + } + + + dictionary.TryGetValue(alarmStatusKey, out var alarmStatusList); + dictionary.TryGetValue(alarmAcceptResKey, out var alarmAcceptResList); + DateTime? processTime = null;//处理时间 + var state = (short)ProAlarmStatus.Unhandled; + + if (faultHistory.Status == 1) + { + state = (short)ProAlarmStatus.Unhandled; + } + else if (faultHistory.Status == 1 || faultHistory.Status == 2) + { + state = (short)ProAlarmStatus.InProgress; + } + else if (faultHistory.Status == 3) + { + state = (short)ProAlarmStatus.Completed; + processTime = faultHistory.DisposalTime; + } + //if (faultHistory.AcceptRes == 1) + //{ + // state = (short)ProAlarmStatus.InProgress; + //} + //else if (faultHistory.AcceptRes == 2) + //{ + // state = (short)ProAlarmStatus.NoActionRequired; + // processTime = faultHistory.ResponseTime; + //} + //else if (faultHistory.AcceptRes == 3) + //{ + // state = (short)ProAlarmStatus.FalseAlarm; + // processTime = faultHistory.ResponseTime; + //} + if (faultHistory.AcceptRes == 2) + { + state = (short)ProAlarmStatus.NoActionRequired; + processTime = faultHistory.ResponseTime; + } + else if (faultHistory.AcceptRes == 3) + { + state = (short)ProAlarmStatus.FalseAlarm; + processTime = faultHistory.ResponseTime; + } + var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto + { + AlarmType = "Security_Alarm", + AlarmLevel = alarmLevel, + Theme = "安消报警", + Content = faultHistory.Name, + AlarmTime = faultHistory.CreateTime.GetValueOrDefault(), + State = state, + MapId = faultHistory.Id + }; + alarms.Add(alarm); + } + var result = await SaveAlarm(alarms); + return result; + } + + /// + /// 测试保存故障报警信息 + /// + /// + /// + /// + /// + public async Task> TestSaveFaultAlarm(DateTime startTime, DateTime endTime, long projectId) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var airDBContext = scope.ServiceProvider.GetRequiredService(); + var tbFaultHistorys = await airDBContext.TbFaultHistory + .Where(t => t.Projectid == projectId && t.Createtime >= startTime && t.Createtime <= endTime).AsNoTracking().ToListAsync(); + result = await SaveFaultAlarm(tbFaultHistorys); + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs new file mode 100644 index 0000000..11a7058 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.Context.AirDB; + +namespace WeiCloud.Core.Services +{ + public class ProjectDWCoreService : IProjectDWCoreService + { + private readonly WeiCloudAirDBContext _Aircontext; + private readonly ILogger _logger; + private List projectId; + public ProjectDWCoreService(WeiCloudAirDBContext Aircontext, ILogger logger) + { + _Aircontext = Aircontext; + _logger = logger; + } + /// + /// 获得今年到目前为止的能耗 + /// + /// + public async Task GetCurrentEnergyYear(long? projectid, DateTime dateTime) + { + DateTime now = DateTimeTools.GetSysDateTimeNow(); + DateTime yearfristday = DateTimeTools.GetYearFirstDay(); + double reData = 0; + try + { + var dwData = await _Aircontext.TbProjectDw.Where(a => a.Parm002 == projectid).ToListAsync(); + var result = (from a in dwData + where a.Parm002 == projectid && a.Parm003 > yearfristday && a.Parm003 < now + group a by a.Parm002 into g + select new + { //002 累计用电,004 累计用水 ,006 累计用气 + sum = (g.Max(a => a.PdParm002) - g.Min(a => a.PdParm002)) * 0.123 + (g.Max(a => a.PdParm004) - g.Min(a => a.PdParm004)) * 1.330 + }).Sum(a => a.sum); + if (result != null && result > 0) + { + reData = (double)result; + } + return reData; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("GetCurrentEnergyYear:{0}", ex)).GetNlogMessage()); + return await Task.FromResult(-1); + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs new file mode 100644 index 0000000..3eb3883 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class ProjectInfoGainCoreService: IProjectInfoGainCoreService + { + private readonly IListService _listService; + private readonly IDictionaryService _dictionaryService; + public ProjectInfoGainCoreService(IListService listService, IDictionaryService dictionaryService) + { + _listService = listService; + _dictionaryService = dictionaryService; + } + public async Task> GetAllEquipRedis() + { + EquipmentInfo equip = new EquipmentInfo(); + var result = _dictionaryService.GetValue(equip.GetType().Name); + var list = result.Values.ToList(); + + return await Task.FromResult(list); + } + public async Task GetEquipModel(long equipId) + { + EquipmentInfo equip = new EquipmentInfo(); + equip = _dictionaryService.GetValue(equip.GetType().Name)[equipId.ToString()]; + return await Task.FromResult(equip); + } + public async Task> GetEquipListByKeys(string[] keys) + { + List equip = new List(); + EquipmentInfo e = new EquipmentInfo(); + equip = _dictionaryService.GetValue(e.GetType().Name, keys).Select(d => d.Value).ToList(); + if (equip != null) + { + equip = equip.Where(d => d != null && d.Id > 0).ToList(); + } + return await Task.FromResult(equip); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs new file mode 100644 index 0000000..5fea871 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs @@ -0,0 +1,625 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.InfoModels; +using WeiCloud.Entity.LogicModels.SysModule; +using WeiCloud.Utils; +using WeiCloud.Utils.RedisUtil; + +namespace WeiCloud.Core.Services +{ + public class PublicFunctionService:IPublicFunctionService + { + private readonly WeiCloudDBContext _context; + private readonly WeiCloudAirDBContext _airContext; + private readonly ILogger _logger; + //private readonly IOptions _ftpUploadConfig; + private readonly IDictionaryService _dictionaryService; + private readonly IUserProjectPressRedisTreeCoreService _pressService; + private readonly WeiCloudDBUserCenterContext _userCenterContext; + public PublicFunctionService(WeiCloudDBContext context, WeiCloudAirDBContext airContext, ILogger logger, + WeiCloudDBUserCenterContext userCenterContext,IDictionaryService dictionaryService, IUserProjectPressRedisTreeCoreService pressService) + { + _context = context; + _airContext = airContext; + _logger = logger; + _dictionaryService = dictionaryService; + _userCenterContext = userCenterContext; + _pressService = pressService; + } + #region 根据登录者获取相应的项目信息(多用于项目下拉框数据源) + /// + /// 根据登录者获取相应的项目信息 + /// + /// + /// + public async Task>> GetProjectListByRole(CurrentUser user) + { + var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Data = new List() }; + try + { + var redisresult = _dictionaryService.GetValue(HashKeyNames.ProjectInfo); + if (redisresult == null || redisresult.Values == null) + { + result.Code = RequestBackStatuEnum.diy.Value; + result.Data = new List(); + return result; + } + var query = redisresult.Values.Where(x => x.State == 1).Select(p => new GetProjectModel + { + Id = p.Id, + Projectname = p.Projectname, + Shortname = p.Shortname, + Ownerid = p.Ownerid, + State = p.State + }).OrderBy(p => p.Projectname).ToList(); + if (user.RoleCode == SysBaseCodeMeta.AdminCode) + {//超级管理员 + result.Data = query; + + } + else + {//其他角色 + result.Data = query.Where(t => user.ProjectIds.Contains(t.Id)).ToList(); + } + return result; + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = ex.Message; + } + return await Task.FromResult(result); + } + #endregion + + #region 获取能耗-水电气热等类型(多用于下拉跨数据源) + public async Task>> GetEngeryType() + { + ApiResult> result = new ApiResult>() { Code=RequestBackStatuEnum.success.Value,Msg="接口请求成功!"}; + List list = new List(); + try + { + list.Add(new DropSimpleTypeModel() { Id= EngeryTypeEnum.ElectEngery,Name="电"}); + list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.WaterEngery, Name = "水" }); + list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.GasEngery, Name = "气" }); + list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.HeatEngery, Name = "热" }); + result.Data = list; + return await Task.FromResult(result); + } + catch (Exception) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "接口请求失败!"; + return result; + } + } + #endregion + #region 获取空气质量类型(多用于下拉跨数据源) + + public async Task>> GetAirQuantityType() + { + ApiResult> result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "接口请求成功!" }; + List list = new List(); + try + { + list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.Temperature, Name = "温度" }); + list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.Humidity, Name = "湿度" }); + list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.CO2, Name = "CO₂" }); + list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.TVOC, Name = "TVOC" }); + list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.PM, Name = "PM2.5" }); + result.Data = list; + return await Task.FromResult(result); + } + catch (Exception) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "接口请求失败!"; + return result; + } + } + #endregion + #region 获取时间间隔数据多用于历史数据查询(下拉跨数据源) + public async Task>> GetTimeSpanData() + { + ApiResult> result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "接口请求成功!" }; + List list = new List(); + try + { + list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.FiveMinute, Name = "5分钟" }); + list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.TenMinute, Name = "10分钟" }); + list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.HalfHour, Name = "30分钟" }); + list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.Hour, Name = "一小时" }); + result.Data = list; + return await Task.FromResult(result); + } + catch (Exception) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = "接口请求失败!"; + return result; + } + } + #endregion + #region 天气 + #region 获取当天天气 + /// + /// 获取当天天气 + /// + /// + /// + public async Task> GetWeatherByProId(long proiectId) + { + ApiResult result = new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "接口请求失败!" }; + string now = DateTime.Now.ToString("yyyy-MM-dd"); ; + WeatherTwoGic gic = new WeatherTwoGic(); + try + { + var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); + var sysAreas = await _userCenterContext.SysArea.ToListAsync(); + var data = (from p in projectInfos + join o in sysAreas + on p.Position equals o.RegionCode + join w in _airContext.WeatherTwo + on p.Position equals w.AreaId + where p.Id == proiectId + && w.WeatherDate.Contains(now) + orderby w.UpdateDate descending + select new WeatherTwoGic + { + Id = w.Id, + WeatherDay = w.WeatherDay, + WeatherDate = w.WeatherDate, + WeatherWea = w.WeatherWea, + WeatherWeaImg = w.WeatherWeaImg, + WeatherTem1 = w.WeatherTem1, + WeatherTem2 = w.WeatherTem2, + WeatherTem = w.WeatherTem, + WeatherWin = w.WeatherWin, + WeatherWinSpeed = w.WeatherWinSpeed, + AreaId = w.AreaId, + PositionName = o.RegionName + } + ).FirstOrDefault(); + if (data != null && !string.IsNullOrEmpty(data.WeatherWin)) + { + var weatherWins = gic.WeatherWin.Split(","); + if (weatherWins.Length > 0) + { + data.WeatherWin = weatherWins[0]; + } + gic = data; + } + result.Code = RequestBackStatuEnum.success.Value; + result.Msg= "接口请求成功!"; + result.Data = gic; + return await Task.FromResult(result); + } + catch (Exception ex) + { + return result; + } + } + #endregion + #region 获取未来7天天气预报 + /// + /// 获取未来7天天气预报 + /// + /// 项目id + /// 天气集合 + public async Task>> Get7DaysWeatherByProId(long proiectId) + { + ApiResult> action = new ApiResult>(); + DateTime now = DateTime.Now.Date; + DateTime end = DateTime.Now.AddDays(7).Date; + List gic = new List(); + WeatherTwoGic nowWeather = new WeatherTwoGic(); + try + { + nowWeather = (await GetWeatherByProIdNow(proiectId)).Data; + var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); + gic = (from p in projectInfos + join w in _airContext.WeatherTwo + on p.Position equals w.AreaId + where p.Id == proiectId + //&& Convert.ToDateTime(w.WeatherDate) >= now + //&& Convert.ToDateTime(w.WeatherDate) <= end + orderby w.WeatherDate, w.UpdateDate + select new WeatherTwoGic + { + Id = w.Id, + WeatherDay = (w.WeatherDay.Substring(0, w.WeatherDay.IndexOf("("))), + WeatherDate = w.WeatherDate, + WeatherWea = w.WeatherWea, + WeatherWeaImg = w.WeatherWeaImg, + WeatherTem1 = w.WeatherTem1, + WeatherTem2 = w.WeatherTem2, + WeatherTem = w.WeatherTem, + WeatherWin = w.WeatherWin.Contains(",") ? w.WeatherWin.Substring(0, w.WeatherWin.IndexOf(",")) : w.WeatherWin, + WeatherWinSpeed = w.WeatherWinSpeed, + AreaId = w.AreaId, + // PositionName = o.RegionName + } + ).OrderByDescending(d => d.WeatherDate).DistinctBy(d => d.WeatherDay).Where(d => d != null).ToList(); + gic = gic.Where(d => Convert.ToDateTime(d.WeatherDate) >= now && Convert.ToDateTime(d.WeatherDate) <= end).OrderBy(d => d.WeatherDate).ToList(); + gic.Insert(0, nowWeather); + action.Data = gic; + action.Code = RequestBackStatuEnum.success.Value; + action.Msg = "请求成功"; + } + catch (Exception ex) + { + action.Data = null; + action.Code = RequestBackStatuEnum.fail.Value; + action.Msg = "服务器请求失败"; + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetWeatherByProId", string.Format("获取手机端天气信息报错:{0}", ex)).GetNlogMessage()); + } + return await Task.FromResult(action); + } + #endregion + #region 获取现在时刻天气 + /// + /// 获取现在时刻天气 + /// + /// + /// + public async Task> GetWeatherByProIdNow(long proiectId) + { + ApiResult result = new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "接口请求失败!" }; + WeatherTwoGic gic = new WeatherTwoGic(); + try + { + var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); + gic = (from p in projectInfos + join w in _airContext.WeatherThree + on p.Position equals w.AreaId + where p.Id == proiectId + && w.WeatherDate == DateTime.Now.Date + orderby w.Id descending + select new WeatherTwoGic + { + Id = w.Id, + WeatherDay = w.WeatherDay, + WeatherDate = w.WeatherDate.ToString(), + WeatherWea = w.WeatherWea, + WeatherWeaImg = w.WeatherWeaImg, + WeatherTem = w.WeatherTem, + WeatherWin = w.WeatherWin, + WeatherWinSpeed = w.WeatherWinSpeed, + AreaId = w.AreaId, + } + ).FirstOrDefault(); + result.Code = RequestBackStatuEnum.success.Value; + result.Msg = "接口请求成功!"; + result.Data = gic; + return await Task.FromResult(result); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("GetWeatherByProIdNow:{0}", ex)).GetNlogMessage()); + return result; + } + } + #endregion + #endregion + #region 根据项目id获取项目名称以及logo + public async Task> GetProjectBaseInfo(long projectid) + { + try + { + var projectInfo = await (from project in _userCenterContext.ProjectInfo + where project.State == 1 && project.Id == projectid + select new ProjectBaseInfo + { + ProjectName = project.Shortname, + ProjectLogoUrl = project.ProjectLogoUrl + }).FirstOrDefaultAsync(); + if (projectInfo != null) + { + return new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = projectInfo }; + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetProjectBaseInfo", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + return new ApiResult { Code = RequestBackStatuEnum.fail.Value, Msg = ex.Message }; + } + return new ApiResult { Code = RequestBackStatuEnum.fail.Value, Msg = "数据为空!" }; + } + #endregion + #region 获取项目看板页底部的菜单 + /// + /// 获取项目看板页底部的菜单 + /// + /// + /// + /// + /// + /// + public async Task>> GetProjectMenuSysModule(string roleCode, long projectId, long parentId, long? modelType = 0) + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + try + { + if (projectId == 0) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "项目Id为空!"; + return result; + } + var query = (from sm in _userCenterContext.SysModule + join psm1 in _userCenterContext.ProjectSysModule on sm.Id equals psm1.Sysmoduleid into tmppsm + from psm in tmppsm.DefaultIfEmpty() + where psm.Isenable == true && (sm.Sysid == 0 || psm.Projectid == projectId) + select new + { + SysModuleId = sm.Id, + PackageName = sm.Packagename, + ActiveRule = sm.Activerule, + ProjectId = psm.Projectid, + OwnerId = psm.Ownerid, + SysModuleName = sm.Name, + SysId = sm.Sysid, + SysModelType = sm.Sysmodeltype, + DisplayType = psm.Displaytype, + }); + if (modelType > 0) + { + query = query.Where(d => d.SysModelType == modelType); + } + else + { + query = query.Where(d => d.SysModelType != 1); + } + var sysModules = query.Select(t => new + { + SysModuleId = t.SysModuleId, + PackageName = t.PackageName, + ActiveRule = t.ActiveRule, + SysModuleName = t.SysModuleName, + SysId = t.SysId, + DisplayType = t.DisplayType, + SysModelType = t.SysModelType + + }).Distinct().ToList().Select(t => new SysUserModuleMenuModel + { + SysModuleId = t.SysModuleId, + PackageName = t.PackageName, + ActiveRule = t.ActiveRule, + SysModuleName = t.SysModuleName, + SysId = t.SysId, + DisplayType = (t.DisplayType == null || (bool)t.DisplayType == false) ? (short)0 : (short)1, + SysModelType = t.SysModelType + }).ToList(); + + + + var menus = _userCenterContext.ProjectMenu.Where(t => t.Isusing == 1 && t.Projectid == projectId).Select(t => new Permissions + { + Id = t.Id, + Permissname = t.Menuname, + Permisscode = t.Menucode, + Permisstype = t.Menutype, + Parentid = t.Parentid, + Isusing = t.Isusing, + Url = t.Url, + IName = t.IName, + Order = t.Order, + Sysmoduleid = t.Sysmoduleid + }).OrderBy(t => t.Order).ToList(); + + menus = menus.OrderBy(t => t.Order).ToList(); + + #region 菜单权限 + + if (roleCode != SysBaseCodeMeta.AdminCode) + { + var userPressStr = await _pressService.GetUserRolePress(); + List pressIdList = new List(); + //有权限才找找菜单树 + if (!string.IsNullOrEmpty(userPressStr)) + { + string[] arr = userPressStr.Split(','); + foreach (string s in arr) + { + if (!string.IsNullOrEmpty(s)) + { + long id = 0; + long.TryParse(s, out id); + if (id > 0) + { + pressIdList.Add(id); + } + } + } + } + menus = menus.Where(t => pressIdList.Contains(t.Id)).ToList(); + } + #endregion + + List firstLevelMenus = menus.Where(t => t.Parentid == parentId).ToList(); + var oneLevelPermissions = GetPermissionsGroupLevel(firstLevelMenus); + oneLevelPermissions = oneLevelPermissions.OrderBy(t => t.Order).ToList(); + var items = new List { }; + var model = (from m in _userCenterContext.ConModule select m).ToList(); + foreach (var oneLevelPermission in oneLevelPermissions) + { + var sysModule = sysModules.FirstOrDefault(t => t.SysModuleId == oneLevelPermission.Sysmoduleid); + if (sysModule == null && oneLevelPermission.Sysmoduleid != 0) + { + continue; + } + var item = new SysUserMenuModuleModel + { + Name = oneLevelPermission.Permissname, + Url = oneLevelPermission.Url, + Id = oneLevelPermission.Id, + IName = oneLevelPermission.IName, + Actions = GetActionList(oneLevelPermission.Id, menus), + //Childs = GetMenuTree1(menus, oneLevelPermission.Id, model), + MenuCode = oneLevelPermission.Permisscode, + ModelId = GetModelId(model, oneLevelPermission.Permissname), + SysModule = sysModule, + ParentId = oneLevelPermission.Parentid + }; + if (sysModule != null && sysModule.DisplayType == 1) + {//横向排序,只有下一级菜单横向显示 + var secondLevelMenus = menus.Where(t => t.Parentid == item.Id).ToList(); + var secondLevelPermissions = GetPermissionsGroupLevel(secondLevelMenus); + secondLevelPermissions = secondLevelPermissions.OrderBy(t => t.Order).ToList(); + foreach (var secondLevelPermission in secondLevelPermissions) + { + var sysModule2 = sysModules.FirstOrDefault(t => t.SysModuleId == secondLevelPermission.Sysmoduleid); + if (sysModule2 == null && secondLevelPermission.Sysmoduleid != 0) + { + continue; + } + var item2 = new SysUserMenuModuleModel + { + Name = secondLevelPermission.Permissname, + Url = secondLevelPermission.Url, + Id = secondLevelPermission.Id, + IName = secondLevelPermission.IName, + Actions = GetActionList(secondLevelPermission.Id, menus), + Childs = GetMenuTree1(menus, secondLevelPermission.Id, model, sysModules), + MenuCode = !string.IsNullOrEmpty(secondLevelPermission.Permisscode) ? secondLevelPermission.Permisscode : secondLevelPermission.Id.ToString(), + ModelId = GetModelId(model, secondLevelPermission.Permissname), + SysModule = sysModule, + ParentId = secondLevelPermission.Parentid + }; + items.Add(item2); + } + } + else + { + item.Childs = GetMenuTree1(menus, oneLevelPermission.Id, model, sysModules); + items.Add(item); + } + } + result.Data = items; + } + catch (Exception ex) + { + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = ex.Message; + _logger.LogError(new NlogMessageHelper(System.Reflection.MethodBase.GetCurrentMethod().Name, string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + private long GetModelId(List modelList, string name) + { + long id = 0; + ConModule model = new ConModule(); + model = (from m in modelList where m.ModuleName.Contains(name) select m).ToList().FirstOrDefault(); + if (model != null) + { + id = model.Id; + } + return id; + } + private List GetMenuTree1(List allPermissions, long id, List model, List sysModules) + { + var items = new List { }; + var childs = allPermissions.Where(t => t.Parentid == id && (t.Permisstype == null || t.Permisstype == 0)).ToList();//只显示菜单t.Permisstype == 0 + foreach (var child in childs) + { + var item = new SysUserMenuModuleModel + { + Name = child.Permissname, + Url = child.Url, + Id = child.Id, + IName = child.IName, + MenuCode = !string.IsNullOrEmpty(child.Permisscode) ? child.Permisscode : child.Id.ToString(), + Actions = GetActionList(child.Id, allPermissions), + ModelId = GetModelId(model, child.Permissname), + Childs = GetMenuTree1(allPermissions, child.Id, model, sysModules), + ParentId = child.Parentid + }; + items.Add(item); + var sysModule = sysModules.FirstOrDefault(t => t.SysModuleId == child.Sysmoduleid); + if (sysModule != null) + { + item.SysModule = sysModule; + } + } + return items; + } + private List GetActionList(long parentId, List pressList) + { + List codeList = new List(); + if (pressList != null && pressList.Count > 0 && parentId >= 0) + { + //查询子集中所有得操作权限code + var data = (from p in pressList where p.Parentid == parentId && p.Permisstype == 1 select p.Permisscode).ToList(); + if (data != null && data.Count > 0) + { + codeList = data; + } + } + return codeList; + } + private List GetPermissionsGroupLevel(List permissions) + { + var parentPermissions = new List { }; + foreach (var permission in permissions) + { + //if (permission.Parentid == null || permission.Parentid == 0) + //{ + // parentPermissions.Add(permission); + //} + //else + //{ + // var parent = permissions.FirstOrDefault(t => t.Id == permission.Parentid); + // if (parent == null) + // { + // parentPermissions.Add(permission); + // } + // else if (parent.Parentid == null || permission.Parentid == 0) + // { + // parentPermissions.Add(parent); + // } + // else + // { + // var _permission = GetPermissionsGroupLevel(permissions, parent); + // } + //} + var _permission = GetPermissionsGroupLevel(permissions, permission); + if (_permission != null) + { + parentPermissions.Add(_permission); + } + } + parentPermissions = parentPermissions.Distinct().ToList(); + return parentPermissions; + } + private Permissions GetPermissionsGroupLevel(List permissions, Permissions permission) + { + var parent = permissions.FirstOrDefault(t => t.Id == permission.Parentid); + if (parent == null) + { + return permission; + } + else if (parent.Parentid == null || permission.Parentid == 0) + { + return parent; + } + else + { + return GetPermissionsGroupLevel(permissions, parent); + } + } + #endregion + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs new file mode 100644 index 0000000..de8ff15 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Core.BaseCore; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.DataCollection; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.RealData +{ + public interface IRealDataCoreService : IGrainWithIntegerKey + { + Task> GetRealValueByProAndKey(long? projectid, string[] paramIds); + Task> GetRealValueFromRedisByPro(long? projectid); + Task PutRealDatas(List tbRealDatas); + Task> ModifyRealData(TbRealData tbRealData); + Task> GetRealValueFromRedisByProEdit(long? projectid); + Task UpdateRealValueToRedisByPro(long? projectid, List tbRealDatas); + Task UpdateRealvalueOnValue(long? projectid, RealDataOnlyValueBo realDataOnlyValueBo); + Task UpdateRealValueToRedisByPro(long? projectid, TbRealData tbRealData); + Task> GetRealValueFromRedisByPro(long projectid, List realdIds, List realDatas = null); + Task> CalculationHisotryVirtualParameters(List tbRealDatasOrg, DateTime? startTime, DateTime? endTime, long projectId, short timeUnit = (short)QueryTimeTypeEnum.Hour); + Task UpdateRealvalueOnValue(long projectId, List realDataOnlyValueBos); + Task> GetRealValueFromDBMaxMin(QueryRealDataTimeZonesMaxMinModel input, List realDatas = null); + Task> GetRealValueFromRedisByProVirtualByEquipId(long projectid, List realdIds, List realDatas = null); + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs new file mode 100644 index 0000000..030597e --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs @@ -0,0 +1,1761 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Utils.RedisUtil; +using WeiCloud.Entity.LogicModels.DataCollection; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity; +using Microsoft.EntityFrameworkCore; +using WeiCloud.Utils.Common; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Utils.Calculation; +using Microsoft.Extensions.DependencyInjection; +using WeiCloud.Core.Services.DataStream; +using Newtonsoft.Json; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.LogicModels.Report; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Core.Services.Report; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.IotDS; +using NPOI.SS.UserModel; +using NPOI.HSSF.Record.Chart; + +namespace WeiCloud.Core.RealData +{ + public class RealDataCoreService : IRealDataCoreService + { + private readonly IDictionaryService _dictionaryService; + private readonly ILogger _logger; + private readonly WeiCloudDBContext _weiCloudDBContext; + private readonly WeiCloudDBUserCenterContext _weiCloudDBUserCenterContext; + private readonly IStringService _stringService; + private readonly LocalData _localData; + private readonly IServiceScopeFactory _serviceScopeFactory; + private readonly ITimeSeqService _timeSeqService; + private readonly List virtualParameterUniqueCodes = new List { "NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" }; + public RealDataCoreService( + ITimeSeqService timeSeqService, + IServiceScopeFactory serviceScopeFactory, + IStringService stringService, + IDictionaryService dictionaryService, + ILogger logger, + WeiCloudDBContext weiCloudDBContext, + LocalData localData, + WeiCloudDBUserCenterContext weiCloudDBUserCenterContext) + { + _serviceScopeFactory = serviceScopeFactory; + _dictionaryService = dictionaryService; + _logger = logger; + _weiCloudDBContext = weiCloudDBContext; + _stringService = stringService; + _localData = localData; + _timeSeqService = timeSeqService; + _weiCloudDBUserCenterContext = weiCloudDBUserCenterContext; + } + public async Task UpdateRealvalueOnValue(long? projectid, RealDataOnlyValueBo realDataOnlyValueBo) + { + try + { + var onlyvaluehashid = HashKeyNames.ProRealValueAndTime + projectid.ToString(); + _dictionaryService.PushValue(onlyvaluehashid, realDataOnlyValueBo.Id.ToString(), realDataOnlyValueBo, 1); + return 1; + } + catch (Exception ex) + { + return -1; + } + } + /// + /// 批量保存 + /// + /// + /// + /// + public async Task UpdateRealvalueOnValue(long projectId, List realDataOnlyValueBos) + { + try + { + var onlyvaluehashid = HashKeyNames.ProRealValueAndTime + projectId.ToString(); + var newdic = realDataOnlyValueBos.ToDictionary(x => x.Id.ToString(), y => new RealDataOnlyValueBo { Id = y.Id, Realvalue = y.Realvalue, Updatetime = y.Updatetime }); + _dictionaryService.PushValue(onlyvaluehashid, newdic, 1); + return 1; + } + catch (Exception ex) + { + return -1; + } + } + /// + /// 更加项目id更新一个参数 + /// + /// + /// + /// + public async Task UpdateRealValueToRedisByPro(long? projectid, TbRealData tbRealData) + { + var result = 1; + try + { + + _dictionaryService.PushValue(HashKeyNames.ProEqRealValue + projectid.ToString(), tbRealData.Id.ToString(), tbRealData, 1); + + return await Task.FromResult(result); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " UpdateRealValueToRedisByPro", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + return -1; + } + } + /// + /// 根据项目id更新多个参数 + /// + /// + /// + /// + public async Task UpdateRealValueToRedisByPro(long? projectid, List tbRealDatas) + { + var result = 0; + if (projectid == null || tbRealDatas == null || tbRealDatas.Count == 0) + { + return result; + } + try + { + var dickey = $"{HashKeyNames.ProEqRealValue}{projectid}"; + var dic = tbRealDatas.Where(x => x != null && x.Id > 0).ToList().ToDictionary(x => x.Id.ToString(), y => y); + _dictionaryService.PushValue(dickey, dic, 1); + + return await Task.FromResult(result); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " UpdateRealValueToRedisByPro", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + return -1; + } + } + public async Task> GetRealValueFromRedisByProEdit(long? projectid) + { + try + { + var templist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); + if (templist == null || templist.Count == 0) + { + templist = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid select a).ToListAsync(); + if (templist != null) + { + _dictionaryService.PushValue(HashKeyNames.TbRealData, templist.ToDictionary(x => x.Id.ToString(), y => y), 1); + } + } + return templist; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + return null; + } + } + + /// + /// 获得项目下所有的实时参数 + /// + /// 项目id + /// + public async Task> GetRealValueFromRedisByPro(long? projectid) + { + try + { + //var templist = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); + var templist = await _localData.GetTbRealDatas(projectid ?? 0); + var realIdStrs = templist.Select(t => t.Id.ToString()).ToArray(); + //var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realIdStrs, 1, 1).Values.ToList(); + if (templist == null || templist.Count() == 0) + {//没有配置信息 + templist = new List { }; + } + var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realIdStrs, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); + if (realvaluelist == null || realvaluelist.Count == 0) + {//没有实时值 + return templist; + } + var isRefresh = await _localData.CheckProIdIsRefresh(projectid ?? 0, templist.Select(t => t.Id).ToList(), realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); + if (isRefresh) + { + templist = await _localData.GetTbRealDatas(projectid ?? 0); + } + var list = new List { }; + + foreach (var temp in templist) + { + var r = realvaluelist.FirstOrDefault(t => t.Id == temp.Id); + if (r != null) + { + temp.Realvalue = r.Realvalue; + temp.Updatetime = r.Updatetime; + } + list.Add(temp); + } + var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); + if (virtualRealDatas.Count() > 0) + { + var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid.GetValueOrDefault()); + foreach (var virtualItem in virtualItems) + { + var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); + if (l != null) + { + l.Realvalue = virtualItem.Realvalue; + l.Updatetime = virtualItem.Updatetime; + } + } + } + return await Task.FromResult(list); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + return new List { }; + } + } + /// + /// 使用虚拟点-设备Id + /// + /// + /// + /// + /// + public async Task> GetRealValueFromRedisByProVirtualByEquipId(long projectid, List realdIds, List realDatas = null) + { + try + { + if (realdIds == null || realdIds.Count() == 0) + { + return new List { }; + } + var realdStrIds = realdIds.Select(t => t.ToString()).ToArray(); + if (realDatas == null || realDatas.Count() == 0) + { + //realDatas = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid && realdIds.Contains(a.Id) select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); + //realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); + realDatas = await _localData.GetTbRealDatas(projectid, realdIds); + //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); + } + if (realDatas == null) + { + realDatas = new List(); + } + var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).ToList(); + if (realvaluelist == null || realvaluelist.Count == 0) + { + return realDatas; + } + var isRefresh = await _localData.CheckProIdIsRefresh(projectid, realdIds, realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); + //if (isRefresh) + //{ + // realDatas = await _localData.GetTbRealDatas(projectid, realdIds); + // //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); + //} + + var list = new List { }; + foreach (var realData in realDatas) + { + var realValue = realvaluelist.FirstOrDefault(t => t != null && t.Id == realData.Id); + if (realValue != null) + { + realData.Realvalue = realValue.Realvalue; + realData.Updatetime = realValue.Updatetime; + } + list.Add(realData); + } + //foreach (var r in realvaluelist) + //{ + // if (r == null) + // { + // continue; + // } + // var temp = realDatas.FirstOrDefault(t => t.Id == r.Id); + // if (temp != null) + // { + // temp.Realvalue = r.Realvalue; + // temp.Updatetime = r.Updatetime; + // list.Add(temp); + // } + //} + + var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); + if (virtualRealDatas.Count() > 0) + { + var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid); + foreach (var virtualItem in virtualItems) + { + var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); + if (l != null) + { + l.Realvalue = virtualItem.Realvalue; + l.Updatetime = virtualItem.Updatetime; + } + } + } + + return await Task.FromResult(list); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByProVirtualByEquipId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + return null; + } + } + public async Task> GetRealValueFromRedisByPro(long projectid, List realdIds, List realDatas = null) + { + try + { + if (realdIds == null || realdIds.Count() == 0) + { + return new List { }; + } + if (realDatas == null || realDatas.Count() == 0) + { + //realDatas = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid && realdIds.Contains(a.Id) select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); + //realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); + realDatas = await _localData.GetTbRealDatas(projectid, realdIds); + //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); + } + if (realDatas == null || realDatas.Count() == 0) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: realDatas为空;")).GetNlogMessage()); + return new List { }; + } + var standarIds = realDatas.Where(t => t.Standarparamid != null && t.Standarparamid > 0).Select(t => t.Standarparamid ?? 0).Distinct().ToList(); + var standarParams = await _weiCloudDBUserCenterContext.StandarParam.Where(t => standarIds.Contains(t.Id)).AsNoTracking().Select(t => new + { + t.Id, + t.Uniquepronoun + }).AsNoTracking().ToListAsync(); + foreach (var realData in realDatas) + { + try + { + if (string.IsNullOrEmpty(realData.JsonContent)) + { + continue; + } + var realParamJson = JsonConvert.DeserializeObject(realData.JsonContent); + if (realData.PointType == 2) + { + foreach (var point in realParamJson.CombinedPoint) + { + if (point.Key > 0) + { + realdIds.Add((long)point.Key); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); + } + } + + var realdStrIds = realdIds.Select(t => t.ToString()).Distinct().ToArray(); + var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).ToList(); + if (realvaluelist == null || realvaluelist.Count == 0) + { + return realDatas; + } + + var list = new List { }; + + //foreach (var realValue in realvaluelist) + //{ + // if (realValue==null) + // { + // continue; + // } + // var realData = realDatas.FirstOrDefault(t => t.Id == realValue.Id); + // if (realData == null) + // { + // realData = new TbRealData { Id = realValue.Id }; + // } + // realData.Realvalue = realValue.Realvalue; + // realData.Updatetime = realValue.Updatetime; + // list.Add(realData); + //} + foreach (var realData in realDatas) + { + list.Add(realData); + var realvalue = realvaluelist.Where(t => t != null).FirstOrDefault(t => t.Id == realData.Id); + if (realvalue != null) + { + realData.Realvalue = realvalue.Realvalue; + realData.Updatetime = realvalue.Updatetime; + + try + { + if (realData.Standarparamid > 0) + { + var standarParam = standarParams.FirstOrDefault(t => t.Id == realData.Standarparamid); + + if (standarParam != null) + { + if (standarParam.Uniquepronoun.Equals("CStartTime") || standarParam.Uniquepronoun.Equals("CEndTime") || standarParam.Uniquepronoun.Equals("CPayTime")) + { + DateTime unixEpoch = new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Utc); + DateTime dateTime = unixEpoch.AddSeconds(long.Parse(realData.Realvalue)); + realData.Realvalue = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {3};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); + } + } + } + + //var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); + //if (virtualRealDatas.Count() > 0) + //{ + // var virtualItems = await CalculationVirtualParametersV02(virtualRealDatas, realvaluelist); + // foreach (var virtualItem in virtualItems) + // { + // var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); + // if (l != null) + // { + // l.Realvalue = virtualItem.Realvalue; + // l.Updatetime = virtualItem.Updatetime; + // } + // } + //} + + return await Task.FromResult(list); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); + return null; + } + } + public async Task> GetRealValueFromDBMaxMin(QueryRealDataTimeZonesMaxMinModel input, List realDatas = null) + { + var result = new List { }; + try + { + if (input.RealIds == null || input.RealIds.Count() == 0) + { + return new List { }; + } + if (realDatas == null || realDatas.Count() == 0) + { + realDatas = await _localData.GetTbRealDatas(input.ProjectId, input.RealIds); + } + foreach (var realData in realDatas) + { + try + { + var realParamJson = JsonConvert.DeserializeObject(realData.JsonContent); + if (realData.PointType == 2) + { + foreach (var point in realParamJson.CombinedPoint) + { + if (point.Key > 0) + { + input.RealIds.Add((long)point.Key); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + } + + var items = await GetRealDataTimeZonesMaxMin(new QueryRealDataTimeZonesMaxMinModel + { + ProjectId = input.ProjectId, + StartTime = input.StartTime, + EndTime = input.EndTime, + RealIds = input.RealIds + }); + foreach (var realData in realDatas) + { + var item = items.FirstOrDefault(t => t.RealId == realData.Id); + if (item != null) + { + result.Add(item); + } + } + var virtualRealDatas = realDatas.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); + if (virtualRealDatas.Count() > 0) + { + var virtualItems = await CalculationVirtualParametersTimeZonesMaxMin(items, virtualRealDatas); + if (virtualItems.Count() > 0) + { + result.AddRange(virtualItems); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return result; + } + + private async Task> GetRealDataTimeZonesMaxMin(QueryRealDataTimeZonesMaxMinModel input) + { + var items = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var userDbContext = scope.ServiceProvider.GetRequiredService(); + var projectInfo = userDbContext.ProjectInfo.Where(t => t.Id == input.ProjectId).Select(t => new + { + t.Id, + t.Dbstr + }).FirstOrDefault(); + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + items = __contextDB.DsPointHistory.Where(t => input.RealIds.Contains(t.Id) && t.CreateTime >= input.StartTime && t.CreateTime < input.EndTime).GroupBy(g => g.Id).Select(t => new RealDataTimeZonesMaxMinModel + { + RealId = t.Key, + Max = t.Max(m => m.Value ?? 0), + Min = t.Min(m => m.Value ?? 0) + }).ToList(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealDataTimeZonesMaxMin", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + private async Task> GetRealDataTimeZones(QueryRealDataTimeZonesMaxMinModel input) + { + var items = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var userDbContext = scope.ServiceProvider.GetRequiredService(); + var projectInfo = userDbContext.ProjectInfo.Where(t => t.Id == input.ProjectId).Select(t => new + { + t.Id, + t.Dbstr + }).FirstOrDefault(); + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + var pointsHistory = __contextDB.DsPointHistory.Where(t => input.RealIds.Contains(t.Id) && t.CreateTime >= input.StartTime && t.CreateTime < input.EndTime).Select(t => new + { + t.Id, + t.Value, + t.CreateTime + }).OrderBy(t => t.CreateTime).ToList(); + foreach (var point in pointsHistory) + { + var item = items.FirstOrDefault(); + if (item == null) + { + item = new RealDataTimeZonesModel + { + RealId = point.Id, + Items = new List { } + }; + items.Add(item); + } + item.Items.Add(new RealDataTimeZonesItemModel + { + Time = point.CreateTime, + Value = point.Value.GetValueOrDefault() + }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealDataTimeZonesMaxMin", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + private async Task> CalculationVirtualParametersTimeZonesMaxMin(List items, List tbRealDatas) + { + var result = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + + Dictionary dicParamsEquipIds = new Dictionary { }; + + foreach (var tbRealData in tbRealDatas) + { + try + { + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); + var maxFormula = tbRealData.Virtualformula; + var minFormula = tbRealData.Virtualformula; + foreach (var formulaParam in formulaParams) + { + var _param = formulaParam.Split("=").ToList(); + dicParamsEquipIds.TryAdd(_param[0], long.Parse(_param[1])); + } + var pointIds = dicParamsEquipIds.Select(t => t.Value).Distinct().ToList(); + var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); + + foreach (var dicParamEquipId in dicParamsEquipIds) + { + if (!tbRealData.Virtualformula.Contains($"{dicParamEquipId.Key}")) + { + continue; + } + if (dicParamEquipId.Value == 0) + { + continue; + } + var _tbRealData = items.FirstOrDefault(t => t.RealId == dicParamEquipId.Value); + if (_tbRealData != null) + { + maxFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Max.ToString()); + minFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Min.ToString()); + } + else + { + minFormula = maxFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", "0"); + } + } + try + { + tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); + result.Add(new RealDataTimeZonesMaxMinModel + { + RealId = tbRealData.Id, + Max = FormulaUtil.InterperterFormula(maxFormula), + Min = FormulaUtil.InterperterFormula(minFormula) + }); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters1", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1} {2}", ex.Message, tbRealData.Transarray, ex.StackTrace)).GetNlogMessage()); + } + dicParamsEquipIds.Clear(); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return result; + } + /// + /// 参数是点 + /// + /// + /// + /// + private async Task> CalculationVirtualParametersV02(List tbRealDatas, List realDatas) + { + try + { + using var scope = _serviceScopeFactory.CreateScope(); + + Dictionary dicParamsEquipIds = new Dictionary { }; + + foreach (var tbRealData in tbRealDatas) + { + try + { + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula) || string.IsNullOrEmpty(tbRealData.Virtualformulaparam)) + { + continue; + } + var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); + foreach (var formulaParam in formulaParams) + { + var _param = formulaParam.Split("=").ToList(); + if (_param.Count() >= 2) + { + dicParamsEquipIds.TryAdd(_param[0], long.Parse(_param[1])); + } + } + var pointIds = dicParamsEquipIds.Select(t => t.Value).Distinct().ToList(); + var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); + + foreach (var dicParamEquipId in dicParamsEquipIds) + { + if (!tbRealData.Virtualformula.Contains($"{dicParamEquipId.Key}")) + { + continue; + } + if (dicParamEquipId.Value == 0) + { + continue; + } + var _tbRealData = realDatas.Where(t => t != null).FirstOrDefault(t => t.Id == dicParamEquipId.Value); + if (_tbRealData != null) + { + if ((tbRealData.Updatetime == null && _tbRealData.Updatetime != null) + || (tbRealData.Updatetime != null && _tbRealData.Updatetime != null && _tbRealData.Updatetime.GetValueOrDefault() < tbRealData.Updatetime.GetValueOrDefault())) + { + tbRealData.Updatetime = _tbRealData.Updatetime; + } + tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Realvalue); + } + else + { + tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", "0"); + } + } + try + { + tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0};{1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + dicParamsEquipIds.Clear(); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return tbRealDatas; + } + + /// + /// 获得项目下所有的实时参数 + /// + /// + /// + /// + public async Task> GetRealValueByProAndKey(long? projectid, string[] paramIds) + { + List list = new List(); + //string[] arr = new string[] { }; + try + { + if (paramIds == null || paramIds.Count() == 0) + { + return new List { }; + } + var realIds = paramIds.StrArrayToLongArray(); + var templist1 = await _localData.GetTbRealDatas(projectid ?? 0, realIds); + //templist1 = templist1.Where(t => realIds.Contains(t.Id)).ToList(); + //var templist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); + if (templist1 == null) + { + templist1 = new List { }; + } + var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), paramIds, 1, 1).Select(d => d.Value).Where(d => d != null && d.Id > 0).ToList(); + if (realvaluelist == null || realvaluelist.Count == 0) + { + return templist1; + } + var isRefresh = await _localData.CheckProIdIsRefresh(projectid ?? 0, realIds, realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); + if (isRefresh) + { + //var realDatas = await _localData.GetTbRealDatas(projectid ?? 0); + //templist1 = realDatas.Where(d => realIds.Contains(d.Id)).ToList(); + templist1 = await _localData.GetTbRealDatas(projectid ?? 0, realIds); + } + + list = (from tre in templist1 + join r in realvaluelist on tre.Id equals r.Id + select new TbRealData + { + Id = tre.Id, + Datafmtdesc = tre.Datafmtdesc, + Isalarm = tre.Isalarm, + Datalength = tre.Datalength, + Descname = tre.Descname, + Aitype = tre.Aitype, + Controllsort = tre.Controllsort, + Equid = tre.Equid, + Hi = tre.Hi, + Hihi = tre.Hihi, + Isvoice = tre.Isvoice, + Lo = tre.Lo, + Lolo = tre.Lolo, + Onemean = tre.Onemean, + Paramean = tre.Paramean, + Plcid = tre.Plcid, + Projectid = tre.Projectid, + Realvalue = r.Realvalue, + Setname = tre.Setname, + Updatetime = r.Updatetime, + Standarparamid = tre.Standarparamid, + Startbyte = tre.Startbyte, + Tagname = tre.Tagname, + Transarray = tre.Transarray, + Unit = tre.Unit, + Valuesort = tre.Valuesort, + Valuetype = tre.Valuetype, + Zeromean = tre.Zeromean, + Virtualformula = tre.Virtualformula, + Virtualformulaparam = tre.Virtualformulaparam + }).ToList(); + var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); + if (virtualRealDatas.Count() > 0) + { + var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid.GetValueOrDefault()); + foreach (var virtualItem in virtualItems) + { + var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); + if (l != null) + { + l.Realvalue = virtualItem.Realvalue; + l.Updatetime = virtualItem.Updatetime; + } + } + } + return await Task.FromResult(list); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + return null; + } + } + + /// + /// 批量保存和编辑实时表数据 + /// + /// + /// + public async Task PutRealDatas(List tbRealDatas) + { + if (tbRealDatas == null || tbRealDatas.Count == 0) + { + return 0; + } + try + { + //_context.TbRealData.UpdateRange(tbRealDatas); + foreach (var item in tbRealDatas) + { + var entity = await (from ur in _weiCloudDBContext.TbRealData where ur.Projectid == item.Projectid && ur.Id == item.Id select ur).FirstOrDefaultAsync(); + if (entity != null) + { + + entity.Equid = item.Equid; + entity.Isalarm = item.Isalarm; + entity.Isvoice = item.Isvoice; + entity.Aitype = item.Aitype; + entity.Controllsort = item.Controllsort; + entity.Datafmtdesc = item.Datafmtdesc; + entity.Datalength = item.Datalength; + entity.Descname = item.Descname; + entity.Hi = item.Hi; + entity.Hihi = item.Hihi; + entity.Lo = item.Lo; + entity.Lolo = item.Lolo; + entity.Onemean = item.Onemean; + entity.Zeromean = item.Zeromean; + entity.Plcid = item.Plcid; + entity.Projectid = item.Projectid; + entity.Setname = item.Setname; + entity.Standarparamid = item.Standarparamid; + entity.Startbyte = item.Startbyte; + entity.Tagname = item.Tagname; + entity.Transarray = item.Transarray; + entity.Unit = item.Unit; + entity.Valuesort = item.Valuesort; + entity.Valuetype = item.Valuetype; + entity.Realvalue = item.Realvalue; + entity.Updatetime = item.Updatetime; + + _weiCloudDBContext.Update(entity); + } + else + { + entity = new TbRealData() + { + + Id = UidGenerator.Uid(), + + Equid = item.Equid, + Isalarm = item.Isalarm, + Isvoice = item.Isvoice, + Aitype = item.Aitype, + Controllsort = item.Controllsort, + Datafmtdesc = item.Datafmtdesc, + Datalength = item.Datalength, + Descname = item.Descname, + Hi = item.Hi, + Hihi = item.Hihi, + Lo = item.Lo, + Lolo = item.Lolo, + Onemean = item.Onemean, + Zeromean = item.Zeromean, + Plcid = item.Plcid, + Projectid = item.Projectid, + Setname = item.Setname, + Standarparamid = item.Standarparamid, + Startbyte = item.Startbyte, + Tagname = item.Tagname, + Transarray = item.Transarray, + Unit = item.Unit, + Valuesort = item.Valuesort, + Valuetype = item.Valuetype, + Realvalue = item.Realvalue, + Updatetime = item.Updatetime, + }; + _weiCloudDBContext.Add(entity); + } + } + + var n = await _weiCloudDBContext.SaveChangesAsync(); + if (n > 0) + { + var projectId = tbRealDatas.Select(d => d.Projectid).FirstOrDefault(); + var result1 = await UpdateRealValueToRedisByPro(projectId, tbRealDatas); + } + return n; + + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "PutRealDatas", ex.Message)).GetNlogMessage()); + return -1; + } + } + + public async Task> ModifyRealData(TbRealData tbRealData) + { + var result1 = 0; + try + { + bool isRateChanged = false; + string lastRateStr = string.Empty; + string nowRateStr = string.Empty; + var realvalue = await (from rv in _weiCloudDBContext.TbRealData where rv.Projectid == tbRealData.Projectid && rv.Id == tbRealData.Id select rv).FirstOrDefaultAsync(); + if (realvalue == null) + { + realvalue = new TbRealData() + { + Id = UidGenerator.Uid(), + + Projectid = tbRealData.Projectid, + Descname = tbRealData.Descname, + Tagname = tbRealData.Tagname, + Aitype = tbRealData.Aitype, + Unit = tbRealData.Unit, + Realvalue = tbRealData.Realvalue, + Hihi = tbRealData.Hihi, + Hi = tbRealData.Hi, + Lolo = tbRealData.Lolo, + Lo = tbRealData.Lo, + Isalarm = tbRealData.Isalarm, + Isvoice = tbRealData.Isvoice, + Valuetype = tbRealData.Valuetype, + Startbyte = tbRealData.Startbyte, + Datalength = tbRealData.Datalength, + Zeromean = tbRealData.Zeromean, + Onemean = tbRealData.Onemean, + Valuesort = tbRealData.Valuesort, + Equid = tbRealData.Equid, + Controllsort = tbRealData.Controllsort, + Transarray = 1, + Datafmtdesc = tbRealData.Datafmtdesc, + Plcid = tbRealData.Plcid, + Setname = tbRealData.Setname, + Standarparamid = tbRealData.Standarparamid, + Paramean = tbRealData.Paramean, + + }; + await _weiCloudDBContext.AddAsync(realvalue); + } + else + { + if (!string.IsNullOrEmpty(realvalue.Datafmtdesc) && !realvalue.Datafmtdesc.Equals(tbRealData.Datafmtdesc, StringComparison.OrdinalIgnoreCase)) + { + isRateChanged = true; + lastRateStr = realvalue.Datafmtdesc; + nowRateStr = tbRealData.Datafmtdesc; + } + + realvalue.Projectid = tbRealData.Projectid; + realvalue.Descname = tbRealData.Descname; + realvalue.Tagname = tbRealData.Tagname; + realvalue.Aitype = tbRealData.Aitype; + realvalue.Unit = tbRealData.Unit; + realvalue.Realvalue = tbRealData.Realvalue; + realvalue.Hihi = tbRealData.Hihi; + realvalue.Hi = tbRealData.Hi; + realvalue.Lolo = tbRealData.Lolo; + realvalue.Lo = tbRealData.Lo; + realvalue.Isalarm = tbRealData.Isalarm; + realvalue.Isvoice = tbRealData.Isvoice; + realvalue.Valuetype = tbRealData.Valuetype; + realvalue.Startbyte = tbRealData.Startbyte; + realvalue.Datalength = tbRealData.Datalength; + realvalue.Zeromean = tbRealData.Zeromean; + realvalue.Onemean = tbRealData.Onemean; + realvalue.Valuesort = tbRealData.Valuesort; + realvalue.Equid = tbRealData.Equid; + realvalue.Controllsort = tbRealData.Controllsort; + realvalue.Transarray = 1; + realvalue.Datafmtdesc = tbRealData.Datafmtdesc; + realvalue.Plcid = tbRealData.Plcid; + realvalue.Setname = tbRealData.Setname; + realvalue.Standarparamid = tbRealData.Standarparamid; + realvalue.Paramean = tbRealData.Paramean; + _weiCloudDBContext.Update(realvalue); + } + _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", Newtonsoft.Json.JsonConvert.SerializeObject(tbRealData), Newtonsoft.Json.JsonConvert.SerializeObject(realvalue))).GetNlogMessage()); + var res = await _weiCloudDBContext.SaveChangesAsync(); + if (res > 0) + { + if (isRateChanged) + { + var expireSeconds = (int)DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")).AddDays(1).Subtract(DateTime.Now).TotalSeconds; + _stringService.Set("EquipRateChanged" + tbRealData.Equid.ToString(), DateTime.Now, expireSeconds, 2); + try + { + decimal lastRate = 1; + decimal nowRate = 1; + if (!string.IsNullOrEmpty(lastRateStr)) + { + //var str = Regex.Replace(lastRateStr, @"[^\d.\d]", ""); + //if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) + //{ + // lastRate = decimal.Parse(str); + //} + var formula = lastRateStr.Replace('X', '1'); + lastRate = FormulaUtil.InterperterFormula(formula); + } + + if (!string.IsNullOrEmpty(nowRateStr)) + { + //var str = Regex.Replace(nowRateStr, @"[^\d.\d]", ""); + //if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) + //{ + // nowRate = decimal.Parse(str); + //} + var formula = nowRateStr.Replace('X', '1'); + nowRate = FormulaUtil.InterperterFormula(formula); + } + if (lastRate - nowRate != 0) + { + //var takeDataService = GrainFactory.GetGrain(CurrentContext.GetContext().UserId); + //await takeDataService.ChangedRateModifyHistoryData(lastRate, nowRate, (long)tbRealData.Equid, DateTime.Now); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "ChangedRateModifyHistoryData", ex.Message)).GetNlogMessage()); + } + } + //await DeleteRealValueToRedisByPro(tbRealData.Projectid, tbRealData); + result1 = await UpdateRealValueToRedisByPro(tbRealData.Projectid, realvalue); + if (result1 > 0) + { + return new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = result1 }; + } + else + { + return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = string.Format("数据库保存成功,Redis保存失败,请查看是否存在Pro{0}", tbRealData.Projectid) }; + } + } + else + { + return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "数据库保存失败" }; + } + + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "ModifyRealData", ex.Message)).GetNlogMessage()); + return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = ex.Message }; + } + } + /// + /// 参数计算 + /// + /// + /// + /// + /// + private async Task CalculationVirtualParameters(List equipIds, string uniqueCode, long projectId) + {//"NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" + var value = 0D; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var airDBConext = scope.ServiceProvider.GetRequiredService(); + var timeQuery = airDBConext.Times.AsQueryable(); + var nowTime = DateTime.Now; + if (uniqueCode == "NowHourEP") + {//电耗 + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + } + else if (uniqueCode == "NowMonthEP") + {//电耗 + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + } + else if (uniqueCode == "NowDayEP") + {//电耗 + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + } + else if (uniqueCode == "NowHourHE") + { + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + } + else if (uniqueCode == "NowMonthHE") + { + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + } + else if (uniqueCode == "NowDayHE") + { + var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return value; + } + private short GetTimeUnit(string uniqueCode) + { + var timeUnit = (short)QueryTimeTypeEnum.Hour; + if (uniqueCode == "NowHourEP") + { + + } + else if (uniqueCode == "NowMonthEP") + { + timeUnit = (short)QueryTimeTypeEnum.Day; + } + else if (uniqueCode == "NowDayEP") + { + timeUnit = (short)QueryTimeTypeEnum.Hour; + } + else if (uniqueCode == "NowHourHE") + { + + } + else if (uniqueCode == "NowMonthHE") + { + timeUnit = (short)QueryTimeTypeEnum.Day; + } + else if (uniqueCode == "NowDayHE") + { + timeUnit = (short)QueryTimeTypeEnum.Hour; + } + return timeUnit; + } + private async Task> CalculationVirtualParameters(List equipIds, string uniqueCode, long projectId, short timeUnit, DateTime? queryStartTime, DateTime? queryEndTime) + {//"NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" + var valueItems = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var airDBConext = scope.ServiceProvider.GetRequiredService(); + //var nowTimeHour = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:00:00")); + //var timeQuery = airDBConext.Times.Where(t => t.Fulldatetime < nowTimeHour).AsQueryable(); + var timeQuery = airDBConext.Times.AsQueryable(); + List dws = null; + //var nowTime = DateTime.Now; + var nowTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:00:00")); + if (queryEndTime.HasValue && queryEndTime.GetValueOrDefault() < nowTime) + { + nowTime = queryEndTime.GetValueOrDefault(); + } + var startTime = nowTime; + if (uniqueCode == "NowHourEP") + {//电耗 + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); + } + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.AmParm003 + }).ToListAsync(); + } + else if (uniqueCode == "NowMonthEP") + {//电耗 + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + } + //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.AmParm003 + }).ToListAsync(); + } + else if (uniqueCode == "NowDayEP") + {//电耗 + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + } + //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); + dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.AmParm003 + }).ToListAsync(); + } + else if (uniqueCode == "NowHourHE") + { + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); + } + //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.HmParm001 + }).ToListAsync(); + } + else if (uniqueCode == "NowMonthHE") + { + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + } + //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.HmParm001 + }).ToListAsync(); + } + else if (uniqueCode == "NowDayHE") + { + if (queryStartTime.HasValue) + { + startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); + } + else + { + startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + } + //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); + var timeIds = timeQuery.Select(t => t.Id).ToList(); + //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); + dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel + { + EquipId = t.Parm002, + TimeId = t.Parm001, + Value = t.HmParm001 + }).ToListAsync(); + } + var times = await timeQuery.ToListAsync(); + List> timeGroups = null; + if (timeUnit <= 0) + { + timeUnit = GetTimeUnit(uniqueCode); + } + if (timeUnit == (short)QueryTimeTypeEnum.Hour) + {//小时 + timeGroups = times.GroupBy(t => new + { + t.Year, + t.Month, + t.Day, + t.Hour + }).Select(t => t.ToList()).ToList(); + } + else if (timeUnit == (short)QueryTimeTypeEnum.Day) + { + timeGroups = times.GroupBy(t => new + { + t.Year, + t.Month, + t.Day + }).Select(t => t.ToList()).ToList(); + } + if (timeGroups != null) + { + foreach (var timeGroup in timeGroups) + { + var _timeIds = timeGroup.Select(t => t.Id).ToList(); + var _value = dws.Where(t => _timeIds.Contains(t.TimeId)).Sum(s => s.Value); + var _time = timeGroup.FirstOrDefault().Fulldatetime; + if (_time == null) + { + continue; + } + valueItems.Add(new TimeDBItemValueModel + { + Time = _time.GetValueOrDefault(), + Value = _value + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return valueItems; + } + private async Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds) + { + var valueItems = new List { }; + + return valueItems; + } + public async Task> QueryEquipRealDataDoc(long projectId, List equipIds, List paramCodes) + { + var resultItems = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var userCenter = scope.ServiceProvider.GetRequiredService(); + var standarParams = await userCenter.StandarParam.Where(t => t.Uniquepronoun != null && paramCodes.Contains(t.Uniquepronoun)).AsNoTracking().Select(t => new + { + t.Id, + t.Uniquepronoun + }).ToListAsync(); + var standarParamIds = standarParams.Select(t => t.Id).ToList(); + var templist = await _localData.GetTbRealDatas(projectId); + var realIds = templist.Where(t => t.Equid != null && equipIds.Contains((long)t.Equid) && t.Standarparamid != null && standarParamIds.Contains((long)t.Standarparamid)).Select(t => t.Id.ToString()).Distinct().ToArray(); + var realDatas = await GetRealValueByProAndKey(projectId, realIds); + foreach (var realData in realDatas) + { + var equipRealDatas = resultItems.FirstOrDefault(t => t.EquipId == realData.Equid); + if (equipRealDatas == null) + { + equipRealDatas = new EquipParamRealDataModel + { + EquipId = realData.Equid.GetValueOrDefault(), + Params = new Dictionary { } + }; + resultItems.Add(equipRealDatas); + } + var standarParam = standarParams.FirstOrDefault(t => t.Id == realData.Standarparamid); + double value = 0; + double.TryParse(realData.Realvalue, out value); + equipRealDatas.Params.Add(standarParam.Uniquepronoun, value); + equipRealDatas.UpdateTime = realData.Updatetime.GetValueOrDefault(); + equipRealDatas.CreateTime = realData.Updatetime.GetValueOrDefault(); + } + var realIdStrs = templist.Select(t => t.Id.ToString()).ToArray(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return resultItems; + } + /// + /// 获取虚拟参数 + /// + /// + /// + /// + private async Task> CalculationVirtualParameters(List tbRealDatasOrg, long projectId) + { + //HourEP:小时电能耗、HourHE:小时热能耗 + //DayEP:日电能耗、DayHE:日热能耗 + //MonthEP:月电能耗、MonthHE:月热能耗 + var tbRealDatas = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(tbRealDatasOrg)); + try + { + using var scope = _serviceScopeFactory.CreateScope(); + var timeSeqService = scope.ServiceProvider.GetRequiredService(); + //var equipIds = new List { }; + + Dictionary> dicParamsEquipIds = new Dictionary> { }; + + foreach (var tbRealData in tbRealDatas) + { + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); + foreach (var formulaParam in formulaParams) + { + var _param = formulaParam.Split("=").ToList(); + dicParamsEquipIds.Add(_param[0], _param[1].Split(",").StrArrayToLongArray()); + } + var equipIds = dicParamsEquipIds.SelectMany(t => t.Value).Distinct().ToList(); + var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); + //foreach (var dicParamEquipIds in dicParamsEquipIds) + //{ + // var dicParamEquipParams = dicParamEquipIds.Key.Split("$"); + // if (virtualParameterUniqueCodes.Any(t => t == dicParamEquipParams[0])) + // {//自定义标签 + // var r = await CalculationVirtualParameters(dicParamEquipIds.Value, dicParamEquipParams[0], projectId); + // //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipIds.Key}`", r.ToString()); + // var formulaParam = $"`{dicParamEquipParams[0]}"; + // if (dicParamEquipParams.Length > 1) + // { + // formulaParam += $"${dicParamEquipParams[1]}"; + // } + // formulaParam += "`"; + // tbRealData.Virtualformula = tbRealData.Virtualformula.Replace(formulaParam, r.ToString()); + // } + // else + // { + // //原始 + // equipIds.AddRange(dicParamEquipIds.Value); + // } + //} + if (equipIds.Count() > 0) + { + var documents = await QueryEquipRealDataDoc(projectId, equipIds.Distinct().ToList(), paramCodes); + //var documents = await timeSeqService.QueryEquipRealDataDoc(DateTime.Now, projectId, equipIds.Distinct().ToList()); + if (documents.Count() > 0) + { + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + try + { + foreach (var dicParamEquipId in dicParamsEquipIds) + { + if (!tbRealData.Virtualformula.Contains($"`{dicParamEquipId.Key}`")) + { + continue; + } + if (dicParamEquipId.Value == null || dicParamEquipId.Value.Count() == 0) + { + continue; + } + //只支持一个设备 + var _document = documents.FirstOrDefault(t => dicParamEquipId.Value.Contains(t.EquipId)); + if (_document.Params == null || !_document.Params.ContainsKey(dicParamEquipId.Key.Split("$")[0])) + { + tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipId.Key}`", "0"); + } + else + { + tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipId.Key}`", _document.Params[dicParamEquipId.Key.Split("$")[0]].ToString()); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1};{2}", ex.Message, ex.StackTrace, tbRealData.Transarray)).GetNlogMessage()); + } + } + } + equipIds.Clear(); + dicParamsEquipIds.Clear(); + } + + + + foreach (var tbRealData in tbRealDatas) + { + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + try + { + tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters1", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); + } + return tbRealDatas; + } + + /// + /// 计算虚拟参数历史值 + /// + /// + /// + /// + /// + /// + /// + public async Task> CalculationHisotryVirtualParameters(List tbRealDatasOrg, DateTime? startTime, DateTime? endTime, long projectId, short timeUnit = (short)QueryTimeTypeEnum.Hour) + { + //HourEP:小时电能耗、HourHE:小时热能耗 + //DayEP:日电能耗、DayHE:日热能耗 + //MonthEP:月电能耗、MonthHE:月热能耗 + var tbRealDatas = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(tbRealDatasOrg)); + var calHisVirDatas = new List { }; + try + { + using var scope = _serviceScopeFactory.CreateScope(); + //var timeSeqService = scope.ServiceProvider.GetRequiredService(); + var equipIds = new List { }; + + Dictionary> dicParamsEquipIds = new Dictionary> { }; + + var userCenterContext = scope.ServiceProvider.GetRequiredService(); + var standarParams = await userCenterContext.StandarParam.AsNoTracking().Select(t => new + { + t.Id, + t.Uniquepronoun + }).ToListAsync(); + + foreach (var tbRealData in tbRealDatas) + { + var calHisVirData = new RealTimeDBItemValueModel + { + RealId = tbRealData.Id, + Items = new List { } + }; + calHisVirDatas.Add(calHisVirData); + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); + foreach (var formulaParam in formulaParams) + { + var _param = formulaParam.Split("=").ToList(); + dicParamsEquipIds.Add(_param[0], _param[1].Split(",").StrArrayToLongArray()); + } + foreach (var dicParamEquipIds in dicParamsEquipIds) + { + var dicParamEquipParams = dicParamEquipIds.Key.Split("$"); + if (virtualParameterUniqueCodes.Any(t => t == dicParamEquipParams[0])) + {//自定义标签 + var valueItems = await CalculationVirtualParameters(dicParamEquipIds.Value, dicParamEquipParams[0], projectId, timeUnit, startTime, endTime); + if (valueItems != null) + { + foreach (var valueItem in valueItems) + { + TimeDBItemValueModel _valueItem = calHisVirData.Items.FirstOrDefault(t => t.Time == valueItem.Time); + if (_valueItem == null) + { + _valueItem = valueItem; + calHisVirData.Items.Add(_valueItem); + } + if (string.IsNullOrEmpty(_valueItem.Virtualformula)) + { + _valueItem.Virtualformula = tbRealData.Virtualformula; + } + var formulaParam = $"`{dicParamEquipParams[0]}"; + if (dicParamEquipParams.Length > 1) + { + formulaParam += $"${dicParamEquipParams[1]}"; + } + formulaParam += "`"; + _valueItem.Virtualformula = _valueItem.Virtualformula.Replace(formulaParam, valueItem.Value.GetValueOrDefault().ToString()); + } + } + //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipIds.Key}`", r.ToString()); + //var formulaParam = $"`{dicParamEquipParams[0]}"; + //if (dicParamEquipParams.Length > 1) + //{ + // formulaParam += $"${dicParamEquipParams[1]}"; + //} + //formulaParam += "`"; + //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace(formulaParam, r.ToString()); + } + else + { + //原始 + equipIds.AddRange(dicParamEquipIds.Value); + } + } + if (equipIds.Count() > 0) + {//瞬时值 + if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) + { + continue; + } + //var valueItems = await QueryEquipIntervalRealDataDoc(startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), projectId, equipIds.Distinct().ToList()); + //var documents = await _timeSeqService.QueryEquipRealDataDoc(DateTime.Now, projectId, equipIds.Distinct().ToList()); + //var documents = await _timeSeqService.QueryEquipIntervalRealDataDoc(startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), projectId, equipIds); + var equipReals = await _weiCloudDBContext.TbRealData.Where(t => t.Projectid == projectId && t.Equid != null && equipIds.Contains((long)t.Equid)).AsNoTracking().Select(t => new + { + t.Id, + t.Equid, + t.Standarparamid + }).ToListAsync(); + var equipRealIds = equipReals.Select(t => t.Id).ToList(); + var dataSourceV03Service = scope.ServiceProvider.GetRequiredService(); + var realDataItems = await dataSourceV03Service.GetHistorys(projectId, startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), equipRealIds); + if (realDataItems.Count() > 0) + { + try + { + var times = realDataItems.Select(t => t.CreateTime).Distinct().ToList(); + foreach (var time in times) + { + var _valueItem = new TimeDBItemValueModel { Time = time, Virtualformula = tbRealData.Virtualformula }; + calHisVirData.Items.Add(_valueItem); + foreach (var dicParamEquipId in dicParamsEquipIds) + { + if (!tbRealData.Virtualformula.Contains($"`{dicParamEquipId.Key}`")) + { + continue; + } + if (dicParamEquipId.Value == null || dicParamEquipId.Value.Count() == 0) + { + continue; + } + //只支持一个设备 + + var standerCode = dicParamEquipId.Key.Split("$")[0]; + var standarParam = standarParams.FirstOrDefault(t => t.Uniquepronoun == standerCode); + if (standarParam == null) + { + continue; + } + var _equipReal = equipReals.FirstOrDefault(t => dicParamEquipId.Value.Contains((long)t.Equid) && t.Standarparamid == standarParam.Id); + + var _realDataItem = realDataItems.Where(t => _equipReal.Id == t.Id && t.CreateTime >= time.AddMinutes(-15) && t.CreateTime <= time).LastOrDefault(); + if (_realDataItem != null) + { + _valueItem.Virtualformula = _valueItem.Virtualformula.Replace($"`{dicParamEquipId.Key}`", _realDataItem.Value.ToString()); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1};{2}", ex.Message, ex.StackTrace, tbRealData.Transarray)).GetNlogMessage()); + } + } + } + equipIds.Clear(); + dicParamsEquipIds.Clear(); + } + + + + foreach (var calHisVirData in calHisVirDatas) + { + if (calHisVirData.Items == null) + { + continue; + } + var failValueItems = new List { }; + foreach (var item in calHisVirData.Items) + { + if (string.IsNullOrWhiteSpace(item.Virtualformula)) + { + continue; + } + try + { + //item.Value = FormulaUtil.InterperterFormula(item.Virtualformula); + double _itemValue = 0; + var _itemValueResult = FormulaUtil.InterperterFormula(item.Virtualformula, ref _itemValue); + if (!_itemValueResult) + {//转换失败 + failValueItems.Add(item); + } + else + { + item.Value = _itemValue; + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationHisotryVirtualParameters1", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + } + if (failValueItems.Count() > 0) + { + calHisVirData.Items.RemoveAll(t => + { + return failValueItems.Any(f => t.Time == f.Time); + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationHisotryVirtualParameters", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return calHisVirDatas; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs new file mode 100644 index 0000000..15209f3 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs @@ -0,0 +1,110 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class RealDataAnalyzeCoreService: IRealDataAnalyzeCoreService + { + private readonly ILogger _logger; + private readonly IDictionaryService _dictionaryService; + private readonly WeiCloudDBContext _weiCloudDBContext; + private int INTERVAL = 60 * 10; //采集间隔 s + + public RealDataAnalyzeCoreService(ILogger logger, IDictionaryService dictionaryService, WeiCloudDBContext weiCloudDBContext) + { + _logger = logger; + _dictionaryService = dictionaryService; + _weiCloudDBContext = weiCloudDBContext; + } + /// + /// 根据设备id查询项目id + /// + /// + /// + private long? GetProjectIdByEquid(long? equid) + { + var equ = _dictionaryService.GetValue("EquipmentInfo", new string[] { equid.ToString() }).FirstOrDefault(); + var projectid = equ.Value.Projectid; + return projectid; + } + public class EquipStatus + { + /// + /// 设备上一个状态 + /// + public short? LastStatus { get; set; } + /// + /// 设备当前状态 + /// + public short? CurrentStatus { get; set; } + } + /// + /// 根据设备id 获取设备的运行状态 + /// + /// 设备ids + /// + public async Task>> GetEquCommStatusAsync(List equids) + { + var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "获取成功" }; + List equCommStatus = new List(); + try + { + long? projectId = 0; + foreach (var equid in equids) + {//存在redis和数据库数据不一致问题 + try + { + projectId = GetProjectIdByEquid(equid); + } + catch (Exception) + { + + } + if (projectId != null && projectId > 0) + { + break; + } + } + var temp = _dictionaryService.GetValue("EquipStatusPro_" + projectId.ToString()); + foreach (var item in equids) + { + if (!temp.ContainsKey(item.ToString())) //检测如果不存在则添加 + { + equCommStatus.Add(new EquCommStatus + { + EquId = item, + CurrentStatus = 3 + }); + + } + else + { + equCommStatus.Add(new EquCommStatus + { + EquId = item, + CurrentStatus = temp[item.ToString()].CurrentStatus + }); + } + } + result.Data = equCommStatus; + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEquCommStatusAsync", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); + result.Data = equCommStatus; + result.Code = RequestBackStatuEnum.fail.Value; + result.Msg = ex.Message; + } + return await Task.FromResult(result); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs new file mode 100644 index 0000000..6339345 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs @@ -0,0 +1,284 @@ +using AutoMapper; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.RealData; +using WeiCloud.Core.Report; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.DataSource; + +namespace WeiCloud.Core.Services.Report +{ + public class DataSourceCoreService : IDataSourceCoreService + { + private readonly WeiCloudDBDataSourceContext _dataSourceContext; + private readonly WeiCloudDBContext _context; + private readonly IDictionaryService _dictionaryService; + private readonly ILogger _logger; + private readonly IRealDataCoreService _realDataCoreService; + private readonly IRealDataAnalyzeCoreService _realDataAnalyzeCoreService; + private readonly IMapper _mapper; + public DataSourceCoreService(WeiCloudDBContext context, IRealDataAnalyzeCoreService realDataAnalyzeCoreService, IMapper mapper, WeiCloudDBDataSourceContext dataSourceContext, IDictionaryService dictionaryService, ILogger logger, IRealDataCoreService realDataCoreService) + { + _context = context; + _dataSourceContext = dataSourceContext; + _dictionaryService = dictionaryService; + _logger = logger; + _realDataCoreService = realDataCoreService; + _mapper = mapper; + _realDataAnalyzeCoreService = realDataAnalyzeCoreService; + } + /// + /// 获取配置值 + /// + /// + /// + public async Task GetDataSource(long dataSourceId) + { + var result = new DataSourceModel + { + Items = new List + { + + } + }; + try + { + var dataSource = _dataSourceContext.DtDataSource.AsNoTracking().TagWith("SubDB").FirstOrDefault(t => t.Id == dataSourceId); + var dataSouceMaps = await _dataSourceContext.DtDataSouceMap.Where(t => t.DataSourceId == dataSourceId).AsNoTracking().TagWith("SubDB").ToListAsync(); + result.Title = dataSource.Title; + result.ProjectId = dataSource.ProjectId; + var dataSouceMap1s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); + var realIds = dataSouceMap1s.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); + var dataSouceMapModels = new List(); + if (realIds != null && realIds.Count() > 0) + { + var realDatas = await _realDataCoreService.GetRealValueFromRedisByPro(dataSource.ProjectId); + foreach (var dataSouceMap1 in dataSouceMap1s) + { + var realData = realDatas.FirstOrDefault(t => t.Id == dataSouceMap1.SourceId); + if (realData == null) + { + continue; + } + var dataSouceMapItem = _mapper.Map(dataSouceMap1); + var value = 0d; + double.TryParse(realData.Realvalue, out value); + dataSouceMapItem.Value = value; + dataSouceMapModels.Add(dataSouceMapItem); + } + var groups = dataSouceMapModels.Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); + foreach (var group in groups) + { + #region 平均值 + var dataSouceMapGroups = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Average).ToList(); + if (dataSouceMapGroups != null && dataSouceMapGroups.Count() > 0) + { + var dataSouceMapGroupAverages = dataSouceMapGroups.GroupBy(t => new + { + t.Parm, + t.Tag + }).Select(t => new + { + Parm = t.Key.Parm, + Tag = t.Key.Tag, + Value = t.Average(a => a.Value) + }).ToList(); + foreach (var dataSouceMapGroupAverage in dataSouceMapGroupAverages) + { + result.Items.Add(new DataSourceItemModel + { + GroupId = group.GroupId, + GroupParm = group.GroupParm, + GroupTag = group.GroupTag, + Parm = dataSouceMapGroupAverage.Parm, + Tag = dataSouceMapGroupAverage.Tag, + Value = dataSouceMapGroupAverage.Value + }); + } + } + #endregion + #region 组 + //var dataSouceMapGroup2s = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Common).ToList(); + //if(dataSouceMapGroup2s) + #endregion + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetDataSource", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + + + public async Task> GetDataSource_v1(JObject input) + { + var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = new DataSourceModel_v1 { ItemsExplain = new List { }, Data = new JObject { } } }; + try + { + long dataSourceId = 0; + long.TryParse(input["dataSourceId"].ToString(), out dataSourceId); + if (dataSourceId == 0) + { + result.Code = RequestBackStatuEnum.badrequest.Value; + result.Msg = "dataSourceId必填!"; + return result; + } + var dataSource = _dataSourceContext.DtDataSource.AsNoTracking().TagWith("SubDB").FirstOrDefault(t => t.Id == dataSourceId); + var queryDataSouceMap = _dataSourceContext.DtDataSouceMap.Where(t => t.DataSourceId == dataSourceId); + if (!string.IsNullOrWhiteSpace(dataSource.QueryTerms)) + { + try + { + var queryTerms = JsonConvert.DeserializeObject>(dataSource.QueryTerms); + foreach (var queryTerm in queryTerms) + { + if(queryTerm.Field== "constId") + { + long constId = 0; + long.TryParse(input["constId"]?.ToString(), out constId); + if (queryTerm.Operation == "equal" && constId > 0) + { + var equipIds = await _context.EquipmentInfo.Where(t => t.Constid == constId && t.State == 1).AsNoTracking().TagWith("SubDB").Select(t => t.Id).ToListAsync(); + queryDataSouceMap = queryDataSouceMap.Where(t => equipIds.Contains(t.EquipId)); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetDataSource_v1", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + } + + var dataSouceMaps = await queryDataSouceMap.AsNoTracking().ToListAsync(); + result.Data.Title = dataSource.Title; + #region 获取实时Id + var dataSouceMap1s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); + var realIds = dataSouceMap1s.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); + var dataSouceMapModels = new List(); + if (realIds != null && realIds.Count() > 0) + { + #region 获取实时值 + var realDatas = await _realDataCoreService.GetRealValueFromRedisByPro(dataSource.ProjectId); + foreach (var dataSouceMap1 in dataSouceMap1s) + { + var realData = realDatas.FirstOrDefault(t => t.Id == dataSouceMap1.SourceId); + if (realData == null) + { + continue; + } + var dataSouceMapItem = _mapper.Map(dataSouceMap1); + var value = 0d; + double.TryParse(realData.Realvalue, out value); + dataSouceMapItem.Value = Math.Round(value, 2); + dataSouceMapModels.Add(dataSouceMapItem); + } + #endregion + } + #endregion + + #region 获取状态值 + var dataSouceMap2s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.Status).ToList(); + if (dataSouceMap2s != null && dataSouceMap2s.Count() > 0) + { + var equipIds = dataSouceMap2s.Select(t => (long?)t.EquipId).Distinct().ToList(); + var equipsCommStatus = await _realDataAnalyzeCoreService.GetEquCommStatusAsync(equipIds); + foreach (var dataSouceMap2 in dataSouceMap2s) + { + var _equipsCommStatus = equipsCommStatus.Data.FirstOrDefault(t => t.EquId == dataSouceMap2.EquipId); + if (_equipsCommStatus == null) + { + continue; + } + var dataSouceMapItem = _mapper.Map(dataSouceMap2); + dataSouceMapItem.Value = _equipsCommStatus.CurrentStatus ?? 0; + dataSouceMapModels.Add(dataSouceMapItem); + } + } + #endregion + var group0s = dataSouceMapModels.Where(t => t.GroupCalculate == ReportGroupCalculateEnum.Common && t.GroupParentId == 0).Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); + if (group0s != null && group0s.Count() > 0) + { + var items = new JArray { }; + foreach (var group in group0s) + { + #region 组 + var dataSouceMapGroup2s = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Common).ToList(); + if (dataSouceMapGroup2s != null && dataSouceMapGroup2s.Count() > 0) + { + var item = new JObject { }; + item["GroupTag"] = group.GroupTag; + item["GroupParm"] = group.GroupParm; + foreach (var dataSouceMapGroup2 in dataSouceMapGroup2s) + { + item[dataSouceMapGroup2.Parm] = dataSouceMapGroup2.Value; + result.Data.ItemsExplain.Add(new ItemExplain + { + GroupTag = dataSouceMapGroup2.GroupTag, + GroupParm = dataSouceMapGroup2.GroupParm, + Parm = dataSouceMapGroup2.Parm, + Tag = dataSouceMapGroup2.Tag + }); + } + items.Add(item); + } + #endregion + } + result.Data.Data["Items"] = items; + } + + + var group1s = dataSouceMapModels.Where(t => t.GroupCalculate == ReportGroupCalculateEnum.Average).Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); + foreach (var group in group1s) + { + #region 平均值 + var dataSouceMapGroups = dataSouceMapModels.Where(t => t.GroupId == group.GroupId).ToList(); + if (dataSouceMapGroups != null && dataSouceMapGroups.Count() > 0) + { + var dataSouceMapGroupAverages = dataSouceMapGroups.GroupBy(t => new + { + t.Parm, + t.Tag + }).Select(t => new + { + Parm = t.Key.Parm, + Tag = t.Key.Tag, + Value = t.Average(a => a.Value) + }).ToList(); + foreach (var dataSouceMapGroupAverage in dataSouceMapGroupAverages) + { + result.Data.Data[dataSouceMapGroupAverage.Parm] = dataSouceMapGroupAverage.Value; + result.Data.ItemsExplain.Add(new ItemExplain + { + GroupTag = group.GroupTag, + GroupParm = group.GroupParm, + Parm = dataSouceMapGroupAverage.Parm, + Tag = dataSouceMapGroupAverage.Tag + }); + } + } + #endregion + } + + result.Data.ItemsExplain = result.Data.ItemsExplain.Distinct().ToList(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetDataSource", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs new file mode 100644 index 0000000..96135bb --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs @@ -0,0 +1,1086 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Report; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.Report +{ + public class DataSourceV02Service : IDataSourceV02Service + { + private readonly ILogger _logger; + private readonly WeiCloudAirDBContext _airDBContext; + private readonly WeiCloudDBContext _context; + public DataSourceV02Service(ILogger logger, WeiCloudDBContext context, WeiCloudAirDBContext airDBContext) + { + _logger = logger; + _airDBContext = airDBContext; + _context = context; + } + /// + /// 能耗列表 + /// + /// + /// + public async Task> GetEnergyConsum(QueryDataSourceEnergyConsumModel input) + { + var result = new ResultPageModel { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + if (input.ProjectId <= 0 && (input.ProjectIds == null || input.ProjectIds.Count() == 0 || input.ProjectIds.Any(t => t < 0))) + { + result.Code = RequestBackStatuEnum.diy.Value; + result.Msg = "项目Id不能为空!"; + return result; + } + if ((!input.StartTimeDay.HasValue || !input.EndTimeDay.HasValue) + && (!input.StartTimeHour.HasValue || !input.EndTimeHour.HasValue)) + { + result.Code = RequestBackStatuEnum.diy.Value; + result.Msg = "日期不能为空!"; + return result; + } + try + { + var equipQuery = _context.EquipmentInfo.Where(t => t.State == 1).AsQueryable(); + if (input.ProjectId > 0) + { + equipQuery = equipQuery.Where(t => t.Projectid == input.ProjectId); + } + if (input.ProjectIds != null && input.ProjectIds.Count() > 0) + { + equipQuery = equipQuery.Where(t => t.Projectid != null && input.ProjectIds.Contains((long)t.Projectid)); + } + + if (input.EquipId > 0) + { + equipQuery = equipQuery.Where(t => t.Id == input.EquipId); + } + if (input.EquipIds != null && input.EquipIds.Count() > 0) + { + equipQuery = equipQuery.Where(t => input.EquipIds.Contains(t.Id)); + } + if (input.ConsturctId > 0) + { + equipQuery = equipQuery.Where(t => t.Constid == input.ConsturctId); + } + if (input.ConsturctIds != null && input.ConsturctIds.Count() > 0) + { + equipQuery = equipQuery.Where(t => t.Constid != null && input.ConsturctIds.Contains((long)t.Constid)); + } + if (!string.IsNullOrWhiteSpace(input.KeyWord)) + { + equipQuery = equipQuery.Where(t => t.Eqname.Contains(input.KeyWord)); + } + //result.TotalCount = equipQuery.Count(); + //if (input.PageSize > 0 && input.PageIndex > 0) + //{ + // equipQuery = equipQuery.Skip((input.PageIndex - 1) * input.PageSize); + //} + var equipInfos = await equipQuery.AsNoTracking().ToListAsync(); + if (equipInfos.Count() == 0) + { + return result; + } + var equipIds = equipInfos.Select(t => t.Id).ToList(); + var timeQuery = _airDBContext.Times.AsQueryable(); + var startTime = DateTime.MinValue; + var endTime = DateTime.MinValue; + if (input.StartTimeDay.HasValue) + { + startTime = DateTime.Parse(input.StartTimeDay.Value.ToString("yyyy-MM-dd")); + endTime = DateTime.Parse(input.EndTimeDay.Value.ToString("yyyy-MM-dd")).AddDays(1); + } + else if (input.StartTimeHour.HasValue) + { + startTime = DateTime.Parse(input.StartTimeDay.Value.ToString("yyyy-MM-dd HH:00:00")); + endTime = DateTime.Parse(input.EndTimeDay.Value.ToString("yyyy-MM-dd HH:00:00")).AddHours(1); + } + timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime); + var timers = await timeQuery.AsNoTracking().ToListAsync(); + var timeIds = timers.Select(t => t.Id).ToList(); + var energyConsumeDBItems = new List { }; + + IQueryable dwQuery = null; + if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.ElectricPower + || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.ElectricPower)) + || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) + { + var ammeterDwQuery = _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).Select(t => new DataSourceEnergyConsumDBItemModel + { + EquipId = t.Parm002 ?? 0, + Consume = t.AmParm003 ?? 0, + Unit = "kWh", + EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.ElectricPower, + TimeId = t.Parm001 + }); + if (dwQuery == null) + { + dwQuery = ammeterDwQuery; + } + else + { + dwQuery.Union(ammeterDwQuery); + } + } + if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Gas + || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Gas)) + || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) + { + var gasDwQuery = _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + { + EquipId = t.Parm002 ?? 0, + Consume = t.GmParm002 ?? 0, + Unit = "m³", + EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Gas, + TimeId = t.Parm001 + }); + if (dwQuery == null) + { + dwQuery = gasDwQuery; + } + else + { + dwQuery.Union(gasDwQuery); + } + } + if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Heat + || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Heat)) + || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) + { + var heatDwQuery = _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + { + EquipId = t.Parm002 ?? 0, + Consume = t.HmParm001 ?? 0, + Unit = "GJ", + EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Heat, + TimeId = t.Parm001 + }); + if (dwQuery == null) + { + dwQuery = heatDwQuery; + } + else + { + dwQuery.Union(heatDwQuery); + } + } + if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Water + || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Water)) + || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) + { + var waterDwQuery = _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + { + EquipId = t.Parm002 ?? 0, + Consume = t.WmParm002 ?? 0, + Unit = "t", + EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Water, + TimeId = t.Parm001 + }); + if (dwQuery == null) + { + dwQuery = waterDwQuery; + } + else + { + dwQuery.Union(waterDwQuery); + } + } + result.TotalCount = dwQuery.Count(); + if (input.PageSize > 0 && input.PageIndex > 0) + { + dwQuery = dwQuery.Skip((input.PageIndex - 1) * input.PageSize); + } + var resultItems = await dwQuery.AsNoTracking().ToListAsync(); + var constIds = equipInfos.Select(t => t.Constid ?? 0).Distinct().ToList(); + var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + foreach (var resultItem in resultItems) + { + var equipInfo = equipInfos.FirstOrDefault(t => t.Id == resultItem.EquipId); + + result.Data.Add(new DataSourceEnergyConsumModel + { + EquipId = resultItem.EquipId, + EquipName = equipInfo.Eqname, + + }); + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + + /// + /// 获取数据表 + /// + /// + public async Task>> GetDataTables() + { + var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; + try + { + var iotLabelTypes = await _context.IotLabelType.Where(t => t.IsDeleted == false).AsNoTracking().ToListAsync(); + var levelIotLabelTypes = iotLabelTypes.Where(t => t.ParentId == 0).ToList(); + foreach (var levelIotLabelType in levelIotLabelTypes) + { + var pItem = new DataSourceDataTableModel + { + Id = levelIotLabelType.Id, + Name = levelIotLabelType.Name, + Remark = levelIotLabelType.Remark + }; + if (!string.IsNullOrEmpty(levelIotLabelType.Dimension)) + { + pItem.Dimensions = JsonConvert.DeserializeObject>(levelIotLabelType.Dimension); + } + result.Data.Add(pItem); + var childIotLabelTypes = iotLabelTypes.Where(t => t.ParentId == levelIotLabelType.Id).ToList(); + foreach (var childIotLabelType in childIotLabelTypes) + { + var cItem = new DataSourceDataTableModel + { + Id = childIotLabelType.Id, + Name = childIotLabelType.Name, + Remark = childIotLabelType.Remark + }; + if (!string.IsNullOrEmpty(childIotLabelType.Inputs)) + { + cItem.QueryParams = JsonConvert.DeserializeObject>(childIotLabelType.Inputs); + } + if (!string.IsNullOrEmpty(childIotLabelType.Outputs)) + { + cItem.ReturnParams = JsonConvert.DeserializeObject>(childIotLabelType.Outputs); + } + pItem.Childs.Add(cItem); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + /// + /// 维度-时间 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private List>> GetDataSourceDataByTime(List labels, DateTime? startTime, DateTime? endTime, string dimension, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) + { + var result = new List>>(); + var _startTime = startTime.GetValueOrDefault(); + var _endTime = _startTime; + + while (_startTime < endTime) + { + if (_startTime > DateTime.Now) + { + break; + } + var timeUnit = string.Empty; + if (dimension == IOTLabelDimensionEnum.TimeHour) + { + _endTime = _startTime.AddHours(1); + timeUnit = _startTime.ToString("yyyy-MM-dd HH"); + } + else if (dimension == IOTLabelDimensionEnum.TimeDay) + { + _endTime = _startTime.AddDays(1); + timeUnit = _startTime.ToString("yyyy-MM-dd"); + } + else if (dimension == IOTLabelDimensionEnum.TimeMonth) + { + _endTime = _startTime.AddMonths(1); + timeUnit = _startTime.ToString("yyyy-MM"); + } + else if (dimension == IOTLabelDimensionEnum.TimeYear) + { + _endTime = _startTime.AddYears(1); + timeUnit = _startTime.ToString("yyyy"); + } + foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) + { + var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); + var _timeIds = times.Where(t => t.Fulldatetime >= _startTime && t.Fulldatetime < _endTime).Select(t => t.Id).ToList(); + //var _consume = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).Sum(s => s.Consume); + var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).ToList()); + + var item = result.FirstOrDefault(t => t.Name == iotLabelType.Name); + if (item == null) + { + item = new DataSourceDataModel> { Name = iotLabelType.Name, Data = new List { } }; + result.Add(item); + } + item.Data.Add(new DataSourceDataItemModel + { + Time = timeUnit, + Value = Math.Round(_consume, 2).ToString() + }); + } + _startTime = _endTime; + } + return result; + } + private double CalConsume(short calculation, List dws) + { + double r = 0; + switch (calculation) + { + case (short)IOTLabelCalculateEnum.Sum: + r = dws.Sum(s => s.Consume); + break; + case (short)IOTLabelCalculateEnum.Average: + r = dws.Average(s => s.Consume); + break; + case (short)IOTLabelCalculateEnum.Max: + r = dws.Max(s => s.Consume); + break; + //case (short)IOTLabelCalculateEnum.DuplicateRemoval: + // r = dws.Distinct(s => s.Consume); + // break; + case (short)IOTLabelCalculateEnum.Count: + r = dws.Count(); + break; + case (short)IOTLabelCalculateEnum.Min: + r = dws.Min(s => s.Consume); + break; + } + return r; + } + /// + /// 维度-设备 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private async Task>> GetDataSourceDataByEquip(List labels, DateTime? startTime, DateTime? endTime, List constructionInfos, List equipInfos, List dws, List dimensions, List times, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) + { + var result = new List>(); + foreach (var equipInfo in equipInfos) + { + if (dimensions.Count() == 1) + { + //var _consume = dws.Where(t => t.EquipId == equipInfo.Id).Sum(s => s.Consume); + var dicIotLabelEquipId = dicIotLabelEquipIds.FirstOrDefault(t => t.Value.Any(v => v == equipInfo.Id)); + var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, dws.Where(t => t.EquipId == equipInfo.Id).ToList()); + result.Add(new DataSourceDataModel + { + Name = equipInfo.Eqname, + Data = Math.Round(_consume, 2).ToString() + }); + } + else if (dimensions.Count() > 1) + { + result.Add(new DataSourceDataModel + { + Name = equipInfo.Eqname, + Data = await GetDataSourceData(labels, startTime, endTime, dimensions.Skip(1).ToList(), times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos) + }); + } + } + return result; + } + /// + /// 建筑物 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private async Task>> GetDataSourceDataByConstruct(List labels, DateTime? startTime, DateTime? endTime, List constructionInfos, List equipInfos, List dws, List dimensions, List times, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) + { + var result = new List>(); + foreach (var constructionInfo in constructionInfos) + { + if (dimensions.Count() == 1) + { + var equipIds = equipInfos.Where(t => t.Constid == constructionInfo.Id).Select(t => t.Id).ToList(); + //var _consume = dws.Where(t => equipIds.Contains(t.EquipId)).Sum(s => s.Consume); + var _consume = CalConsume(labels.First().Calculation, dws.Where(t => equipIds.Contains(t.EquipId)).ToList()); + result.Add(new DataSourceDataModel + { + Name = constructionInfo.Constinfo, + Data = Math.Round(_consume, 2).ToString() + }); + } + else if (dimensions.Count() > 1) + { + result.Add(new DataSourceDataModel + { + Name = constructionInfo.Constinfo, + Data = await GetDataSourceData(labels,startTime, endTime, dimensions.Skip(1).ToList(), times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos) + }); + } + } + return result; + } + + private async Task GetDataSourceData(List labels, DateTime? startTime, DateTime? endTime, + List dimensions, List times, List dws, + Dictionary> dicIotLabelEquipIds, List iotLabelTypes, List equipInfos, List constructionInfos) + { + if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Equip) + { + var r = GetDataSourceDataByEquip(labels, startTime, endTime, constructionInfos, equipInfos, dws, dimensions, times, dicIotLabelEquipIds, iotLabelTypes); + return await r; + } + else if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeYear + || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeMonth + || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeDay + || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeHour) + { + var r = GetDataSourceDataByTime(labels, startTime, endTime, dimensions.FirstOrDefault(), times, dws, dicIotLabelEquipIds, iotLabelTypes); + return r; + } + else if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Consturct) + { + var constIds = equipInfos.Select(t => t.Constid ?? 0).ToList(); + //var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + var r = GetDataSourceDataByConstruct(labels, startTime, endTime, constructionInfos.Where(t => constIds.Contains(t.Id)).ToList(), equipInfos, dws, dimensions, times, dicIotLabelEquipIds, iotLabelTypes); + return await r; + } + return null; + } + + private async Task GetDataSourceDataV02(List labels, DateTime? startTime, DateTime? endTime, List dimensions, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes, List equipInfos, List constructionInfos) + { + var result = new List { }; + var groupKeys = new List { }; + foreach (var dimension in dimensions) + { + if (dimension == IOTLabelDimensionEnum.Equip) + { + groupKeys.Add("EquipName"); + } + else if (dimension == IOTLabelDimensionEnum.TimeYear) + { + groupKeys.Add("Year"); + } + else if (dimension == IOTLabelDimensionEnum.TimeMonth) + { + groupKeys.Add("YearMonth"); + } + else if (dimension == IOTLabelDimensionEnum.TimeDay) + { + groupKeys.Add("YearMonthDay"); + } + else if (dimension == IOTLabelDimensionEnum.TimeHour) + { + groupKeys.Add("YearMonthDayHour"); + } + else if (dimension == IOTLabelDimensionEnum.Consturct) + { + groupKeys.Add("ConstName"); + } + } + //var query = dws.DynamicGroupBy(new string[] { "EquipId" }); + var queryItems = dws.DynamicGroupBy(groupKeys.ToArray()); + foreach (var queryItem in queryItems) + { + var resultItem = new List { }; + var keys = queryItem.Key.Select(t => t.ToString()).ToList(); + + resultItem.AddRange(keys); + var _dws = ((WeiCloud.Core.Services.Report.LinqExt.DGroupBy)queryItem)._innerlist; + foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) + { + var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); + var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, _dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId)).ToList()); + resultItem.Add(Math.Round(_consume, 2)); + } + result.Add(resultItem); + } + return result; + } + private List GetDataSourceDataByTimeV02(List labels, DateTime? startTime, DateTime? endTime, List equipInfos, List constructionInfos, string dimension, List otherDimensions, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) + { + var result = new List(); + var _startTime = startTime.GetValueOrDefault(); + var _endTime = _startTime; + + while (_startTime < endTime) + { + var resultItem = new List(); + if (_startTime > DateTime.Now) + { + break; + } + var timeUnit = string.Empty; + if (dimension == IOTLabelDimensionEnum.TimeHour) + { + _endTime = _startTime.AddHours(1); + timeUnit = _startTime.ToString("yyyy-MM-dd HH"); + } + else if (dimension == IOTLabelDimensionEnum.TimeDay) + { + _endTime = _startTime.AddDays(1); + timeUnit = _startTime.ToString("yyyy-MM-dd"); + } + else if (dimension == IOTLabelDimensionEnum.TimeMonth) + { + _endTime = _startTime.AddMonths(1); + timeUnit = _startTime.ToString("yyyy-MM"); + } + else if (dimension == IOTLabelDimensionEnum.TimeYear) + { + _endTime = _startTime.AddYears(1); + timeUnit = _startTime.ToString("yyyy"); + } + resultItem.Add(timeUnit); + if (otherDimensions.Count() > 0) + { + foreach (var otherDimension in otherDimensions) + { + if (otherDimension == IOTLabelDimensionEnum.Consturct) + { + //resultItem.Add(otherDimension); + foreach (var constructionInfo in constructionInfos) + { + resultItem.Add(constructionInfo.Constinfo); + } + } + } + } + else + { + + } + + var _timeIds = times.Where(t => t.Fulldatetime >= _startTime && t.Fulldatetime < _endTime).Select(t => t.Id).ToList(); + //var consumeList = GetCalConsume(constructionInfos, equipInfos, otherDimensions, dicIotLabelEquipIds, labels, _timeIds, iotLabelTypes); + _startTime = _endTime; + result.Add(resultItem); + } + return result; + } + private List GetCalConsume(List constructionInfos, List equipInfos, List otherDimensions, List dws, Dictionary> dicIotLabelEquipIds, List labels, List _timeIds, List iotLabelTypes) + { + var result = new List(); + + + foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) + { + var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); + + foreach (var otherDimension in otherDimensions) + { + if (otherDimension == "Consturct") + { + + } + } + //var _consume = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).Sum(s => s.Consume); + var _dws = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).ToList(); + var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, _dws); + + result.Add(_consume); + } + return result; + } + /// + /// 获取数据 + /// + /// + /// + //public async Task> GetDataSourceData(GetDataSourceDataModel input) + //{ + // var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = new object { } }; + // try + // { + // //if (input.Dimensions == null || input.Dimensions.Count() == 0) + // //{ + // // result.Code = RequestBackStatuEnum.diy.Value; + // // result.Msg = "维度不能为空!"; + // // return result; + // //} + // //if (input.Labels == null || input.Labels.Count() == 0) + // //{ + // // result.Code = RequestBackStatuEnum.diy.Value; + // // result.Msg = "项目Id不能为空!"; + // // return result; + // //} + + // if ((input.Dimensions == null || input.Dimensions.Count() == 0) && (input.Labels == null || input.Labels.Count() == 0)) + // { + // result.Code = RequestBackStatuEnum.diy.Value; + // result.Msg = "维度或者指标不能为空!"; + // return result; + // } + + // var labelIds = input.Labels.Select(t => t.LabelId).ToList(); + // var iotLabelTypes = await _context.IotLabelType.Where(t => labelIds.Contains(t.Id) && t.IsDeleted == false).AsNoTracking().ToListAsync(); + // if (iotLabelTypes.Count() == 0 || !iotLabelTypes.Any(t => t.ParentId > 0)) + // { + // result.Code = RequestBackStatuEnum.diy.Value; + // result.Msg = "标签未找到!"; + // return result; + // } + // #region 条件 + // DateTime? startTime = DateTime.MinValue; + // DateTime? endTime = DateTime.Now; + // //var queryTimeType = (short)QueryTimeTypeEnum.Day; + + // if (input.Query != null && input.Query.ContainsKey("TimeDay")) + // { + // startTime = DateTime.Parse(input.Query["TimeDay"].ToString()); + // endTime = startTime.GetValueOrDefault().AddDays(1); + // //queryTimeType = (short)QueryTimeTypeEnum.Day; + // } + // else if (input.Query != null && input.Query.ContainsKey("TimeMonth")) + // { + // startTime = DateTime.Parse($"{input.Query["TimeMonth"].ToString()}-01"); + // endTime = startTime.GetValueOrDefault().AddMonths(1); + // //queryTimeType = (short)QueryTimeTypeEnum.Month; + // } + // else if (input.Query != null && input.Query.ContainsKey("TimeYear")) + // { + // startTime = DateTime.Parse($"{input.Query["TimeYear"].ToString()}-01-01"); + // endTime = startTime.GetValueOrDefault().AddYears(1); + // //queryTimeType = (short)QueryTimeTypeEnum.Year; + // } + // else if (input.Query != null && input.Query.ContainsKey("StartTimeDay") && input.Query.ContainsKey("EndTimeDay")) + // { + // startTime = DateTime.Parse(input.Query["StartTimeDay"].ToString()); + // endTime = DateTime.Parse(input.Query["EndTimeDay"].ToString()).AddDays(1); + // //queryTimeType = (short)QueryTimeTypeEnum.Custom; + // } + // if (startTime != null && startTime >= DateTime.Now) + // { + // result.Code = RequestBackStatuEnum.diy.Value; + // result.Msg = "开始时间不能大于当前时间!"; + // return result; + // } + // #endregion + + + // var labelType = iotLabelTypes.FirstOrDefault(t => t.Type > 0).Type; + // var iotLabelTypeIds = iotLabelTypes.Select(t => t.Id).ToList(); + // var iotThingAttributes = await _context.IotThingAttribute.Where(t => iotLabelTypeIds.Contains(t.LabelCodeId) && t.IsDeleted == false).AsNoTracking().ToListAsync(); + // var equipIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Equip && t.IsDeleted == false).Select(t => t.ThingId).ToList(); + // var constructIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Construct && t.IsDeleted == false).Select(t => t.ThingId).ToList(); + // var paramIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Param && t.IsDeleted == false).Select(t => t.ThingId).ToList(); + // var projectIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Project && t.IsDeleted == false).Select(t => t.ThingId).ToList(); + // var queryEquipInfos = _context.EquipmentInfo.Where(t => t.State == 1); + + // if (input.Query!=null && input.Query.ContainsKey("EquipId")) + // { + // var _equipId = long.Parse(input.Query["EquipId"].ToString()); + // queryEquipInfos = queryEquipInfos.Where(t => t.Id == _equipId); + // } + // else if (input.Query != null && input.Query.ContainsKey("EquipIds")) + // { + // var _equipIds = JsonConvert.DeserializeObject>(input.Query["EquipIds"].ToString()); + // queryEquipInfos = queryEquipInfos.Where(t => _equipIds.Contains(t.Id)); + // } + // if (input.Query != null && input.Query.ContainsKey("ConsturctId")) + // { + // var _consturctId = long.Parse(input.Query["ConsturctId"].ToString()); + // queryEquipInfos = queryEquipInfos.Where(t => t.Constid == _consturctId); + // } + // else if (input.Query != null && input.Query.ContainsKey("ConsturctIds")) + // { + // var _consturctIds = JsonConvert.DeserializeObject>(input.Query["ConsturctIds"].ToString()); + // queryEquipInfos = queryEquipInfos.Where(t => t.Constid != null && _consturctIds.Contains((long)t.Constid)); + // } + // if (projectIds.Count() > 0) + // { + // queryEquipInfos = queryEquipInfos.Where(t => t.Projectid != null && projectIds.Contains((long)t.Projectid)); + // } + // if (constructIds.Count() > 0) + // { + // queryEquipInfos = queryEquipInfos.Where(t => t.Constid != null && constructIds.Contains((long)t.Constid)); + // } + // List realDatas = null; + // if (paramIds.Count() > 0) + // { + // realDatas = await _context.TbRealData.Where(t => paramIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + // var realDataEquipIds = realDatas.Select(t => t.Equid ?? 0).ToList(); + // equipIds.AddRange(realDataEquipIds); + // } + // if (equipIds.Count() > 0) + // { + // queryEquipInfos = queryEquipInfos.Where(t => equipIds.Contains(t.Id)); + // } + + // Dictionary> dicIotLabelEquipIds = new Dictionary> { }; + // foreach (var iotLabelType in iotLabelTypes) + // { + // var _equipIds = new List(); + // var _iotThingAttributes = iotThingAttributes.Where(t => t.LabelCodeId == iotLabelType.Id).ToList(); + // foreach (var _iotThingAttribute in _iotThingAttributes) + // { + // if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Equip) + // { + // _equipIds.Add(_iotThingAttribute.ThingId); + // } + // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Construct) + // { + // var __equipIds = queryEquipInfos.Where(t => _iotThingAttribute.ThingId == t.Constid).Select(t => t.Id).ToList(); + // if (__equipIds.Count() > 0) + // { + // _equipIds.AddRange(__equipIds); + // } + // } + // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Project) + // { + // var __equipIds = queryEquipInfos.Where(t => _iotThingAttribute.ThingId == t.Projectid).Select(t => t.Id).ToList(); + // if (__equipIds.Count() > 0) + // { + // _equipIds.AddRange(__equipIds); + // } + // } + // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Param) + // { + // var __equipIds = realDatas.Where(t => _iotThingAttribute.ThingId == t.Id).Select(t => t.Equid ?? 0).ToList(); + // if (__equipIds.Count() > 0) + // { + // _equipIds.AddRange(__equipIds); + // } + // } + // } + + // _equipIds = _equipIds.Distinct().ToList(); + // dicIotLabelEquipIds.Add(iotLabelType.Id, _equipIds); + // } + // var equipInfos = await queryEquipInfos.AsNoTracking().ToListAsync(); + // var equipInfoIds = equipInfos.Select(t => t.Id).ToList(); + + // if (endTime > DateTime.Now) + // { + // endTime = DateTime.Now; + // } + + // var times = await _airDBContext.Times.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime).AsNoTracking().ToListAsync(); + // var timeIds = times.Select(t => t.Id).ToList(); + + // var ammeterType = (short)ReportEnergyConsumeTypeEnum.ElectricPower; + // //var ammeterDwQuery = _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + // //{ + // // EquipId = t.Parm002 ?? 0, + // // Consume = t.AmParm003 ?? 0, + // // Unit = "kWh", + // // EnergyConsumeType = ammeterType, + // // TimeId = t.Parm001 + // //}); + // var ammeterDwQuery = from dw in _airDBContext.TbAmmeterDw + // join time in _airDBContext.Times on dw.Parm001 equals time.Id + // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime + // select new DataSourceEnergyConsumDBItemModel + // { + // EquipId = dw.Parm002 ?? 0, + // Consume = dw.AmParm003 ?? 0, + // Unit = "kWh", + // EnergyConsumeType = ammeterType, + // TimeId = time.Id, + // Year = time.Year.ToString(), + // YearMonth = time.Year + "-" + time.Month, + // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, + // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + // }; + // var gasType = (short)ReportEnergyConsumeTypeEnum.Gas; + // //var gasDwQuery = _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + // //{ + // // EquipId = t.Parm002 ?? 0, + // // Consume = t.GmParm002 ?? 0, + // // Unit = "m³", + // // EnergyConsumeType = gasType, + // // TimeId = t.Parm001 + // //}); + // var gasDwQuery = from dw in _airDBContext.TbGasMeterDw + // join time in _airDBContext.Times on dw.Parm001 equals time.Id + // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime + // select new DataSourceEnergyConsumDBItemModel + // { + // EquipId = dw.Parm002 ?? 0, + // Consume = dw.GmParm002 ?? 0, + // Unit = "m³", + // EnergyConsumeType = gasType, + // TimeId = time.Id, + // Year = time.Year.ToString(), + // YearMonth = time.Year + "-" + time.Month, + // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, + // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + // }; + + // var headType = (short)ReportEnergyConsumeTypeEnum.Heat; + // //var heatDwQuery = _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + // //{ + // // EquipId = t.Parm002 ?? 0, + // // Consume = t.HmParm001 ?? 0, + // // Unit = "GJ", + // // EnergyConsumeType = headType, + // // TimeId = t.Parm001 + // //}); + // var heatDwQuery = from dw in _airDBContext.TbHeatMeterDw + // join time in _airDBContext.Times on dw.Parm001 equals time.Id + // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime + // select new DataSourceEnergyConsumDBItemModel + // { + // EquipId = dw.Parm002 ?? 0, + // Consume = dw.HmParm001 ?? 0, + // Unit = "GJ", + // EnergyConsumeType = headType, + // TimeId = time.Id, + // Year = time.Year.ToString(), + // YearMonth = time.Year + "-" + time.Month, + // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, + // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + // }; + + // var waterType = (short)ReportEnergyConsumeTypeEnum.Water; + // //var waterDwQuery = _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel + // //{ + // // EquipId = t.Parm002 ?? 0, + // // Consume = t.WmParm002 ?? 0, + // // Unit = "t", + // // EnergyConsumeType = waterType, + // // TimeId = t.Parm001 + // //}); + // var waterDwQuery = from dw in _airDBContext.TbWaterMeterDw + // join time in _airDBContext.Times on dw.Parm001 equals time.Id + // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime + // select new DataSourceEnergyConsumDBItemModel + // { + // EquipId = dw.Parm002 ?? 0, + // Consume = dw.WmParm002 ?? 0, + // Unit = "t", + // EnergyConsumeType = waterType, + // TimeId = time.Id, + // Year = time.Year.ToString(), + // YearMonth = time.Year + "-" + time.Month, + // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, + // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + // }; + + // //var query = ammeterDwQuery.Union(gasDwQuery).Union(heatDwQuery).Union(waterDwQuery); + // //var list = await query.ToListAsync(); + + + // var ammeterDws = await ammeterDwQuery.ToListAsync(); + // var gasDws = await gasDwQuery.ToListAsync(); + // var heatDws = await heatDwQuery.ToListAsync(); + // var waterDws = await waterDwQuery.ToListAsync(); + + // //dwQuery = ammeterDwQuery.Union(gasDwQuery).Union(heatDwQuery).Union(waterDwQuery); + // //var dws = await dwQuery.ToListAsync(); + // var dws = new List { }; + // if (ammeterDws.Count() > 0) + // { + // dws.AddRange(ammeterDws); + // } + // if (gasDws.Count() > 0) + // { + // dws.AddRange(gasDws); + // } + // if (heatDws.Count() > 0) + // { + // dws.AddRange(heatDws); + // } + // if (waterDws.Count() > 0) + // { + // dws.AddRange(waterDws); + // } + // if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeYear)) + // { + // dws = dws.GroupBy(t => new { t.EquipId, t.Year }).Select(t => new DataSourceEnergyConsumDBItemModel + // { + // EquipId = t.Key.EquipId, + // Consume = t.Sum(s => s.Consume), + // Unit = t.First().Unit, + // EnergyConsumeType = t.First().EnergyConsumeType, + // TimeId = t.First().TimeId, + // Year = t.Key.Year, + // YearMonth = t.First().YearMonth, + // YearMonthDay = t.First().YearMonthDay, + // YearMonthDayHour = t.First().YearMonthDayHour + // }).ToList(); + // } + // else if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeMonth)) + // { + // dws = dws.GroupBy(t => new { t.EquipId, t.YearMonth }).Select(t => new DataSourceEnergyConsumDBItemModel + // { + // EquipId = t.Key.EquipId, + // Consume = t.Sum(s => s.Consume), + // Unit = t.First().Unit, + // EnergyConsumeType = t.First().EnergyConsumeType, + // TimeId = t.First().TimeId, + // Year = t.First().Year, + // YearMonth = t.Key.YearMonth, + // YearMonthDay = t.First().YearMonthDay, + // YearMonthDayHour = t.First().YearMonthDayHour + // }).ToList(); + // } + // else if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeDay)) + // { + // dws = dws.GroupBy(t => new { t.EquipId, t.YearMonthDay }).Select(t => new DataSourceEnergyConsumDBItemModel + // { + // EquipId = t.Key.EquipId, + // Consume = t.Sum(s => s.Consume), + // Unit = t.First().Unit, + // EnergyConsumeType = t.First().EnergyConsumeType, + // TimeId = t.First().TimeId, + // Year = t.First().Year, + // YearMonth = t.First().YearMonth, + // YearMonthDay = t.Key.YearMonthDay, + // YearMonthDayHour = t.First().YearMonthDayHour + // }).ToList(); + // } + // else if (!input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeHour)) + // { + // dws = dws.GroupBy(t => t.EquipId).Select(t => new DataSourceEnergyConsumDBItemModel + // { + // EquipId = t.Key, + // Consume = t.Sum(s => s.Consume), + // Unit = t.First().Unit, + // EnergyConsumeType = t.First().EnergyConsumeType, + // TimeId = t.First().TimeId, + // Year = t.First().Year, + // YearMonth = t.First().YearMonth, + // YearMonthDay = t.First().YearMonthDay, + // YearMonthDayHour = t.First().YearMonthDayHour + // }).ToList(); + // } + + // var constIds = equipInfos.Select(i => i.Constid ?? 0).ToList(); + // var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + // foreach (var dw in dws) + // { + // var equipInfo = equipInfos.FirstOrDefault(t => t.Id == dw.EquipId); + // if (equipInfo != null) + // { + // dw.EquipName = equipInfo.Eqname; + // } + // var constructionInfo = constructionInfos.FirstOrDefault(t => t.Id == equipInfo.Constid); + // if (constructionInfo != null) + // { + // dw.ConstId = constructionInfo.Id; + // dw.ConstName = constructionInfo.Constinfo; + // } + // //var time = times.FirstOrDefault(t => t.Id == dw.TimeId); + // //if (time != null) + // //{ + // // dw.Year = time.Fulldatetime.GetValueOrDefault().ToString("yyyy"); + // // dw.YearMonth = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM"); + // // dw.YearMonthDay = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM-dd"); + // // dw.YearMonthDayHour = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM-dd HH"); + // //} + // } + + // var resultItems = await GetDataSourceDataV02(input.Labels, startTime, endTime, input.Dimensions, times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos); + // result.Data = new + // { + // Labels = iotLabelTypes.Select(t => new { t.Name, t.Id }).ToList(), + // Data = resultItems + // }; + // //if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Equip) + // //{ + // // result.Data = GetDataSourceDataByEquip(equipInfos, dws); + // //} + // //else if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeYear + // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeMonth + // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeDay + // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeHour) + // //{ + // // result.Data = GetDataSourceDataByTime(startTime, endTime, input.Dimensions.FirstOrDefault(), times, dws, dicIotLabelEquipIds, iotLabelTypes); + // //} + // //else if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Consturct) + // //{ + // // var constIds = queryEquipInfos.Select(t => t.Constid ?? 0).ToList(); + // // var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); + // // result.Data = GetDataSourceDataByConstruct(constructionInfos, equipInfos, dws, input.Dimensions, times, dicIotLabelEquipIds, iotLabelTypes); + // //} + // } + // catch (Exception ex) + // { + // _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + // } + // return result; + //} + } + #region GroupBy + static class LinqExt + { + public class DGroupBy : IGrouping + { + public List _innerlist = new List(); + + private object[] _key; + + public DGroupBy(object[] key) { _key = key; } + + public object[] Key + { + get { return _key; } + } + + public void Add(T value) + { + _innerlist.Add(value); + } + + public IEnumerator GetEnumerator() + { + return this._innerlist.GetEnumerator(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return this._innerlist.GetEnumerator(); + } + } + + public static IEnumerable> DynamicGroupBy(this IEnumerable data, string[] keys) + { + List> list = new List>(); + foreach (var item in data.Select(x => new { + k = keys.Select(y => x.GetType().GetProperty(y).GetValue(x, null)).ToArray(), + v = x + })) + { + DGroupBy existing = list.SingleOrDefault(x => x.Key.Zip(item.k, (a, b) => a.Equals(b)).All(y => y)); + if (existing == null) + { + existing = new DGroupBy(item.k); + list.Add(existing); + } + existing.Add(item.v); + } + return list; + } + } + + #endregion +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs new file mode 100644 index 0000000..89167fc --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs @@ -0,0 +1,787 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using MySqlConnector; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.Report +{ + public class DataSourceV03Service : IDataSourceV03Service + { + private readonly ILogger _logger; + private readonly WeiCloudDBUserCenterContext _userCenterContext; + private readonly WeiCloudDBContext _dbContext; + public DataSourceV03Service(ILogger logger, WeiCloudDBUserCenterContext userCenterContext , WeiCloudDBContext dbContext) + { + _logger = logger; + _userCenterContext = userCenterContext; + _dbContext = dbContext; + } + /// + /// 获取参数历史数据 + /// + /// + /// + /// + /// + /// + public async Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds) + { + var items = new List { }; + try + { + // var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); + + // var contextOptions = new DbContextOptionsBuilder() + //.UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + // using var __contextDB = new WeiCloudDBContext(contextOptions); + // items = await __contextDB.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).OrderBy(t => t.CreateTime).ToListAsync(); + //直接注入 + items = await _dbContext.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).ToListAsync(); + // items = await _dbContext.DsPointHistory + //.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime) + //.GroupBy(t => new { t.Id, Hour = t.CreateTime.Hour, Date = t.CreateTime.Date }) + //.Select(g => g.OrderBy(t => t.CreateTime).FirstOrDefault()) + //.OrderBy(t => t.CreateTime) + //.ToListAsync(); + + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + /// + /// 获取历史数据(间隔) + /// + /// + /// + /// + /// + /// 1-5分钟、2-10分钟、3-30分钟、4-1小时 + /// + public async Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds, short intervalType) + { + var items = new List { }; + try + { + var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + if (intervalType == 1) + { + items = await __contextDB.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).OrderBy(t => t.CreateTime).ToListAsync(); + } + else + { + var dateFormat = string.Empty; + var dateFormatValueSql = string.Empty; + if (intervalType == 2) + { + dateFormat = "i"; + dateFormatValueSql = "%10=0"; + } + else if (intervalType == 3) + { + dateFormat = "i"; + dateFormatValueSql = "%30=0"; + } + else if (intervalType == 4) + { + dateFormat = "i"; + dateFormatValueSql = "=0"; + } + string sql = $"SELECT * FROM `DS_Point_History` ph WHERE ph.`Id` IN ({pointIds.ListToStr()}) AND ph.`CreateTime`>='{startTime.ToString("yyyy-MM-dd HH:mm:ss")}' AND ph.`CreateTime`<'{endTime.ToString("yyyy-MM-dd HH:mm:ss")}' AND DATE_FORMAT(`CreateTime`,'%{dateFormat}'){dateFormatValueSql} ORDER BY ph.`CreateTime` ASC"; + using var conn = __contextDB.Database.GetDbConnection(); + if (conn.State == ConnectionState.Closed) + { + conn.Open(); + } + using var cmd = conn.CreateCommand(); + cmd.CommandText = sql; + using var reader = await cmd.ExecuteReaderAsync(); + DataTable dt = new DataTable(); + dt.Load(reader); + foreach (DataRow row in dt.Rows) + { + try + { + var item = new DsPointHistory + { + Id = long.Parse(row["Id"].ToString()), + Time = DateTime.Parse(row["Time"].ToString()), + //Value = double.Parse(row["Value"].ToString()), + CreateTime = DateTime.Parse(row["CreateTime"].ToString()) + }; + items.Add(item); + if (!string.IsNullOrEmpty(row["Value"].ToString())) + { + item.Value = double.Parse(row["Value"].ToString()); + } + } + catch (Exception ex) + { + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetHistorys", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + /// + /// 获取参数历史数据 + /// + /// + /// + /// + /// + public async Task> GetHistorys(long projectId, DateTime queryTime, List pointIds) + { + //var startTime = queryTime.AddMinutes(-30); + var startTime = queryTime.AddHours(-1); + var endTime = queryTime; + var items = new List { }; + try + { + if (pointIds == null || pointIds.Count() == 0) + { + return items; + } + var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + + //string sql = @"SELECT t1.* FROM `DS_Point_History` t1 + //INNER JOIN ( + //SELECT t2.`Id`,MAX(t2.`CreateTime`) AS CreateTime FROM `DS_Point_History` t2 WHERE t2.`Id` IN (@Ids) AND t2.`CreateTime`>@StartTime AND t2.`CreateTime`<=@EndTime GROUP BY t2.`Id` + //) AS t3 ON t1.`Id`=t3.Id AND t1.`CreateTime`=t3.CreateTime"; + string sql = string.Format(@"SELECT t1.* FROM `DS_Point_History` t1 +INNER JOIN ( +SELECT t2.`Id`,MAX(t2.`CreateTime`) AS CreateTime FROM `DS_Point_History` t2 WHERE t2.`Id` IN ({0}) +AND t2.`CreateTime`>@StartTime AND t2.`CreateTime`<=@EndTime GROUP BY t2.`Id` +) AS t3 ON t1.`Id`=t3.Id AND t1.`CreateTime`=t3.CreateTime", pointIds.Join(",")); + //items = await __contextDB.DsPointHistory.FromSqlRaw(sql).AsNoTracking().ToListAsync(); + + var queryParameters = new List { + //new MySqlParameter("@Ids", pointIds.Join(",")), + //new MySqlParameter("@Ids", pointIds.ToArray()), + new MySqlParameter("@StartTime", startTime), + new MySqlParameter("@EndTime", endTime) + }; + items = await __contextDB.DsPointHistory.FromSqlRaw(sql, queryParameters.ToArray()).AsNoTracking().ToListAsync(); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + + /// + /// 获取时间区间内的最大和最小值 + /// + /// + /// + /// + /// + /// + public async Task> GetIntervalMaxMinHistorys(ProjectInfo projectInfo, DateTime startTime, DateTime endTime, List pointIds) + { + var items = new List { }; + try + { + if (pointIds == null || pointIds.Count() == 0 || projectInfo == null || string.IsNullOrEmpty(projectInfo.Dbstr)) + { + return items; + } + //var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + + string sql = string.Format(@"SELECT t2.`Id`,MAX(t2.`Value`) Mx,MIN(t2.`Value`) Mn FROM `DS_Point_History` t2 +WHERE t2.`Id` IN ({0}) +AND t2.`CreateTime`>=@StartTime AND t2.`CreateTime`<=@EndTime AND t2.`Value`>=0 GROUP BY t2.`Id`", pointIds.Join(",")); + + using var conn = __contextDB.Database.GetDbConnection(); + if (conn.State == ConnectionState.Closed) + { + conn.Open(); + } + using var cmd = conn.CreateCommand(); + cmd.CommandText = sql; + cmd.Parameters.Add(new MySqlParameter("@StartTime", startTime)); + cmd.Parameters.Add(new MySqlParameter("@EndTime", endTime)); + using var reader = await cmd.ExecuteReaderAsync(); + DataTable dt = new DataTable(); + dt.Load(reader); + items = DataTableHelper.ConvertToModel(dt); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return items; + } + + /// + /// 获取设备历史数据 + /// + /// + /// + public async Task>> GetEquipHistorys(GetEquipHistoryModel input) + { + var result = new ResultPageModel> { Data = new List> { } }; + try + { + if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) + { + return result; + } + var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + + var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new + { + t.Id, + t.Equid, + t.Standarparamid + }).AsNoTracking().ToListAsync(); + var standarParamIds = realDatas.Select(t => t.Standarparamid ?? 0).Distinct().ToList(); + var realDataIds = realDatas.Select(t => t.Id).ToList(); + + var standarParams = await _userCenterContext.StandarParam.Where(t => standarParamIds.Contains(t.Id)).AsNoTracking().Select(t => new + { + t.Id, + t.Descname + }).ToListAsync(); + + StringBuilder sbCol = new StringBuilder(); + for (var i = 0; i < standarParams.Count(); i++) + { + var standarParam = standarParams[i]; + sbCol.Append("SUM(IF(r.`standarparamid` = ").Append(standarParam.Id).Append(",ph.`Value`,0)) AS '").Append(standarParam.Descname).Append("',"); + } + string otherConditions = string.Empty; + if (input.Interval > 0) + { + switch (input.Interval) + { + case 1: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; + break; + case 2: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; + break; + case 3: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; + break; + case 4: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; + break; + } + } + string sql = string.Format(@"SELECT r.`equid` as Equid,e.`eqname` as EquName, ph.`CreateTime` +,{1} +FROM `DS_Point_History` ph +INNER JOIN `Tb_RealData` r ON ph.id=r.id +INNER JOIN `EquipmentInfo` e ON r.`equid`=e.id +WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} +GROUP BY r.`equid`,ph.`CreateTime`", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions); + + string sqlResult = string.Empty; + if (input.PageIndex > 0 && input.PageSize > 0) + { + sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.`CreateTime` desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); + } + else + { + sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.`CreateTime` desc", sql); + } + + string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); + + using var conn = __contextDB.Database.GetDbConnection(); + if (conn.State == ConnectionState.Closed) + { + conn.Open(); + } + using var cmd = conn.CreateCommand(); + cmd.CommandText = sqlResult; + cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); + cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); + using var reader = await cmd.ExecuteReaderAsync(); + DataTable dt = new DataTable(); + dt.Load(reader); + + foreach (DataRow row in dt.Rows) + { + var dic = new Dictionary { }; + var equipObj = row["Equid"]; + dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); + var equipNameObj = row["EquName"]; + dic.Add("EquName", equipNameObj == null ? "" : equipNameObj.ToString()); + var createTimeObj = row["CreateTime"]; + dic.Add("CreateTime", createTimeObj == null ? "" : Convert.ToDateTime(createTimeObj.ToString()).ToString("yyyy-MM-dd HH:mm:ss") ); + foreach (var standarParam in standarParams) + { + var colObj = row[standarParam.Descname]; + dic.Add(standarParam.Descname, colObj == null ? "" : colObj.ToString()); + } + result.Data.Add(dic); + } + #region 获取数据总个数 + cmd.CommandText = sqlCount; + var totalCount = cmd.ExecuteScalar(); + if (totalCount != null) + { + result.TotalCount = int.Parse(totalCount.ToString()); + } + #endregion + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + /// + /// 获取设备历史数据 + /// + /// + /// + public async Task>> GetEquipHistorysV03(GetEquipHistoryModel input) + { + var result = new ResultPageModel> { Data = new List> { } }; + try + { + if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) + { + return result; + } + var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); + + + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + + var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new + { + t.Id, + t.Equid, + t.Descname + }).AsNoTracking().ToListAsync(); + realDatas = realDatas.OrderBy(d=>d.Descname).ToList(); + var realDataIds = realDatas.Select(t => t.Id).ToList(); + StringBuilder sbCol = new StringBuilder(); + for (var i = 0; i < realDatas.Count(); i++) + { + var realData = realDatas[i]; + sbCol.Append("SUM(IF(ph.id = ").Append(realData.Id).Append(",ph.`Value`,0)) AS '").Append(realData.Id).Append("',"); + } + string otherConditions = string.Empty; + string groupStr = "ph.`CreateTime` as dates "; + //if (input.Interval > 0) + //{ + // switch (input.Interval) + // { + // case 1: + // //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; + // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:50:00')"; + // break; + // case 2: + // otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; + // break; + // case 3: + // otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; + // break; + // case 4: + // //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; + // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; + // break; + // case 5: + // //groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; + // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; + // break; + // } + //} + if (input.Interval < 5) + { + string sql = string.Format(@"SELECT r.`equid` as Equid,{3} +,{1} +FROM `DS_Point_History` ph +INNER JOIN `Tb_RealData` r ON ph.id=r.id +WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} +GROUP BY r.`equid`,dates", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions, groupStr); + + string sqlResult = string.Empty; + //if (input.PageIndex > 0 && input.PageSize > 0) + //{ + // sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); + //} + //else + //{ + // sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); + //} + sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); + //string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); + string sqlCount = string.Empty; + using var conn = __contextDB.Database.GetDbConnection(); + if (conn.State == ConnectionState.Closed) + { + conn.Open(); + } + using var cmd = conn.CreateCommand(); + cmd.CommandText = sqlResult; + cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); + cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); + using var reader = await cmd.ExecuteReaderAsync(); + DataTable dt = new DataTable(); + dt.Load(reader); + + foreach (DataRow row in dt.Rows) + { + var createTimeObj = row["dates"]; + if (createTimeObj == null) + { + continue; + } + if (DateTime.TryParse(createTimeObj.ToString(), out DateTime tm)) + { + if (input.Interval > 0) + { + switch (input.Interval) + { + case 1: + //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; + //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:50:00')"; + if (tm.Minute % 5 != 0) + { + continue; + } + break; + case 2: + //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; + if (tm.Minute % 10 != 0) + { + continue; + } + break; + case 3: + //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; + if (tm.Minute % 30 != 0) + { + continue; + } + break; + case 4: + //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; + //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; + if (tm.Minute != 0) + { + continue; + } + break; + case 5: + //groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; + //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; + if (tm.Minute != 0) + { + continue; + } + break; + } + } + } + else + { + continue; + } + + var dic = new Dictionary { }; + var equipObj = row["Equid"]; + dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); + + + dic.Add("CreateTime", createTimeObj == null ? "" : createTimeObj.ToString()); + foreach (var realData in realDatas) + { + var colObj = row[realData.Id.ToString()]; + dic.Add(realData.Id.ToString(), colObj == null ? "" : colObj.ToString()); + } + result.Data.Add(dic); + } + #region 获取数据总个数 + sqlCount = result.Data.Count().ToString(); + if (input.PageIndex > 0 && input.PageSize > 0) + { + result.Data = result.Data.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList(); + } + cmd.CommandText = sqlCount; + var totalCount = cmd.ExecuteScalar(); + if (totalCount != null) + { + result.TotalCount = int.Parse(totalCount.ToString()); + } + #endregion + } + else if (input.Interval == 5) //按照天进行计算 + { + var dspointdatas = await __contextDB.DsPointHistory.Where(x => realDataIds.Contains(x.Id) && x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime).ToListAsync(); + var st = input.EndTime - input.StartTime; + result.TotalCount = input.EquipIds.Count * st.Days + 1; + + int c = 0; + int end = 0; + int start = (input.PageIndex - 1) * input.PageSize; + if (dspointdatas == null || dspointdatas.Count == 0) + { + end = 0; + } + else if(input.PageIndex > 0 && input.PageSize > 0) + { + end = input.PageIndex * input.PageSize - 1; + } + else + { + end = dspointdatas.Count - 1; + } + foreach (var equ in input.EquipIds) + { + + while (input.EndTime.Date >= input.StartTime.Date) + { + if (start <= c && c <= end) + { + var dic = new Dictionary { }; + + dic.TryAdd("Equid", equ.ToString()); + dic.TryAdd("CreateTime", input.EndTime.Date.ToStringYMD24HMS()); + foreach (var realData in realDatas) + { + var value = dspointdatas.Where(x => x.Id == realData.Id && x.CreateTime >= input.EndTime.Date && x.CreateTime < input.EndTime.Date.AddDays(1)).OrderByDescending(x => x.CreateTime).FirstOrDefault(); + if(value != null) + { + dic.TryAdd("CreateTime", value.CreateTime.ToStringYMD24HMS()); + } + dic.TryAdd(realData.Id.ToString(), value?.Value.ToString()); + } + + result.Data.Add(dic); + } + input.EndTime = input.EndTime.Date.AddDays(-1); + c++; + } + } + if (result.Data.Count == 0) + { + result.TotalCount = 0; + } + + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEquipHistorysV02", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + public async Task>> GetEquipHistorysV02(GetEquipHistoryModel input) + { + var result = new ResultPageModel> { Data = new List> { } }; + try + { + if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) + { + return result; + } + var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); + + + + var contextOptions = new DbContextOptionsBuilder() + .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; + using var __contextDB = new WeiCloudDBContext(contextOptions); + + var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new + { + t.Id, + t.Equid, + t.Descname + }).AsNoTracking().ToListAsync(); + realDatas = realDatas.OrderBy(d => d.Descname).ToList(); + var realDataIds = realDatas.Select(t => t.Id).ToList(); + StringBuilder sbCol = new StringBuilder(); + for (var i = 0; i < realDatas.Count(); i++) + { + var realData = realDatas[i]; + sbCol.Append("SUM(IF(ph.id = ").Append(realData.Id).Append(",ph.`Value`,0)) AS '").Append(realData.Id).Append("',"); + } + string otherConditions = string.Empty; + string groupStr = "ph.`CreateTime` as dates "; + if (input.Interval > 0) + { + switch (input.Interval) + { + case 1: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; + break; + case 2: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; + break; + case 3: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; + break; + case 4: + otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; + break; + case 5: + groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; + break; + } + } + if (input.Interval < 5) + { + string sql = string.Format(@"SELECT r.`equid` as Equid,{3} +,{1} +FROM `DS_Point_History` ph +INNER JOIN `Tb_RealData` r ON ph.id=r.id +WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} +GROUP BY r.`equid`,dates", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions, groupStr); + + string sqlResult = string.Empty; + if (input.PageIndex > 0 && input.PageSize > 0) + { + sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); + } + else + { + sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); + } + + string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); + + using var conn = __contextDB.Database.GetDbConnection(); + if (conn.State == ConnectionState.Closed) + { + conn.Open(); + } + using var cmd = conn.CreateCommand(); + cmd.CommandText = sqlResult; + cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); + cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); + using var reader = await cmd.ExecuteReaderAsync(); + DataTable dt = new DataTable(); + dt.Load(reader); + + foreach (DataRow row in dt.Rows) + { + var dic = new Dictionary { }; + var equipObj = row["Equid"]; + dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); + var createTimeObj = row["dates"]; + dic.Add("CreateTime", createTimeObj == null ? "" : createTimeObj.ToString()); + foreach (var realData in realDatas) + { + var colObj = row[realData.Id.ToString()]; + dic.Add(realData.Id.ToString(), colObj == null ? "" : colObj.ToString()); + } + result.Data.Add(dic); + } + #region 获取数据总个数 + cmd.CommandText = sqlCount; + var totalCount = cmd.ExecuteScalar(); + if (totalCount != null) + { + result.TotalCount = int.Parse(totalCount.ToString()); + } + #endregion + } + else if (input.Interval == 5) //按照天进行计算 + { + var dspointdatas = await __contextDB.DsPointHistory.Where(x => realDataIds.Contains(x.Id) && x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime).ToListAsync(); + var st = input.EndTime - input.StartTime; + result.TotalCount = input.EquipIds.Count * st.Days + 1; + + int c = 0; + int end = 0; + int start = (input.PageIndex - 1) * input.PageSize; + if (dspointdatas == null || dspointdatas.Count == 0) + { + end = 0; + } + else if (input.PageIndex > 0 && input.PageSize > 0) + { + end = input.PageIndex * input.PageSize - 1; + } + else + { + end = dspointdatas.Count - 1; + } + foreach (var equ in input.EquipIds) + { + + while (input.EndTime.Date >= input.StartTime.Date) + { + if (start <= c && c <= end) + { + var dic = new Dictionary { }; + + dic.TryAdd("Equid", equ.ToString()); + dic.TryAdd("CreateTime", input.EndTime.Date.ToStringYMD24HMS()); + foreach (var realData in realDatas) + { + var value = dspointdatas.Where(x => x.Id == realData.Id && x.CreateTime >= input.EndTime.Date && x.CreateTime < input.EndTime.Date.AddDays(1)).OrderByDescending(x => x.CreateTime).FirstOrDefault(); + if (value != null) + { + dic.TryAdd("CreateTime", value.CreateTime.ToStringYMD24HMS()); + } + dic.TryAdd(realData.Id.ToString(), value?.Value.ToString()); + } + + result.Data.Add(dic); + } + input.EndTime = input.EndTime.Date.AddDays(-1); + c++; + } + } + if (result.Data.Count == 0) + { + result.TotalCount = 0; + } + + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper("GetEquipHistorysV02", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs new file mode 100644 index 0000000..3f5243b --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs @@ -0,0 +1,380 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Services.Report +{ + public class EnergyConsumService: IEnergyConsumService + { + private readonly WeiCloudDBContext _context; + private readonly WeiCloudAirDBContext _airContext; + private readonly ILogger _logger; + public EnergyConsumService(WeiCloudDBContext context, WeiCloudAirDBContext airContext, ILogger logger) + { + _context = context; + _airContext = airContext; + _logger = logger; + } + public double GetEnergyConsumSum(List equipIds, DateTime startTime, DateTime endTime, int eqType) + { + double sum = 0; + + if (eqType == 1 || eqType == 5) + { + var _ammeterDwQuery = _airContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + #region 电 + var ammeterDwQuery = from ammeterDw in _ammeterDwQuery + join tm in _airContext.Times on ammeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = ammeterDw.AmParm003 ?? 0 + }; + + ammeterDwQuery = ammeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + + #endregion + sum += ammeterDwQuery.Sum(t => t.Consum); + } + else if (eqType == 2) + { + var _gasMeterDwQuery = _airContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + #region 气 + var gasMeterDwQuery = from gasMeterDw in _gasMeterDwQuery + join tm in _airContext.Times on gasMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = gasMeterDw.GmParm002 ?? 0 + }; + gasMeterDwQuery = gasMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + #endregion + sum += gasMeterDwQuery.Sum(t => t.Consum); + } + else if (eqType == 3) + { + var _waterMeterDw = _airContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + #region 水 + var waterMeterDwQuery = from waterMeterDw in _waterMeterDw + join tm in _airContext.Times on waterMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = waterMeterDw.WmParm002 ?? 0 + }; + waterMeterDwQuery = waterMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + + #endregion + sum += waterMeterDwQuery.Sum(t => t.Consum); + } + else if (eqType == 4) + { + var _heatMeterDw = _airContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + #region 热 + var heatMeterDwQuery = from heatMeterDw in _heatMeterDw + join tm in _airContext.Times on heatMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = heatMeterDw.HmParm001 ?? 0 + }; + heatMeterDwQuery = heatMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + #endregion + sum += heatMeterDwQuery.Sum(t => t.Consum); + } + return sum; + } + + /// + /// 计算能耗 + /// + /// + /// + /// + /// + /// 间隔单位1-分,2-时,3-日,4-月,5-年 + /// + public async Task> GetRunEnergyConsum(List equipIds, DateTime startTime, DateTime endTime, double interval, int intervalUnit) + { + var startYear = startTime.Year; + var startMonth = startTime.Month; + var startDay = startTime.Day; + var startHour = startTime.Hour; + + var endYear = endTime.Year; + var endMonth = endTime.Month; + var endDay = endTime.Day; + var endHour = endTime.Hour; + + #region 电 + var _ammeterDwQuery = _airContext.TbAmmeterDw.AsQueryable(); + var _waterMeterDw = _airContext.TbWaterMeterDw.AsQueryable(); + var _gasMeterDwQuery = _airContext.TbGasMeterDw.AsQueryable(); + var _heatMeterDw = _airContext.TbHeatMeterDw.AsQueryable(); + if (equipIds != null && equipIds.Count() > 0) + { + _ammeterDwQuery = _ammeterDwQuery.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + _waterMeterDw = _waterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + _gasMeterDwQuery = _gasMeterDwQuery.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + _heatMeterDw = _heatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); + } + var ammeterDwQuery = from ammeterDw in _ammeterDwQuery + join tm in _airContext.Times on ammeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = ammeterDw.AmParm003 + }; + + ammeterDwQuery = ammeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + var ammeterDwItems = ammeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new + { + Year = t.Key.Year, + Month = t.Key.Month, + Day = t.Key.Day, + Hour = t.Key.Hour, + Fulldatetime = t.Key.Fulldatetime, + Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) + }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); + #endregion + #region 水 + var waterMeterDwQuery = from waterMeterDw in _waterMeterDw + join tm in _airContext.Times on waterMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = waterMeterDw.WmParm002 + }; + waterMeterDwQuery = waterMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + + var waterMeterDwItems = waterMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new + { + Year = t.Key.Year, + Month = t.Key.Month, + Day = t.Key.Day, + Hour = t.Key.Hour, + Fulldatetime = t.Key.Fulldatetime, + Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) + }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); + #endregion + #region 气 + var gasMeterDwQuery = from gasMeterDw in _gasMeterDwQuery + join tm in _airContext.Times on gasMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = gasMeterDw.GmParm002 + }; + gasMeterDwQuery = gasMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + var gasMeterDwItems = gasMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new + { + Year = t.Key.Year, + Month = t.Key.Month, + Day = t.Key.Day, + Hour = t.Key.Hour, + Fulldatetime = t.Key.Fulldatetime, + Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) + }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); + #endregion + #region 热 + var heatMeterDwQuery = from heatMeterDw in _heatMeterDw + join tm in _airContext.Times on heatMeterDw.Parm001 equals tm.Id + select new + { + Year = tm.Year, + Month = tm.Month, + Day = tm.Day, + Hour = tm.Hour, + Fulldatetime = tm.Fulldatetime, + Consum = heatMeterDw.HmParm001 + }; + heatMeterDwQuery = heatMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); + var heatMeterDwItems = heatMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new + { + Year = t.Key.Year, + Month = t.Key.Month, + Day = t.Key.Day, + Hour = t.Key.Hour, + Fulldatetime = t.Key.Fulldatetime, + Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) + }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); + #endregion + var time = startTime; + + var result = new List(); + int maxCount = 100; + int count = 0; + do + { + if (time > DateTime.Now) + { + break; + } + if (count > maxCount) + { + break; + } + count++; + + var timeStartYear = time.Year; + var timeStartMonth = time.Month; + var timeStartDay = time.Day; + var timeStartHour = time.Hour; + #region 截止时间 + DateTime _endTime; + if (intervalUnit == 1) + { + _endTime = time.AddMinutes(interval); + } + else if (intervalUnit == 2) + { + _endTime = time.AddHours(interval); + } + else if (intervalUnit == 3) + { + _endTime = time.AddDays(interval); + } + else if (intervalUnit == 4) + { + _endTime = time.AddMonths((int)Math.Round(interval)); + } + else + { + _endTime = time.AddYears((int)Math.Round(interval)); + } + var timeEndYear = _endTime.Year; + var timeEndMonth = _endTime.Month; + var timeEndDay = _endTime.Day; + var timeEndHour = _endTime.Hour; + #endregion + double ammeterDw = 0; + double waterMeterDw = 0; + double gasMeterDw = 0; + double heatMeterDw = 0; + if (_endTime > endTime) + { + var _ammeterDwItems = ammeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); + var _waterMeterDwItems = waterMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); + var _gasMeterDwItems = gasMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); + var _heatMeterDwItems = heatMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); + + ammeterDw = _ammeterDwItems.Sum(t => t.Consum); + waterMeterDw = _waterMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Water; + gasMeterDw = _gasMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Gas; + heatMeterDw = _heatMeterDwItems.Sum(t => t.Consum); + } + else + { + var _ammeterDwItems = ammeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); + var _waterMeterDwItems = waterMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); + var _gasMeterDwItems = gasMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); + var _heatMeterDwItems = heatMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); + + ammeterDw = _ammeterDwItems.Sum(t => t.Consum); + waterMeterDw = _waterMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Water; + gasMeterDw = _gasMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Gas; + heatMeterDw = _heatMeterDwItems.Sum(t => t.Consum); + } + + + result.Add(new RunEnergyConsumItemModel + { + Year = timeStartYear, + Month = timeStartMonth, + Day = timeStartDay, + Hour = timeStartHour, + Consum = Math.Round(ammeterDw + waterMeterDw + gasMeterDw + heatMeterDw, 2) + }); + time = _endTime; + } while (time <= endTime); + return result; + } + + + /// + /// 获取设备分组 通过menuId + /// + /// + /// + /// + /// + public async Task> GetEquipmentGroupByMenuId(List groups, int eqType, long menuId) + { + var groupParentIds = await _context.EquipmentGroupMenuShip.Where(x => groups.Select(t => t.Id).Contains(x.Groupid) && x.Menuid == menuId).Select(x => x.Groupid).ToListAsync(); + List list = new List(); + foreach (var pid in groupParentIds) + { + var gr = groups.Where(x => x.Id == pid && x.Itemtype == eqType).FirstOrDefault(); + if (gr?.Id > 0) + { + var rest = GetSons(groups, pid); + list.AddRange(rest); + } + } + return list; + } + /// + /// 获取父节点的孩子 + /// + /// + /// + /// + private IEnumerable GetSons(IList list, long Fid) + { + var query = list.Where(p => p.Id == Fid).ToList(); + var list2 = query.Concat(GetSonList(list, Fid)); + return list2; + } + /// + /// 递归子孩子的子孩子 + /// + /// + /// + /// + private IEnumerable GetSonList(IList list, long Fid) + { + var query = list.Where(p => p.Parentid == Fid).ToList(); + return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.Id))); + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs new file mode 100644 index 0000000..22a4cb0 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.Report +{ + public interface IDataSourceCoreService + { + Task GetDataSource(long dataSourceId); + Task> GetDataSource_v1(JObject input); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs new file mode 100644 index 0000000..9d7ac97 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.Report +{ + public interface IDataSourceV02Service + { + //Task> GetDataSourceData(GetDataSourceDataModel input); + Task>> GetDataTables(); + Task> GetEnergyConsum(QueryDataSourceEnergyConsumModel input); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs new file mode 100644 index 0000000..2c5bcb1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Report; + +namespace WeiCloud.Core.Services.Report +{ + public interface IDataSourceV03Service + { + Task>> GetEquipHistorys(GetEquipHistoryModel input); + Task>> GetEquipHistorysV02(GetEquipHistoryModel input); + Task>> GetEquipHistorysV03(GetEquipHistoryModel input); + Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds); + Task> GetHistorys(long projectId, DateTime queryTime, List pointIds); + Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds, short intervalType); + Task> GetIntervalMaxMinHistorys(ProjectInfo projectInfo, DateTime startTime, DateTime endTime, List pointIds); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs new file mode 100644 index 0000000..083c147 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.LogicModels.InfoModels; + +namespace WeiCloud.Core.Services.Report +{ + public interface IEnergyConsumService + { + double GetEnergyConsumSum(List equipIds, DateTime startTime, DateTime endTime, int eqType); + Task> GetRunEnergyConsum(List equipIds, DateTime startTime, DateTime endTime, double interval, int intervalUnit); + Task> GetEquipmentGroupByMenuId(List groups, int eqType, long menuId); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs new file mode 100644 index 0000000..f906481 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs @@ -0,0 +1,76 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class StandarParamsCoreService: IStandarParamsCoreService + { + private readonly WeiCloudDBContext _cloudContext; + private readonly WeiCloudAirDBContext _context; + private readonly ILogger _logger; + private readonly IDictionaryService _dictionaryService; + private readonly WeiCloudDBUserCenterContext _userCenterContext; + + public StandarParamsCoreService(IDictionaryService dictionaryService,WeiCloudAirDBContext context, WeiCloudDBContext cloudContext, ILogger logger, WeiCloudDBUserCenterContext userCenterContext) + { + _cloudContext = cloudContext; + _context = context; + _logger = logger; + _dictionaryService = dictionaryService; + _userCenterContext = userCenterContext; + } + /// + /// 根据id查询标准点表信息 + /// + /// 标准点表id + /// 标准点表信息 + public async Task GetStandarParam(int id) + { + return _userCenterContext.StandarParam.TagWith("SubDB").FirstOrDefault(t => t.Id == id); + } + public async Task> GetStandarParam() + { + StandarParam standar = new StandarParam(); + try + { + var result = _dictionaryService.GetValue(standar.GetType().Name); + var list = result.Values.ToList(); + return await Task.FromResult(list); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetStandarParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + throw; + } + + } + public async Task> GetStandarParamByAllKes(string[] keys) + { + List standar = new List(); + try + { + var result = _dictionaryService.GetValue(new StandarParam().GetType().Name, keys).Select(d => d.Value).ToList(); + if (result != null) + { + standar = result.Where(d => d != null && d.Id > 0).ToList(); + } + return await Task.FromResult(standar); + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetStandarParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + throw; + } + + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs new file mode 100644 index 0000000..87d8ba2 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public class SteamHeatCalculateService: ISteamHeatCalculateService + { + /*蒸汽热量=蒸汽流量(t/s)*1000 *比热(KJ/Kg .°C)*温差(°C)/潜热(KJ/Kg) + 做一个公共函数,传参数(蒸汽流量,蒸汽出温度,进水温度) + 汽化潜热的比焓值:2258. 2kJ/kg + */ + private readonly WeiCloudDBUserCenterContext _context; + public SteamHeatCalculateService(WeiCloudDBUserCenterContext context) + { + _context = context; + + } + public async Task CalculateSteamHeat(double steamFlow, double steamOutTemperature, double waterInTemperature) + { + double steamHeat = 0; + double temp = (int)Math.Round(steamOutTemperature / 10.0) * 10; + var spec =await _context.SpecificHeatCapacity.Where(d => d.Temperature == temp).FirstOrDefaultAsync(); + if (spec == null) + { + return steamHeat; + } + if ((steamOutTemperature - waterInTemperature) <= 0) + { + return steamHeat; + } + steamHeat = steamFlow*1000 * spec.SpecificHeat * (steamOutTemperature - waterInTemperature) / 2258.2; + steamHeat = Math.Round(steamHeat, 2); + return steamHeat; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs new file mode 100644 index 0000000..949af36 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs @@ -0,0 +1,11 @@ +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Tenant; + +namespace WeiCloud.Core.Services.Tenement +{ + public interface ITenantEMSService + { + Task> SendHttpRequest(TenantSendMsgDto payload, string accessKey, string accessSecret, string url); + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs new file mode 100644 index 0000000..9677167 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs @@ -0,0 +1,73 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.Tenant; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services.Tenement +{ + public class TenantEMSService : ITenantEMSService + { + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + private readonly IConfiguration _configuration; + public TenantEMSService( + IHttpClientFactory httpClientFactory, + ILogger logger, + IConfiguration configuration) + { + _httpClientFactory = httpClientFactory; + _logger = logger; + _configuration = configuration; + } + /// + /// 发送短信 + /// + /// + /// + /// + /// + /// + public async Task> SendHttpRequest(TenantSendMsgDto payload, string accessKey, string accessSecret, string url) + { + //AccessKey:anxiao 秘钥:ZrhSAF#2025 + + using var client = _httpClientFactory.CreateClient(); + + var ts = DateTime.Now.ToString("yyyyMMddHHmm"); + var accessSign = MD5Helper.getMd5Hash($"{accessKey}{accessSecret}{ts}"); + + var jsonStr = JsonConvert.SerializeObject(payload); + var contentBytes = Encoding.UTF8.GetBytes(jsonStr); + var content = new ByteArrayContent(contentBytes); + content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + using var request = new HttpRequestMessage(HttpMethod.Post, url) + { + Content = content + }; + request.Headers.Add("AccessKey", accessKey); + request.Headers.Add("AccessSign", accessSign); + + using var response = await client.SendAsync(request); + + if (response.IsSuccessStatusCode) + { + var detail = await response.Content.ReadAsStringAsync(); + _logger.LogError("发送短信成功: {Status} | {Body}", response.StatusCode, detail); + return ApiResult.IsSuccess(true); + } + + var detail1 = await response.Content.ReadAsStringAsync(); + + _logger.LogError("发送短信失败: {Status} | {Body}", response.StatusCode, detail1); + return ApiResult.IsFail("发送短信失败"); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs new file mode 100644 index 0000000..6ed116c --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Utils; + +namespace WeiCloud.ProConfiguration.Service +{ + public class UserGroupsGainCoreService : IUserGroupsGainCoreService + { + private readonly IListService _listService; + private readonly IDictionaryService _dictionaryService; + public UserGroupsGainCoreService(IListService listService, IDictionaryService dictionaryService) + { + _listService = listService; + _dictionaryService = dictionaryService; + } + + public async Task deleteUserGroupsInfo(string[] keys) + { + + try + { + UserGroups userGroups = new UserGroups(); + _dictionaryService.DeleteValue(userGroups.GetType().Name, keys); + return await Task.FromResult(1); + } + catch (Exception ex) + { + + throw; + } + } + + public async Task PushUserGroupsToRedis(UserGroups userGroups) + { + try + { + _dictionaryService.PushValue(userGroups.GetType().Name, userGroups.Id.ToString(), userGroups); + + return await Task.FromResult(1); + } + catch (Exception) + { + + throw; + } + } + public async Task GetUserGroupsModelById(long id) + { + try + { + UserGroups group = new UserGroups(); + group = _dictionaryService.GetValue(group.GetType().Name)[id.ToString()]; + return await Task.FromResult(group); + } + catch (Exception) + { + + throw; + } + } + public async Task> GetAllUserGroupsRedis() + { + UserGroups group = new UserGroups(); + var result = _dictionaryService.GetValue(group.GetType().Name); + var list = result.Values.ToList(); + return await Task.FromResult(list); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs new file mode 100644 index 0000000..b9d8574 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs @@ -0,0 +1,88 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.UserCenter; + +namespace WeiCloud.Core.Services +{ + public class UserProjectPermissionsCoreService : IUserProjectPermissionsCoreService + { + private readonly IDictionaryService _dictionaryService; + public UserProjectPermissionsCoreService(IDictionaryService dictionaryService) + { + _dictionaryService = dictionaryService; + } + /// + /// 获取当前用户权限 + /// + /// + /// + /// + public async Task GetCurrentUserPermission(string userRoleId, string userGroupId) + { + var permission = new CurrentUserPermissionModel { }; + + var userRole = _dictionaryService.GetValue(typeof(UserRoles).Name, userRoleId.ToString()); + if (userRole.Isusing == 0) + { + return permission; + } + permission.RoleId = userRole.Id; + permission.RoleName = userRole.Rolename; + permission.RoleCode = userRole.Rolecode; + var userGroup = _dictionaryService.GetValue(typeof(UserGroups).Name, userGroupId); + if (userGroup != null) + { + permission.OwerId = userGroup.Ownerid; + } + + return await Task.FromResult(permission); + } + /// + /// 获取当前用户权限 + /// + /// + /// + public async Task GetCurrentUserPermission(string userId) + { + var permission = new CurrentUserPermissionModel { }; + var user = _dictionaryService.GetValue(typeof(Users).Name, userId.ToString()); + if (user == null || user.Userrole == null || user.Userrole == 0) + { + return permission; + } + + var userRole = _dictionaryService.GetValue(typeof(UserRoles).Name, user.Userrole.ToString()); + if (userRole.Isusing == 0) + { + return permission; + } + permission.RoleId = userRole.Id; + permission.RoleName = userRole.Rolename; + permission.RoleCode = userRole.Rolecode; + if (user.Usergroup != 0) + { + var userGroup = _dictionaryService.GetValue(typeof(UserGroups).Name, user.Usergroup.ToString()); + if (userGroup != null) + { + permission.OwerId = userGroup.Ownerid; + } + } + + return await Task.FromResult(permission); + } + public async Task> GetAllGroupPressRedis() + { + UserProjectPermissions group = new UserProjectPermissions(); + var result = _dictionaryService.GetValue(group.GetType().Name); + var list = result.Values.ToList(); + return await Task.FromResult(list); + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs new file mode 100644 index 0000000..5021969 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs @@ -0,0 +1,639 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Core.Common; +using WeiCloud.Core.EnumTools; +using WeiCloud.Entity.LogicModels; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Utils; +using WeiCloud.Entity.Context.UserCenter; +using Microsoft.EntityFrameworkCore; +using System.Diagnostics; + +namespace WeiCloud.Core.Services +{ + public class UserProjectPressRedisTreeCoreService: WeiCloud.Core.BaseCore.Grain, IUserProjectPressRedisTreeCoreService + { + private readonly WeiCloudDBUserCenterContext _userContext; + private readonly WeiCloudDBContext _context; + private readonly IDictionaryService _dictionaryService; + private List constIdList = new List(); + private List constPressIdList = new List(); + private readonly ILogger _logger; + + public UserProjectPressRedisTreeCoreService(WeiCloudDBContext context,WeiCloudDBUserCenterContext userContext, IDictionaryService dictionaryService, ILogger logger) + { + _context = context; + _userContext = userContext; + _dictionaryService = dictionaryService; + _logger = logger; + } + /// + /// 获取redis中的菜单权限拼接串 + /// + /// 角色id + /// 权限拼接串 + private string GetUserPermRedisByUserId(string roleid) + { + string returnStr = string.Empty; + UserPermissions userPerm = new UserPermissions(); + var userPermissions = _dictionaryService.GetValue(userPerm.GetType().Name)[roleid]; + if (userPermissions != null) + { + returnStr = userPermissions.Permisscodes; + } + else + { + returnStr = string.Empty; + } + return returnStr; + } + private List GetPermissionsRedis() + { + List list = new List(); + Permissions press = new Permissions(); + var data = _dictionaryService.GetValue(press.GetType().Name); + list = data.Values.ToList(); + return list; + } + private Users GetUsersRedis(string userId) + { + Users users = new Users(); + users = _dictionaryService.GetValue(users.GetType().Name, userId.ToString()); + return users; + } + /// + /// 获取用户的菜单权限菜单id拼接串 + /// + /// 用户id + /// 用户的菜单权限菜单id拼接串 + public async Task GetUserRolePress() + { + //登录者角色code + string code = CurrentContext.GetContext().RoleCode; + long userId = CurrentContext.GetContext().UserId; + string userPressStr = string.Empty; + StringBuilder build = new StringBuilder(); + try + { + //超级管理员权限 + if (code == SysBaseCodeMeta.AdminCode) + { + var press = GetPermissionsRedis(); + if (press == null || press.Count == 0) + { + var mysqlPress = (from p in _userContext.Permissions select p).ToList(); + if (mysqlPress != null && mysqlPress.Count > 0) + { + press = mysqlPress; + } + } + if (press != null && press.Count > 0) + { + foreach (Permissions p in press) + { + build.Append(p.Id.ToString() + ","); + } + userPressStr = build.ToString(); + } + } + //不是超级管理员 + else + { + var users = GetUsersRedis(userId.ToString()); + if (users != null && users.Userrole > 0) + { + //获取登录者的菜单权限 + userPressStr = GetUserPermRedisByUserId(users.Userrole.ToString()); + } + //redis读取不到权限,则数据库读取 + if (string.IsNullOrEmpty(userPressStr)) + { + var userPress = (from u in _userContext.Users + join p in _userContext.UserPermissions + on u.Userrole equals p.Roleid + where u.Userrole > 0 && u.Id == userId + select p).FirstOrDefault(); + if (userPress != null && !string.IsNullOrEmpty(userPress.Permisscodes)) + { + userPressStr = userPress.Permisscodes; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetUserRolePress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + //throw; + } + return await Task.FromResult(userPressStr); + } + public async Task GetUserRolePress(long? userId, string code) + { + //登录者角色code + //string code = CurrentContext.GetContext().RoleCode; + //long userId = CurrentContext.GetContext().UserId; + string userPressStr = string.Empty; + StringBuilder build = new StringBuilder(); + try + { + //超级管理员权限 + if (code == SysBaseCodeMeta.AdminCode) + { + var press = GetPermissionsRedis(); + if (press == null || press.Count == 0) + { + var mysqlPress = (from p in _userContext.Permissions select p).ToList(); + if (mysqlPress != null && mysqlPress.Count > 0) + { + press = mysqlPress; + } + } + if (press != null && press.Count > 0) + { + foreach (Permissions p in press) + { + build.Append(p.Id.ToString() + ","); + } + userPressStr = build.ToString(); + } + } + //不是超级管理员 + else + { + var users = GetUsersRedis(userId.ToString()); + if (users != null && users.Userrole > 0) + { + //获取登录者的菜单权限 + userPressStr = GetUserPermRedisByUserId(users.Userrole.ToString()); + } + //redis读取不到权限,则数据库读取 + if (string.IsNullOrEmpty(userPressStr)) + { + var userPress = (from u in _userContext.Users + join p in _userContext.UserPermissions + on u.Userrole equals p.Roleid + where u.Userrole > 0 && u.Id == userId + select p).FirstOrDefault(); + if (userPress != null && !string.IsNullOrEmpty(userPress.Permisscodes)) + { + userPressStr = userPress.Permisscodes; + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetUserRolePress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + //throw; + } + return await Task.FromResult(userPressStr); + } + /// + /// 根据数据权限信息组织登录者的数据权限 + /// + /// 用户组id + /// 项目id拼接串 + /// 建筑物id拼接串 + /// 组织好的数据权限 + private ProAndConstPression SetUserGroupProPress(long? userGroupId, string projestStr, string constStr) + { + ProAndConstPression pression = new ProAndConstPression(); + //int res = 0; + List projectIds = new List(); + List constIds = new List(); + try + { + if (!string.IsNullOrEmpty(projestStr) && !string.IsNullOrEmpty(constStr)) + { + string[] arrProject = projestStr.Split(','); + string[] arrConst = constStr.Split(','); + //项目 + foreach (string s in arrProject) + { + long id = 0; + long.TryParse(s, out id); + if (id > 0) + { + projectIds.Add(id); + } + } + //建筑物 + foreach (string s in arrConst) + { + long cid = 0; + long.TryParse(s, out cid); + if (cid > 0) + { + constIds.Add(cid); + } + } + } + if (projectIds != null && projectIds.Count > 0 && constIds != null && constIds.Count > 0) + { + constPressIdList = constPressIdList.Union(constIds).Distinct().ToList(); + var constAll = (from c in _context.ConstructionInfo + where c.Projectid != null && projectIds.Contains((long)c.Projectid) + select new ConstructionInfo + { + Id = c.Id, + Projectid = c.Projectid, + Constarea = c.Constarea, + Constcode = c.Constcode, + Constcount = c.Constcount, + Constinfo = c.Constinfo, + }).ToList(); + var projects = _userContext.ProjectInfo.Where(p => p.State == 1 && projectIds.Contains(p.Id)).AsNoTracking().ToList(); + var tree = (from p in projects + select new ProAndConstTree + { + Id = p.Id, + Code = p.Projectcode, + Label = p.Projectname, + Projectid = p.Id, + Type = 0, + Children = GetConstInfoByParentId(0, p.Id, constIds, constAll, false) + }).ToList(); + if (tree != null && tree.Count() > 0 && userGroupId > 0) + { + pression.UserGroupId = (long)userGroupId; + pression.ProjectIds = projectIds; + pression.ConstIds = constPressIdList; + pression.ProAndConstTree = tree; + //res = PushProtPermssionToRedis(pression); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "SetUserGroupProPress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + throw; + } + return pression; + } + private UserRoles GetUsersRoleRedis(string roleId) + { + UserRoles role = new UserRoles(); + role = _dictionaryService.GetValue(role.GetType().Name, roleId.ToString()); + return role; + } + private List GetAllConstructionInfoRedis() + { + ConstructionInfo construction = new ConstructionInfo(); + var result = _dictionaryService.GetValue(construction.GetType().Name); + var list = result.Values.ToList(); + + return list; + } + private List GetAllConstructionInfoRedis(string hashId) + { + ConstructionInfo construction = new ConstructionInfo(); + var result = _dictionaryService.GetValue(hashId); + var list = result.Values.ToList(); + return list; + } + private List GetAllProjectRedis() + { + ProjectInfo project = new ProjectInfo(); + var result = _dictionaryService.GetValue(project.GetType().Name); + var list = result.Values.ToList(); + + return list; + } + /// + /// 获取子建筑物递归方法 + /// + /// + /// + /// + /// + /// + /// + private List GetConstInfoByParentId(long parentId, long projectId, List constId, List constList, bool isNote) + { + List conSmpleList = new List(); + conSmpleList = (from c in constList + where c.Projectid == projectId && + c.Parentid == parentId + && (parentId == 0 ? constId.Contains(c.Id) : true) + orderby c.Constcode + select new ProAndConstTree + { + Id = c.Id, + Code = c.Constcode, + Label = c.Constinfo, + Projectid = projectId, + Type = 1, + Children = GetConstInfoByParentId(c.Id, projectId, constId, constList, false) + }).ToList(); + if (conSmpleList != null && conSmpleList.Count > 0) + { + var listid = (from c in conSmpleList select c.Id).ToList(); + if (listid != null && listid.Count > 0) + { + constPressIdList = constPressIdList.Union(listid).ToList(); + } + } + return conSmpleList; + } + /// + /// 根据项目id和父节点获取建筑物的集合(递归) + /// + /// 父id + /// 项目id + /// 建筑物id + /// 建筑物树 + private List GetConstInfoByParentId(long parentId, long projectId, List constList) + { + List conSmpleList = new List(); + if (constList == null || constList.Count() == 0) + { + return conSmpleList; + } + ////逻辑根建筑物去掉 + //if (parentId == 0) + //{ + // var constInfo = (from c in constList + // where (int)c.Projectid == projectId + // && c.Parentid == 0 && c.Isusing == 1 + // select c).FirstOrDefault(); + // if (constInfo != null && constInfo.Id > 0) + // { + // parentId = constInfo.Id; + // } + //} + conSmpleList = (from c in constList + where c.Projectid == projectId && + c.Parentid == parentId + orderby c.Constcode + select new ProAndConstTree + { + Id = c.Id, + Code = c.Constcode, + Label = c.Constinfo, + Projectid = projectId, + Type = 1, + Children = GetConstInfoByParentId(c.Id, projectId, constList) + }).ToList(); + if (conSmpleList != null && conSmpleList.Count > 0) + { + var idList = (from c in conSmpleList select c.Id).ToList(); + if (idList != null && idList.Count > 0) + { + //存储用户的建筑物id集合 + constIdList = constIdList.Union(idList).ToList(); + } + } + return conSmpleList; + } + /// + /// 获取登录者的数据权限树状结构 + /// + /// 用户id + /// 权限集合 + public async Task GetProIdAndConstPressTreeByUserId(long userId) + { + ProAndConstPression pression = new ProAndConstPression(); + List pressList = new List(); + List projectId = new List(); + List constId = new List(); + try + { + //读取redis中用户信息 + var user = GetUsersRedis(userId.ToString()); + //redis中的用户信息为空则读取mysql中的用户信息 + if (user == null) + { + var mysqlUser = (from u in _userContext.Users where u.Id == userId select u).FirstOrDefault(); + if (mysqlUser != null) + { + user = mysqlUser; + } + } + if (user != null && user.Userrole > 0) + { + //读redis中的角色信息 + var role = GetUsersRoleRedis(user.Userrole.ToString()); + //redis中的角色信息为空则读mysql + if (role == null) + { + var mysqlRole = (from r in _userContext.UserRoles where r.Id == user.Userrole select r).FirstOrDefault(); + if (mysqlRole != null) + { + role = mysqlRole; + } + } + //超级管理员要查询所有权限 + if (role != null && role.Rolecode == SysBaseCodeMeta.AdminCode)//超级管理员 + { + var projectList = (from p in _userContext.ProjectInfo where p.State == 1 select p).AsNoTracking().Select(t => new ProjectInfo + { + Id = t.Id, + Projectcode = t.Projectcode, + Projectname = t.Projectname, + Engabb = t.Engabb + }).ToList(); + var projectIds = projectList.Select(t => t.Id).ToList(); + //redis建筑物集合 + List constInfo = new List { }; + //var constInfo = GetAllConstructionInfoRedis(); + var typeNameConstructionInfo = typeof(ConstructionInfo).Name; + foreach (var project in projectList) + { + var _constInfo = GetAllConstructionInfoRedis($"{project.Engabb}_{typeNameConstructionInfo}"); + if (_constInfo != null && _constInfo.Count() > 0) + { + constInfo.AddRange(_constInfo); + } + } + //List constInfo = null; + //redis中没有建筑物信息则读取 + if (constInfo == null || constInfo.Count == 0) + { + var mysqlConstInfo = (from c in _context.ConstructionInfo + where c.Projectid != null && projectIds.Contains((long)c.Projectid) + select new ConstructionInfo + { + Id = c.Id, + Constinfo = c.Constinfo, + Parentid = c.Parentid, + Constcode = c.Constcode, + Projectid = c.Projectid, + Constarea = c.Constarea, + Constcount = c.Constcount, + Consttype = c.Consttype, + Latitude = c.Latitude, + Longitude = c.Longitude, + Isshow = c.Isshow, + Isusing = c.Isusing, + Unicode = c.Unicode, + }).ToList(); + if (mysqlConstInfo != null && mysqlConstInfo.Count > 0) + { + constInfo = mysqlConstInfo; + } + } + if (projectList != null && projectList.Count > 0) + { + pressList = (from p in projectList + //where p.State == 1 + select new ProAndConstTree + { + Id = p.Id, + Code = p.Projectcode, + Label = p.Projectname, + Projectid = p.Id, + Type = 0, + Children = GetConstInfoByParentId(0, p.Id, constInfo) + }).ToList(); + } + //获取用户的建筑物id集合 + if (pressList != null && pressList.Count > 0) + { + var idList = (from p in pressList select p.Id).ToList(); + if (idList != null && idList.Count > 0) + { + projectId = idList; + } + } + pression.UserGroupId = 0; + pression.ProjectIds = projectId; + pression.ConstIds = constIdList; + pression.ProAndConstTree = pressList; + } + //读取redis中设置的权限 + else + { + //redis中的用户组权限读取 + pression = _dictionaryService.GetValue(pression.GetType().Name, user.Usergroup.ToString()); + //redis中的数据为空则读mysql中的 + if (pression == null) + { + var mysqlPress = (from p in _userContext.UserProjectPermissions where p.Groupid == user.Usergroup select p).FirstOrDefault(); + if (mysqlPress != null && !string.IsNullOrEmpty(mysqlPress.Projectpermiss) && !string.IsNullOrEmpty(mysqlPress.Constpermiss)) + { + var mysqlPressData = SetUserGroupProPress(user.Usergroup, mysqlPress.Projectpermiss, mysqlPress.Constpermiss); + if (mysqlPressData != null) + { + pression = mysqlPressData; + } + } + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProIdAndConstPressTreeByUserId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + throw; + } + return await Task.FromResult(pression); + } + + public async Task GetProIdAndConstPressTreeByUserId(CurrentUser currentUser) + { + ProAndConstPression pression = new ProAndConstPression(); + List pressList = new List(); + List projectId = new List(); + List constId = new List(); + try + { + //超级管理员要查询所有权限 + if (currentUser.RoleCode == SysBaseCodeMeta.AdminCode)//超级管理员 + { + var projectList = (from p in _userContext.ProjectInfo where p.State == 1 select p).AsNoTracking().Select(t => new ProjectInfo + { + Id = t.Id, + Projectcode = t.Projectcode, + Projectname = t.Projectname + }).ToList(); + var projectIds = projectList.Select(t => t.Id).ToList(); + //redis建筑物集合 + var constInfo = GetAllConstructionInfoRedis(); + //redis中没有建筑物信息则读取 + if (constInfo == null || constInfo.Count == 0) + { + var mysqlConstInfo = (from c in _context.ConstructionInfo + where c.Projectid != null && projectIds.Contains((long)c.Projectid) + select new ConstructionInfo + { + Id = c.Id, + Constinfo = c.Constinfo, + Parentid = c.Parentid, + Constcode = c.Constcode, + Projectid = c.Projectid, + Constarea = c.Constarea, + Constcount = c.Constcount, + Consttype = c.Consttype, + Latitude = c.Latitude, + Longitude = c.Longitude, + Isshow = c.Isshow, + Isusing = c.Isusing, + Unicode = c.Unicode, + }).ToList(); + if (mysqlConstInfo != null && mysqlConstInfo.Count > 0) + { + constInfo = mysqlConstInfo; + } + } + + if (projectList != null && projectList.Count > 0) + { + pressList = (from p in projectList + //where p.State == 1 + select new ProAndConstTree + { + Id = p.Id, + Code = p.Projectcode, + Label = p.Projectname, + Projectid = p.Id, + Type = 0, + Children = GetConstInfoByParentId(0, p.Id, constInfo) + }).ToList(); + } + //获取用户的建筑物id集合 + if (pressList != null && pressList.Count > 0) + { + var idList = (from p in pressList select p.Id).ToList(); + if (idList != null && idList.Count > 0) + { + projectId = idList; + } + } + pression.UserGroupId = 0; + pression.ProjectIds = projectId; + pression.ConstIds = constIdList; + pression.ProAndConstTree = pressList; + } + //读取redis中设置的权限 + else + { + //redis中的用户组权限读取 + pression = _dictionaryService.GetValue(pression.GetType().Name, currentUser.UserGroupId.ToString()); + //redis中的数据为空则读mysql中的 + if (pression == null) + { + var mysqlPress = (from p in _userContext.UserProjectPermissions where p.Groupid == currentUser.UserGroupId select p).FirstOrDefault(); + if (mysqlPress != null && !string.IsNullOrEmpty(mysqlPress.Projectpermiss) && !string.IsNullOrEmpty(mysqlPress.Constpermiss)) + { + var mysqlPressData = SetUserGroupProPress(currentUser.UserGroupId, mysqlPress.Projectpermiss, mysqlPress.Constpermiss); + if (mysqlPressData != null) + { + pression = mysqlPressData; + } + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProIdAndConstPressTreeByUserId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); + throw; + } + return await Task.FromResult(pression); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs new file mode 100644 index 0000000..e592257 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs @@ -0,0 +1,247 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Entity.LogicModels.ConfigModels; +using WeiCloud.Entity.LogicModels.Users; +using WeiCloud.Utils; +using Microsoft.Extensions.Options; +using DotNetCore.CAP; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using WeiCloud.Utils.Common; +using System.IdentityModel.Tokens.Jwt; +using NewLife.Model; + +namespace WeiCloud.Core.Services +{ + public class UsersCoreService : IUsersCoreService + { + private readonly WeiCloudDBUserCenterContext _context; + private readonly IDictionaryService _dictionaryService; + private readonly IOptions _identityClientConfig; + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + public UsersCoreService(WeiCloudDBUserCenterContext context, IDictionaryService dictionaryService, + IOptions identityClientConfig, IHttpClientFactory httpClientFactory, + ILogger logger) + { + _context = context; + _dictionaryService = dictionaryService; + _httpClientFactory = httpClientFactory; + _identityClientConfig = identityClientConfig; + _logger = logger; + } + public async Task GetUsersByName(string name) + { + var users = _dictionaryService.GetValue(); + var user = users.FirstOrDefault(t => t.Value.Username == name).Value; + return await Task.FromResult(user); + } + public async Task GetUsersById(long id) + { + var user = _dictionaryService.GetValue(typeof(Users).Name, id.ToString()); + //var user = users.FirstOrDefault(t => t.Value.Id == id).Value; + return await Task.FromResult(user); + } + public async Task GetUsersByIdV02(long id) + { + var users = _dictionaryService.GetValue(typeof(Users).Name, new string[] { id.ToString() }); + var user = users.FirstOrDefault().Value; + return await Task.FromResult(user); + } + + public async Task GetAdmin() + { + var users = _context.Users.Where(t => t.Usercode == "admin").Select(t => new Users + { + Id = t.Id + }).FirstOrDefault(); + return await Task.FromResult(users); + } + /// + /// 获取子部门所有人员 + /// + /// + /// + /// + public async Task> GetChildDeptUsers(List userGroups, long deptId) + { + var allChildDepts = GetAllChildDepts(userGroups, deptId); + var childDeptIds = allChildDepts.Select(t => t.Id).ToList(); + if (childDeptIds.Count() > 0) + { + return await _context.Users.Where(t => t.Usergroup != null && childDeptIds.Contains((long)t.Usergroup)).AsNoTracking().ToListAsync(); + } + return new List { }; + } + private List GetAllChildDepts(List userGroups, long parentDeptId) + { + var resultItems = new List { }; + var childUserGroups = userGroups.Where(t => t.Parentid == parentDeptId); + foreach (var childUserGroup in childUserGroups) + { + resultItems.Add(childUserGroup); + var _childUserGroups = GetAllChildDepts(userGroups, childUserGroup.Id); + if (_childUserGroups.Count() > 0) + { + resultItems.AddRange(_childUserGroups); + } + } + return resultItems; + } + /// + /// 更加项目Id获取所有账号Id + /// + /// + /// + public async Task> GetUserIdsByProjectId(long projectId) + { + var userIds = new List { }; + try + { + var _project = _context.ProjectInfo.Where(t => t.Id == projectId).Select(t => new + { + t.Ownerid, + t.Id + }).FirstOrDefault(); + if (_project != null) + { + var _ownerId = _project.Ownerid; + if (_ownerId > 0) + { + var _deptIds = await _context.UserGroups.Where(t => t.Ownerid == _ownerId && t.Isusing == 1).AsNoTracking().Select(t => t.Id).ToListAsync(); + if (_deptIds.Any()) + { + userIds = await _context.Users.Where(t => t.Usergroup != null && _deptIds.Contains((long)t.Usergroup) && t.Isusing == 1).AsNoTracking().Select(t => t.Id).ToListAsync(); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); + } + return userIds; + } + /// + /// 根据token获取用户信息 + /// + /// + /// + public async Task GetUserInfoByJwt(string token) + { + UserInfoJwtViewModel result = new UserInfoJwtViewModel { }; + try + { + var url = $"{_identityClientConfig.Value.Authority}/connect/userinfo"; + var client = _httpClientFactory.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.Add("Authorization", token); + using var httpResponse = await client.SendAsync(request); + if (httpResponse.StatusCode == HttpStatusCode.OK) + { + var httpresultStr = await httpResponse.Content.ReadAsStringAsync(); + if (!string.IsNullOrEmpty(httpresultStr)) + { + result = Newtonsoft.Json.JsonConvert.DeserializeObject(httpresultStr); + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + } + return result; + } + public UserInfoJwtViewModel GetUserInfoByJwtStr(string token) + { + UserInfoJwtViewModel result = new UserInfoJwtViewModel { }; + try + { + token = token.Substring("Bearer ".Length).Trim(); + var jwtHandler = new JwtSecurityTokenHandler(); + var jwtToken = jwtHandler.ReadJwtToken(token); + + foreach (var claim in jwtToken.Claims) + { + if (claim.Type == "sub") + { + result.Sub = claim.Value; + } + else if (claim.Type == "nickname") + { + result.NickName = claim.Value; + } + else if (claim.Type == "name") + { + result.Name = claim.Value; + } + } + } + catch (Exception ex) + { + _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); + } + return result; + } + + public async Task PushUserToRedis(Users users) + { + try + { + _dictionaryService.PushValue(users.GetType().Name, users.Id.ToString(), users); + return await Task.FromResult(1); + } + catch (Exception) + { + throw; + } + } + /// + /// 修改用户密码 + /// + /// + /// + /// + public async Task ChangeUserPassword(long userId, string newPwd) + { + var result = RequestBackStatuEnum.success.Value; + try + { + //查看是否存在user + var userReal0 = (from u in _context.Users where u.Id == userId select u).FirstOrDefault(); + if (userReal0 != null) + { + DateTime createTime = (DateTime)userReal0.Createtime; + string passEndStr = createTime.ToString("HHmmss");//加密需要 + userReal0.Password = MD5Helper.getMd5Hash(newPwd + passEndStr);//新密码加盐 + userReal0.Updatetime = DateTime.Now; + _context.Entry(userReal0).State = EntityState.Modified; + //数据库中更新用户状态 + var res = await _context.SaveChangesAsync(); + //redis中更新用户状态 + + var res1 = await PushUserToRedis(userReal0); + } + else + { + result = RequestBackStatuEnum.notfound.Value; + } + } + catch (Exception ex) + { + result = RequestBackStatuEnum.badrequest.Value; + } + return result; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs new file mode 100644 index 0000000..2fb6322 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.DB; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Utils; + +namespace WeiCloud.Core.Services +{ + public class UsersGainCoreService: IUsersGainCoreService + { + private readonly IListService _listService; + private readonly IDictionaryService _dictionaryService; + public UsersGainCoreService(IListService listService, IDictionaryService dictionaryService) + { + _listService = listService; + _dictionaryService = dictionaryService; + } + public async Task PushUserToRedis(Users users) + { + try + { + _dictionaryService.PushValue(users.GetType().Name, users.Id.ToString(), users); + return await Task.FromResult(1); + } + catch (Exception) + { + throw; + } + } + public async Task GetUserModelById(long id) + { + Users users = new Users(); + users = _dictionaryService.GetValue(users.GetType().Name)[id.ToString()]; + return await Task.FromResult(users); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs new file mode 100644 index 0000000..f39c153 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Policy; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using NewLife.Log; +using Newtonsoft.Json; +using WeiCloud.Entity.LogicModels.BaseModels; +using WeiCloud.Entity.LogicModels.DataModels; + +namespace WeiCloud.Core.Services +{ + public class WorkflowService : IWorkflowService + { + private readonly string _wfUrl; + private readonly IHttpClientFactory _clientFactory; + public IConfiguration Configuration { get; } + private readonly ILogger _logger; + public WorkflowService(IHttpClientFactory clientFactory, IConfiguration configuration, ILogger logger) + { + _clientFactory = clientFactory; + _logger = logger; + Configuration = configuration; + _wfUrl = Configuration.GetSection("WF:AutoCreateWFUrl").Value; + } + /// + /// 保存工作流 + /// + /// + /// + public async Task SaveWorkflowAsync(WorkOrderAggregateDto dto) + { + var client = _clientFactory.CreateClient(); + var reqMsg = JsonConvert.SerializeObject(dto); + using (HttpContent httpContent = new StringContent(reqMsg)) + { + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + using (var httpClient = new HttpClient()) + { + httpClient.Timeout = new TimeSpan(0, 0, 10); + HttpResponseMessage resp = await httpClient.PostAsync(_wfUrl, httpContent); + string res = await resp.Content.ReadAsStringAsync(); + _logger.LogWarning($"{reqMsg}保存工作流返回结果:{res}"); + ApiResult data = JsonConvert.DeserializeObject>(res); + if (data.Code == 200) + { + return data.Data; + } + else + { + return -1; + } + } + + } + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs b/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs new file mode 100644 index 0000000..71981a5 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs @@ -0,0 +1,166 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using MySqlConnector; +using ShardingCore; +using ShardingCore.Bootstrappers; +using ShardingCore.TableExists; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using WeiCloud.Entity.Context.AirDB; +using WeiCloud.Entity.Context.ContextCore.Route; +using WeiCloud.Entity.Context.DB; + +namespace WeiCloud.Core.StartUp +{ + public class autostart : IHostedService + { + private readonly IConfiguration _config; + private readonly IServiceProvider _serviceProvider; + public autostart(IShardingBootstrapper shardingBootstrapper, IConfiguration config, IServiceProvider serviceProvider) + { + shardingBootstrapper.Start(); + _serviceProvider = serviceProvider; + _config = config; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + //var _weiCloudDBconn = _config.GetConnectionString("WeiCloudDBConn"); + //if (string.IsNullOrEmpty(_weiCloudDBconn)) + //{ + // var dbContext = _serviceProvider.GetRequiredService(); + // var n = dbContext.ConstructionInfo.Count(); + //} + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } + public static class ShardingCoreExtend + { + public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder => + { + //builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name).AddConsole(); + }); + public static IServiceCollection AddShardingCore(this IServiceCollection services, IConfiguration configuration) + { + var _weiCloudDBUserCenterConn = configuration.GetConnectionString("WeiCloudUserCenterDBConn"); + var _weiCloudAirDBConn = configuration.GetConnectionString("WeiCloudAirDBConn"); + var _weiCloudDBconn = configuration.GetConnectionString("WeiCloudDBConn"); + services.AddHostedService(); + #region EFShardingCore + if (!string.IsNullOrEmpty(_weiCloudAirDBConn)) + { + services.AddShardingDbContext() + .AddEntityConfig(op => + { + op.CreateShardingTableOnStart = false; + op.EnsureCreatedWithOutShardingTable = false; + op.UseShardingQuery((conn, builder) => + { + builder.UseMySql(conn, new MySqlServerVersion(new Version(8, 0, 19)), opts => + { + opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); + }).UseLoggerFactory(efLogger); + }); + op.UseShardingTransaction((conn, builder) => + { + builder.UseMySql(conn, new MySqlServerVersion(new Version(8, 0, 19)), opts => + { + opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); + }).UseLoggerFactory(efLogger); + }); + }).AddConfig(op => + { + op.ConfigId = typeof(WeiCloudAirDBContext).Name; + op.AddDefaultDataSource(Guid.NewGuid().ToString("n"), _weiCloudAirDBConn); + }).EnsureConfig(); + } + + + services.AddShardingDbContext().AddEntityConfig(o => + { + o.CreateShardingTableOnStart = false; + o.EnsureCreatedWithOutShardingTable = false; + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); + }).AddConfig(op => + { + op.ConfigId = typeof(WeiCloudDBContext).Name; + op.UseShardingQuery((conStr, builder) => + { + builder.UseMySql(conStr, new MySqlServerVersion(new Version(8, 0, 19)), opts => + { + opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); + }).UseLoggerFactory(efLogger);//.EnableSensitiveDataLogging(); + }); + op.UseShardingTransaction((connection, builder) => + { + builder.UseMySql(connection, new MySqlServerVersion(new Version(8, 0, 19)), opts => + { + opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); + }).UseLoggerFactory(efLogger);//.EnableSensitiveDataLogging(); + }); + + op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager()); + if (!string.IsNullOrWhiteSpace(_weiCloudDBconn)) + { + op.AddDefaultDataSource(Guid.NewGuid().ToString("n"), _weiCloudDBconn); + } + else + { + using (var conn = new MySqlConnection(_weiCloudDBUserCenterConn)) + { + conn.Open(); + string sql = "SELECT id,dbstr FROM `ProjectInfo` WHERE state=1 AND dbstr IS NOT NULL;"; +#if DEBUG + sql = "SELECT id,dbstr FROM `ProjectInfo` WHERE state=1 AND dbstr IS NOT NULL LIMIT 1;"; +#endif + MySqlCommand cmd = new MySqlCommand(sql, conn); + cmd.CommandText = sql; + MySqlDataReader rdr = cmd.ExecuteReader(); + int index = 0; + var dicSqlConn = new Dictionary(); + while (rdr.Read()) + { + if (index == 0) + { + op.AddDefaultDataSource(rdr[0].ToString(), rdr[1].ToString()); + } + else + { + dicSqlConn.Add(rdr[0].ToString(), rdr[1].ToString()); + } + index++; + } + rdr.Close(); + if (dicSqlConn.Count() > 0) + { + op.AddExtraDataSource(sp => + { + return dicSqlConn; + }); + } + } + } + }).EnsureConfig(); + #endregion + return services; + } + } +} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs new file mode 100644 index 0000000..a0129da --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Extensions.DependencyInjection; +using WeiCloud.Entity.Context.DB; +using Microsoft.EntityFrameworkCore; +using WeiCloud.Utils; +using NodaTime.TimeZones; +using WeiCloud.Utils.RedisUtil; + +namespace WeiCloud.Core.TenantDb +{ + public static class MultipleTenancyExtension + { + public static IServiceCollection AddConnectionByDatabase(this IServiceCollection services) + { + services.AddScoped((serviceProvider) => + { + var resolver = serviceProvider.GetRequiredService(); + var redis = serviceProvider.GetRequiredService(); + var prefix = resolver.GetRedisPrefix(); + return new QueueService(redis, prefix); + }); + services.AddScoped((serviceProvider) => + { + var resolver = serviceProvider.GetRequiredService(); + var redis = serviceProvider.GetRequiredService(); + var prefix = resolver.GetRedisPrefix(); + return new ListService(redis, prefix); + }); + services.AddScoped((serviceProvider) => + { + var resolver = serviceProvider.GetRequiredService(); + var redis = serviceProvider.GetRequiredService(); + var prefix = resolver.GetRedisPrefix(); + return new SetService(redis, prefix); + }); + services.AddScoped((serviceProvider) => + { + var resolver = serviceProvider.GetRequiredService(); + var redis = serviceProvider.GetRequiredService(); + var prefix = resolver.GetRedisPrefix(); + return new StringService(redis, prefix); + }); + services.AddScoped((serviceProvider) => + { + var resolver = serviceProvider.GetRequiredService(); + var redis = serviceProvider.GetRequiredService(); + var prefix = resolver.GetRedisPrefix(); + return new DictionaryService(redis, prefix); + }); + services.AddDbContext((serviceProvider, options) => + { + var resolver = serviceProvider.GetRequiredService(); + var connstr = resolver.GetConnection(); + if (!string.IsNullOrEmpty(connstr)) + { + options.UseMySql(connstr, new MySqlServerVersion(new Version(8, 0, 19))); + } + }); + + return services; + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs new file mode 100644 index 0000000..e796fc1 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs @@ -0,0 +1,75 @@ +using System; +using System.Linq; +using Microsoft.Extensions.Configuration; +using WeiCloud.Entity.Context.UserCenter; +using WeiCloud.Utils; +using WeiCloud.Utils.RedisUtil; + +namespace WeiCloud.Core.TenantDb +{ + + public interface ISqlConnectionResolver + { + string GetConnection(); + string GetRedisPrefix(); + } + + public class HttpHeaderSqlConnectionResolver : ISqlConnectionResolver + { + private readonly TenantInfo tenantInfo; + private readonly IConfiguration configuration; + + private readonly IRedisHelper _redisHelper; + public HttpHeaderSqlConnectionResolver(TenantInfo tenantInfo, IConfiguration configuration, IRedisHelper redisHelper) + { + this.tenantInfo = tenantInfo; + this.configuration = configuration; + _redisHelper = redisHelper; + } + public string GetConnection() + { + var connectionString = ""; + var _dictionaryService = new DictionaryService(_redisHelper); + var project = _dictionaryService.GetValue(HashKeyNames.ProjectInfo, new String[] { this.tenantInfo.ProjectId.ToString() }).FirstOrDefault(); + + if (project.Value != null) + { + if (string.IsNullOrEmpty(project.Value.Dbstr)) + { + throw new NullReferenceException($"项目ID {project.Key}无法找到连接串"); + } + connectionString = project.Value.Dbstr; + } + else + { + // throw new NullReferenceException($"项目ID {project.Key}无法找到连接串"); + } + return connectionString; + } + public string GetRedisPrefix() + { + var prefix = ""; + var _dictionaryService = new DictionaryService(_redisHelper); + var project = _dictionaryService.GetValue(HashKeyNames.ProjectInfo, new String[] { this.tenantInfo.ProjectId.ToString() }).FirstOrDefault(); + + if (project.Value != null) + { + if (string.IsNullOrEmpty(project.Value.Engabb)) + { + throw new NullReferenceException($"项目ID {project.Key}无法找到Redis前缀"); + } + prefix = project.Value.Engabb; + if (!project.Value.Engabb.EndsWith("_")) + { + prefix = prefix + "_"; + } + } + else + { + //throw new NullReferenceException($"项目ID {project.Key}无法找到Redis前缀"); + } + return prefix; + } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs new file mode 100644 index 0000000..47f82e6 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace WeiCloud.Core.TenantDb +{ + /// + /// 多租户信息 + /// + public class TenantInfo + { + /// + /// 项目ID + /// + public long ProjectId { get; set; } + /// + /// redis前缀 + /// + public string RedisPrefix { get; set; } + + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs new file mode 100644 index 0000000..244d501 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; +using WeiCloud.Utils; +using Microsoft.Extensions.DependencyInjection; + +namespace WeiCloud.Core.TenantDb +{ + public class TenantInfoMiddleware + { + private readonly RequestDelegate _next; + + + public TenantInfoMiddleware(RequestDelegate next) + { + _next = next; + + } + + public async Task InvokeAsync(HttpContext context) + { + var tenantInfo = context.RequestServices.GetRequiredService(); + var projectId = context.Request.Headers["ProjectId"]; + + if (string.IsNullOrEmpty(projectId)) + { + projectId = "-1"; + } + + long.TryParse(projectId, out long d); + tenantInfo.ProjectId = d; + // Call the next delegate/middleware in the pipeline + await _next(context); + } + } +} diff --git a/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj b/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj new file mode 100644 index 0000000..7ab19c4 --- /dev/null +++ b/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj @@ -0,0 +1,65 @@ + + + + netcoreapp3.1;net8.0 + + + + obj\Debug\netstandard2.0\WeiCloud.Core.xml + 1701;1702;1591 + true + + + + obj\Debug\netstandard2.0\WeiCloud.Core.xml + 1701;1702;1591 + true + + + + obj\Release\netstandard2.0\WeiCloud.Core.xml + + + + obj\Release\netstandard2.0\WeiCloud.Core.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- 2.36.2 From 1a8d1e602ef3cbf857c1d2022e38b82b5e40a788 Mon Sep 17 00:00:00 2001 From: chencaixia Date: Mon, 11 Aug 2025 11:34:15 +0800 Subject: [PATCH 2/2] =?UTF-8?q?core=20=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AliYunSms/ISmsHelperService.cs | 12 - .../AliYunSms/SmsHelperService.cs | 227 -- .../WeiCloud.Core/BaseCore/ClusterClient.cs | 24 - .../WeiCloud.Core/BaseCore/Grain.cs | 19 - .../WeiCloud.Core/BaseCore/GrainFactory.cs | 24 - .../BaseCore/IGrainWithIntegerKey.cs | 13 - .../BaseCore/ReentrantAttribute.cs | 19 - .../Calculation/CalculationformulaEnum.cs | 14 - .../Calculation/DateTimeComponetUtil.cs | 95 - .../Calculation/EngeryCalculation.cs | 180 -- .../Calculation/ExpressionFunc.cs | 120 - .../Calculation/UnitConvertUtil.cs | 126 -- .../WeiCloud.Core/Common/AppConstant.cs | 52 - .../WeiCloud.Core/Common/AxHelper.cs | 28 - .../WeiCloud.Core/Common/BaseDataCodeRule.cs | 36 - .../WeiCloud.Core/Common/CertStatus.cs | 15 - .../WeiCloud.Core/Common/ComComparer.cs | 142 -- .../WeiCloud.Core/Common/ConfigHelper.cs | 39 - .../WeiCloud.Core/Common/CurrentContext.cs | 93 - .../Common/DataSetGroup/DataSetGroupMeta.cs | 45 - .../Common/DataStream/ParamConfigConst.cs | 29 - .../DataStream/QualityMethodTypeConst.cs | 30 - .../WeiCloud.Core/Common/DataTableHelper.cs | 48 - .../WeiCloud.Core/Common/DateNowSession.cs | 49 - .../WeiCloud.Core/Common/DateTimeTools.cs | 351 --- .../Common/DatetimeJsonConverter.cs | 27 - .../EnergyConsumPlan/EnergyConsumPlanConst.cs | 18 - .../WeiCloud.Core/Common/EnthalpyBase.cs | 32 - .../Common/EquipGroup/EquipGroupConst.cs | 21 - .../Common/EquipPart/EquipPartConst.cs | 26 - .../WeiCloud.Core/Common/ExceptionHelp.cs | 27 - .../WeiCloud.Core/Common/ExpandClass.cs | 677 ------ .../WeiCloud.Core/Common/FanCmdContextVo.cs | 17 - .../WeiCloud.Core/Common/HealthLevel.cs | 166 -- .../WeiCloud.Core/Common/HolidayUtil.cs | 43 - .../WeiCloud.Core/Common/HttpClientHelper.cs | 162 -- .../StaticHttpContextExtensions.cs | 27 - .../Common/HttpContext/WEIHttpContext.cs | 19 - .../WeiCloud.Core/Common/HttpContextHelper.cs | 63 - .../WeiCloud.Core/Common/HttpHelper.cs | 875 -------- .../WeiCloud.Core/Common/HttpUtils.cs | 99 - .../WeiCloud.Core/Common/IPUtil.cs | 10 - .../Interceptor/SlowQueryInterceptor.cs | 58 - .../WeiCloud.Core/Common/LocalCache.cs | 10 - .../WeiCloud.Core/Common/MathExpandClass.cs | 21 - .../WeiCloud.Core/Common/MyAllowAnonymous.cs | 87 - .../WeiCloud.Core/Common/NumberCharConvert.cs | 10 - .../Common/PolicyContextModel.cs | 28 - .../Common/PostUniClientModel.cs | 34 - .../WeiCloud.Core/Common/QueryConst.cs | 350 --- .../Common/RandomNumberCreate.cs | 138 -- .../WeiCloud.Core/Common/RealValueMean.cs | 43 - .../Common/SteamHeatCalculate.cs | 15 - .../WeiCloud.Core/Common/Tasks/TaskManager.cs | 44 - .../EnumTools/AirQuantityEnum.cs | 33 - .../WeiCloud.Core/EnumTools/AssetTypeEnum.cs | 11 - .../WeiCloud.Core/EnumTools/CarbonEnum.cs | 33 - .../WeiCloud.Core/EnumTools/ClimNum.cs | 15 - .../WeiCloud.Core/EnumTools/ConModelEnum.cs | 30 - .../WeiCloud.Core/EnumTools/ConstTypeEnum.cs | 49 - .../EnumTools/DataSetGroupEnum.cs | 27 - .../WeiCloud.Core/EnumTools/EnergyItemEnum.cs | 43 - .../EnumTools/EngeryBillingType.cs | 47 - .../WeiCloud.Core/EnumTools/EngeryTypeEnum.cs | 46 - .../WeiCloud.Core/EnumTools/EnumHelper.cs | 40 - .../EnumTools/EnumSystemModel.cs | 34 - .../WeiCloud.Core/EnumTools/Enumeration2.cs | 131 -- .../EnumTools/EqGroupTypeEnum.cs | 99 - .../EnumTools/EquipRuningStatus.cs | 28 - .../WeiCloud.Core/EnumTools/EquipTypeEnum.cs | 220 -- .../EnumTools/FamilyDecorationEnum.cs | 85 - .../EnumTools/FauabnormalEnum.cs | 38 - .../EnumTools/FaultHandleEnum.cs | 31 - .../EnumTools/FaultStatusEnum.cs | 34 - .../EnumTools/FunPermissionEnum.cs | 13 - .../WeiCloud.Core/EnumTools/GearEnum.cs | 31 - .../EnumTools/HandWritetenEnum.cs | 13 - .../WeiCloud.Core/EnumTools/InfoApiEnum.cs | 239 -- .../WeiCloud.Core/EnumTools/IotDsEnum.cs | 29 - .../WeiCloud.Core/EnumTools/KBEnum.cs | 34 - .../WeiCloud.Core/EnumTools/MenuTypeEnum.cs | 22 - .../WeiCloud.Core/EnumTools/MsgServiceEnum.cs | 74 - .../WeiCloud.Core/EnumTools/NlogTypeNum.cs | 16 - .../WeiCloud.Core/EnumTools/NormUnitNum.cs | 18 - .../WeiCloud.Core/EnumTools/PayEnum.cs | 45 - .../WeiCloud.Core/EnumTools/ProAlarm.cs | 66 - .../EnumTools/RealDataValueTypeEnum.cs | 20 - .../EnumTools/STTargetCategoryEnum.cs | 29 - .../WeiCloud.Core/EnumTools/SafetyEnum.cs | 619 ------ .../EnumTools/StandardCoalEnum.cs | 103 - .../EnumTools/SyaConfigNameEnum.cs | 47 - .../EnumTools/SysBaseCodeMeta.cs | 111 - .../WeiCloud.Core/EnumTools/SysModuleEnum.cs | 11 - .../WeiCloud.Core/EnumTools/TaskApiEnum.cs | 16 - .../WeiCloud.Core/EnumTools/TenantPayEnum.cs | 32 - .../WeiCloud.Core/EnumTools/TimeSpanEnum.cs | 26 - .../EnumTools/UserCenterApiEnum.cs | 116 - .../EnumTools/WorkOrderProConfig.cs | 44 - .../EventBus/CapPublisherService.cs | 69 - .../WeiCloud.Core/EventBus/FaultMsgModel.cs | 51 - .../IBusinessMessageSubscriberEventBus.cs | 10 - .../EventBus/IMessageSubscriberEventBus.cs | 9 - .../EventBus/IPublisherService.cs | 22 - .../EventBus/MessageSubscriberEventBus.cs | 134 -- .../EventBus/MsgTempateEventDto.cs | 32 - .../WeiCloud.Core/EventBus/SendTypeMeta.cs | 17 - .../Extension/ExceptionExtension.cs | 36 - .../Extension/FriendlyException.cs | 18 - .../Extension/IQueryableExtensions.cs | 84 - .../Extension/TryConvertExtension.cs | 198 -- .../Filters/ApiIgnoreAttribute.cs | 14 - .../WeiCloud.Core/Filters/ApiResultFilter.cs | 75 - .../WeiCloud.Core/Filters/AuthActionFilter.cs | 175 -- .../Filters/FunctionAttribute.cs | 23 - .../Filters/GlobalExceptionsFilter.cs | 90 - .../Filters/SkipMyGlobalActionFilter.cs | 15 - .../Filters/TenantAccessCheckFilter.cs | 88 - .../Filters/ValidateFieldsMiddleware.cs | 89 - .../HostService/LogHostedService.cs | 36 - .../WeiCloud.Core/HostService/MonitorLog.cs | 56 - .../HostService/MonitorLogTaskHost.cs | 37 - .../WeiCloud.Core/LocalCache/LocalData.cs | 402 ---- .../WeiCloud.Core/ML/RegressionUtil.cs | 161 -- .../WeiCloud.Core/ML/TrainModel.cs | 18 - .../Middleware/ImgResponseMiddleware.cs | 265 --- .../WeiCloud.Core/Middleware/LogMiddleware.cs | 65 - .../MsgSocket/MsgWebSocketClientInstance.cs | 191 -- .../MsgSocket/MsgWebSocketMessageHandler.cs | 76 - .../NlogTools/INlogMessageHelper.cs | 13 - .../WeiCloud.Core/NlogTools/LoggerHelper.cs | 187 -- .../NlogTools/NlogMessageHelper.cs | 300 --- .../WeiCloud.Core/PayTool/HttpMethods.cs | 159 -- .../WeiCloud.Core/PayTool/PayRequesEntity.cs | 34 - .../WeiCloud.Core/PayTool/WeChatPayHelper.cs | 180 -- .../WeiCloud.Core/Report/ReportEnum.cs | 68 - .../RulesEngine/CronExpressionHelper.cs | 169 -- .../RulesEngine/ExecuterRepository.cs | 99 - .../RulesEngine/IExecuterContainer.cs | 12 - .../RulesEngine/IExecuterRepository.cs | 31 - .../RulesEngine/IExecuterSession.cs | 28 - .../WeiCloud.Core/RulesEngine/NRulesHelper.cs | 33 - .../RulesEngine/NulesExecuterContainer.cs | 26 - .../RulesEngine/NulesExecuterSession.cs | 30 - .../RulesEngine/RuleDefinition.cs | 23 - .../RulesEngine/RulesModels/Arithmetic.cs | 7 - .../RulesEngine/RulesModels/Energy.cs | 41 - .../RulesEngine/RulesModels/EnergyTypeEnum.cs | 25 - .../RulesEngine/RulesModels/IEntity.cs | 7 - .../RulesEngine/RulesModels/RuleConditions.cs | 54 - .../RulesEngine/RulesModels/RuleInfos.cs | 166 -- .../RulesEngine/RulesModels/RuleTypes.cs | 19 - .../Schedule/ScheduleItemConvert.cs | 82 - .../CarbonEmission/CarbonEmissionService.cs | 135 -- .../CarbonEmission/ICarbonEmissionService.cs | 14 - .../Services/ConstrInfoGainCoreService.cs | 213 -- .../IProjectParamMethodRuleCoreService.cs | 13 - .../DataStream/ISubscribePointCoreService.cs | 21 - .../Services/DataStream/ITimeSeqService.cs | 19 - .../ProjectParamMethodRuleCoreService.cs | 202 -- .../DataStream/SubscribePointCoreService.cs | 175 -- .../Services/DataStream/TimeSeqService.cs | 607 ----- .../Services/EnergySaveDwService.cs | 51 - .../Services/EquipInfoCoreService.cs | 32 - .../EquipPart/EquipPartCoreService.cs | 207 -- .../EquipPart/IEquipPartCoreService.cs | 11 - .../EquipReport/EquipStatisticsService.cs | 1961 ----------------- .../EquipReport/IEquipStatisticsService.cs | 29 - .../Services/IConstrInfoGainCoreService.cs | 18 - .../Services/IEnergySaveDwCoreService.cs | 18 - .../Services/IEquipInfoCoreService.cs | 11 - .../Services/INlogCoreService.cs | 20 - .../Services/IPermissionsGainCoreService.cs | 11 - .../Services/IProjectDWCoreService.cs | 12 - .../Services/IProjectInfoGainCoreService.cs | 15 - .../Services/IPublicFunctionService.cs | 26 - .../Services/IRealDataAnalyzeCoreService.cs | 14 - .../Services/IStandarParamsCoreService.cs | 14 - .../Services/ISteamHeatCalculateService.cs | 12 - .../Services/IUserGroupsGainCoreService.cs | 14 - .../IUserProjectPermissionsCoreService.cs | 17 - .../IUserProjectPressRedisTreeService.cs | 15 - .../Services/IUsersCoreService.cs | 20 - .../Services/IUsersGainCoreService.cs | 11 - .../Services/IWorkflowService.cs | 13 - .../WeiCloud.Core/Services/Iot/IIotService.cs | 12 - .../WeiCloud.Core/Services/Iot/IotService.cs | 73 - .../Services/Job/IJobManagerCoreService.cs | 10 - .../Services/Job/JobManagerCoreService.cs | 58 - .../Services/Message/IMessageService.cs | 12 - .../Services/Message/IMsgCenterCoreService.cs | 14 - .../Services/Message/MessageService.cs | 459 ---- .../Services/Message/MsgCenterCoreService.cs | 476 ---- .../Services/Message/UniPushInstance.cs | 41 - .../Module/IModuleManagerCoreService.cs | 13 - .../Services/Module/IModuleMenuCoreService.cs | 11 - .../Module/ModuleManagerCoreService.cs | 52 - .../Services/Module/ModuleMenuCoreService.cs | 44 - .../WeiCloud.Core/Services/Msg/IMsgService.cs | 15 - .../WeiCloud.Core/Services/Msg/MsgService.cs | 163 -- .../WeiCloud.Core/Services/NlogCoreService.cs | 299 --- .../Permission/FunPermissionCoreService.cs | 100 - .../Permission/IFunPermissionCoreService.cs | 14 - .../Services/PermissionsGainCoreService.cs | 30 - .../Services/PredicateBuilder.cs | 33 - .../Services/ProAlarm/IProAlarmService.cs | 21 - .../Services/ProAlarm/ProAlarmService.cs | 418 ---- .../Services/ProjectDWCoreService.cs | 55 - .../Services/ProjectInfoGainCoreService.cs | 46 - .../Services/PublicFunctionService.cs | 625 ------ .../Services/RealData/IRealDataCoreService.cs | 29 - .../Services/RealData/RealDataCoreService.cs | 1761 --------------- .../Services/RealDataAnalyzeCoreService.cs | 110 - .../Services/Report/DataSourceService.cs | 284 --- .../Services/Report/DataSourceV02Service.cs | 1086 --------- .../Services/Report/DataSourceV03Service.cs | 787 ------- .../Services/Report/EnergyConsumService.cs | 380 ---- .../Services/Report/IDataSourceService.cs | 16 - .../Services/Report/IDataSourceV02Service.cs | 14 - .../Services/Report/IDataSourceV03Service.cs | 21 - .../Services/Report/IEnergyConsumService.cs | 15 - .../Services/StandarParamsCoreService.cs | 76 - .../Services/SteamHeatCalculateService.cs | 41 - .../Services/Tenement/ITenantEMSService.cs | 11 - .../Services/Tenement/TenantEMSService.cs | 73 - .../Services/UserGroupsGainCoreService.cs | 73 - .../UserProjectPermissionsCoreService.cs | 88 - .../UserProjectPressRedisTreeCoreService.cs | 639 ------ .../Services/UsersCoreService.cs | 247 --- .../Services/UsersGainCoreService.cs | 37 - .../WeiCloud.Core/Services/WorkflowService.cs | 63 - .../StartUp/ShardingCoreExtend.cs | 166 -- .../TenantDb/MultipleTenancyExtension.cs | 65 - .../TenantDb/SqlConnectionResolver.cs | 75 - .../WeiCloud.Core/TenantDb/TenantInfo.cs | 22 - .../TenantDb/TenantInfoMiddleware.cs | 38 - .../WeiCloud.Core/WeiCloud.Core.csproj | 3 + 236 files changed, 3 insertions(+), 25436 deletions(-) delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs delete mode 100644 WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs diff --git a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs deleted file mode 100644 index 49525fc..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/ISmsHelperService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.BaseModels; -namespace WeiCloud.Core.AliYunSms -{ - public interface ISmsHelperService - { - SmsResposeModel SendSms(string phoneNumber, string templateParams, int type); - SmsResposeModel SendSms(string phoneNumber, string signName, string templateCode, string templateParams, string accessKeyId, string accessSecret, string host); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs b/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs deleted file mode 100644 index bc02d06..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/AliYunSms/SmsHelperService.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using System.Collections.Generic; -using Aliyun.Acs.Core; -using Aliyun.Acs.Core.Profile; -using Aliyun.Acs.Core.Exceptions; -using Aliyun.Acs.Core.Http; -using Newtonsoft.Json; -using WeiCloud.Entity.LogicModels.BaseModels; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using AlibabaCloud.SDK.Dysmsapi20170525.Models; - -namespace WeiCloud.Core.AliYunSms -{ - public class SmsHelperService : ISmsHelperService - { - private readonly string _accessKeyId; - private readonly string _accessSecret; - private readonly string _regionId; - - /// - /// 发送单条短信 - /// - private readonly string _sendSms_signName; - private readonly string _sendSms_templateCode; - private readonly string _sendOrderSms_signName; - private readonly string _sendOrderSms_templateCode; - private readonly string _sendKnowledgeSms_signName; - private readonly string _sendKnowledgeSms_templateCode; - private readonly string _sendFaultSms_signName; - private readonly string _sendFaultSms_templateCode; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - /// - /// 发送多条短信 待扩充 - /// - private readonly string _sendBatchSms_signName; - private readonly string _sendBatchSms_templateCode; - - public SmsHelperService(IConfiguration configuration, ILogger logger) - { - _logger = logger; - _configuration = configuration; - _accessKeyId = _configuration["AliYunSms:API_KEY"]; - _accessSecret = _configuration["AliYunSms:SECRET_KEY"]; - _regionId = _configuration["AliYunSms:REGION_ID"]; - _sendSms_signName = _configuration["AliYunSms:SendSms:SIGN_NAME"]; - _sendSms_templateCode = _configuration["AliYunSms:SendSms:TEMPLATE_CODE"]; - - - _sendOrderSms_signName = _configuration["AliYunSms:SendOrderSms:SIGN_NAME"]; - _sendOrderSms_templateCode = _configuration["AliYunSms:SendOrderSms:TEMPLATE_CODE"]; - _sendKnowledgeSms_signName = _configuration["AliYunSms:SendKnowledgeSms:SIGN_NAME"]; - _sendKnowledgeSms_templateCode = _configuration["AliYunSms:SendKnowledgeSms:TEMPLATE_CODE"]; - _sendFaultSms_signName = _configuration["AliYunSms:SendFaultSms:SIGN_NAME"]; - _sendFaultSms_templateCode = _configuration["AliYunSms:SendFaultSms:TEMPLATE_CODE"]; - - //_sendBatchSms_signName = _configuration["AliYunSms:SendBatchSms:SIGN_NAME"]; - //_sendBatchSms_templateCode = _configuration["AliYunSms:SendBatchSms:TEMPLATE_CODE"]; - } - /// - /// 发送单条短信 - /// - /// 手机号 - /// 模板内容JsonString - /// 0验证码 1工单2知识库 3报警 - /// SmsResponse 实体 Code=OK为成功 其他为失败 - public SmsResposeModel SendSms(string phoneNumber, string templateParams, int type) - { - try - { - AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config - { - // 您的AccessKey ID - AccessKeyId = _accessKeyId, - // 您的AccessKey Secret - AccessKeySecret = _accessSecret, - }; - // 访问的域名 - config.Endpoint = "dysmsapi.aliyuncs.com"; - var client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config); - - string tempcode = ""; - string param = ""; - string signname = ""; - switch (type) - { - case 0: - tempcode = _sendSms_templateCode; - signname = _sendSms_signName; - param = templateParams; - - break; - case 1: //工单 - tempcode = _sendOrderSms_templateCode; - signname = _sendOrderSms_signName; - param = templateParams; - - break; - case 2://知识库 - tempcode = _sendKnowledgeSms_templateCode; - signname = _sendKnowledgeSms_signName; - param = templateParams; - break; - case 3://报警 - tempcode = _sendFaultSms_templateCode; - signname = _sendFaultSms_signName; - param = templateParams; - - break; - case 4://计划管理 待扩充 - - break; - case 5: //智能诊断 - tempcode = _sendFaultSms_templateCode; - signname = _sendFaultSms_signName; - param = templateParams; - break; - default: - tempcode = _sendSms_templateCode; - signname = _sendSms_signName; - param = templateParams; - break; - } - _logger.LogWarning($"发送短信参数为{phoneNumber} {signname} {tempcode} {templateParams}"); - var sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest - { - PhoneNumbers = phoneNumber, - SignName = signname, - TemplateCode = tempcode, - TemplateParam = templateParams, - }; - - SendSmsResponse sendSms = client.SendSms(sendSmsRequest); - if (sendSms.Body.Code.ToLower() == "ok") - { - return new SmsResposeModel - { - Message = sendSms.Body.Message, - Code = "OK" - }; - } - else - { - return new SmsResposeModel - { - Message = "Http错误," + sendSms.Body.Message, - Code = "HTTP_ERROR" - }; - } - } - catch (Exception ex) - { - - return new SmsResposeModel - { - Message = "Http错误," + ex.Message, - Code = "HTTP_EXCEPT" - }; - } - } - /// - /// 发送短信 - /// - /// - /// - /// - /// - /// - /// - /// - /// - public SmsResposeModel SendSms(string phoneNumber, string signName, string templateCode, string templateParams, string accessKeyId, string accessSecret, string host) - { - try - { - AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config - { - // 您的AccessKey ID - AccessKeyId = accessKeyId, - // 您的AccessKey Secret - AccessKeySecret = accessSecret, - }; - // 访问的域名 - config.Endpoint = host; - var client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config); - - - _logger.LogWarning($"发送短信参数为{phoneNumber} {signName} {templateCode} {templateParams}"); - var sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest - { - PhoneNumbers = phoneNumber, - SignName = signName, - TemplateCode = templateCode, - TemplateParam = templateParams, - }; - - SendSmsResponse sendSms = client.SendSms(sendSmsRequest); - if (sendSms.Body.Code.ToLower() == "ok") - { - return new SmsResposeModel - { - Message = sendSms.Body.Message, - Code = "OK" - }; - } - else - { - return new SmsResposeModel - { - Message = "Http错误," + sendSms.Body.Message, - Code = "HTTP_ERROR" - }; - } - } - catch (Exception ex) - { - - return new SmsResposeModel - { - Message = "Http错误," + ex.Message, - Code = "HTTP_EXCEPT" - }; - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs deleted file mode 100644 index 68255ba..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ClusterClient.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.BaseCore -{ - public interface IClusterClient - { - T GetGrain(long guiId) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey; - } - public class ClusterClient: IClusterClient - { - private readonly IServiceProvider _serviceProvider; - public ClusterClient(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public T GetGrain(long guiId) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - var serviceInstence = _serviceProvider.GetService(typeof(T)); - return (T)serviceInstence; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs deleted file mode 100644 index 7973b8d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/Grain.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Core.Common; - -namespace WeiCloud.Core.BaseCore -{ - public class Grain - { - public GrainFactory GrainFactory { get; set; } - public CurrentContext CurrentContext { get; set; } - public Grain() { } - //public Grain(GrainFactory GrainFactory, CurrentContext CurrentContext) - //{ - // this.GrainFactory = GrainFactory; - // this.CurrentContext = CurrentContext; - //} - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs deleted file mode 100644 index 5b5101c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/GrainFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Core.Common; - -namespace WeiCloud.Core.BaseCore -{ - //public interface GrainFactory - //{ - // T GetGrain(long guid) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey; - //} - public class GrainFactory //: GrainFactory - { - private readonly IServiceProvider _serviceProvider; - public GrainFactory(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public T GetGrain(long guid) where T : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - return (T)_serviceProvider.GetService(typeof(T)); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs deleted file mode 100644 index 49ebe58..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/IGrainWithIntegerKey.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Autofac.Extras.DynamicProxy; -using MonitorAopLog.Util; -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.BaseCore -{ - [Intercept(typeof(FunctionInterceptor))] - public interface IGrainWithIntegerKey - { - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs deleted file mode 100644 index 7bb0c79..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/BaseCore/ReentrantAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.BaseCore -{ - - public class ReentrantAttribute: Attribute - { - } - public class AlwaysInterleave : Attribute - { - - } - [AttributeUsage(AttributeTargets.Property)] - public class AutowiredAttribute : Attribute - { - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs deleted file mode 100644 index 689ef94..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Calculation/CalculationformulaEnum.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Calculation -{ - public enum CalculationformulaEnum - { - COP = 1, - WTF = 5, - WTFcw = 6, - η = 7 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs deleted file mode 100644 index 2ebb2a9..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Calculation/DateTimeComponetUtil.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.DataAnalysis; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Calculation -{ - public class DateTimeComponetUtil - { - static List<(DateTime, DateTime)> SplitTimePeriod(DateTime start, DateTime end, IntervalType intervalType) - { - List<(DateTime, DateTime)> result = new List<(DateTime, DateTime)>(); - DateTime currentStart = start; - - while (currentStart < end) - { - DateTime currentEnd; - - switch (intervalType) - { - case IntervalType.Hour: - currentEnd = currentStart.AddHours(1).AddSeconds(-1); - break; - case IntervalType.Day: - currentEnd = currentStart.AddDays(1).AddSeconds(-1); - break; - case IntervalType.Month: - currentEnd = currentStart.AddMonths(1).AddSeconds(-1); - break; - case IntervalType.Year: - currentEnd = new DateTime(currentStart.Year, 12, 31).AddDays(1).AddSeconds(-1); - break; - default: - throw new ArgumentException("Invalid interval type"); - } - - if (currentEnd > end) - { - currentEnd = end; - } - - result.Add((currentStart, currentEnd)); - currentStart = currentEnd.AddSeconds(1); - } - - return result; - } - public static (DateTime, DateTime, List<(DateTime, DateTime)>, IntervalType) GetStartAndEndTime(TimeDimenEnum timeDimen, QueryTimeModel queryTime, IntervalType intervalType = IntervalType.Hour) - { - DateTime startTime = DateTime.MinValue; - DateTime endTime = DateTime.MaxValue; - List<(DateTime, DateTime)> timePeriods = new List<(DateTime, DateTime)>(); - switch (timeDimen) - { - case TimeDimenEnum.Day: - startTime = queryTime.StartTime; - endTime = queryTime.StartTime.AddHours(24).AddTicks(-1); - break; - case TimeDimenEnum.Month: - startTime = new DateTime(queryTime.StartTime.Year, queryTime.StartTime.Month, 1); - endTime = startTime.AddMonths(1).AddTicks(-1); - break; - case TimeDimenEnum.Year: - startTime = new DateTime(queryTime.StartTime.Year, 1, 1); - endTime = startTime.AddYears(1).AddTicks(-1); - break; - case TimeDimenEnum.CustomRange: - startTime = queryTime.StartTime; - endTime = queryTime.EndTime.AddDays(1).AddTicks(-1); - var timeDiff = (endTime - startTime).TotalHours; - if (0 < timeDiff && timeDiff <= 24 * 7)//按小时统计 - { - intervalType = IntervalType.Hour; - } - else if (24 * 7 < timeDiff && timeDiff <= 24 * 30)//按天统计 - { - intervalType = IntervalType.Day; - } - else if (24 * 30 < timeDiff && timeDiff <= 24 * 365)//按月统计 - { - intervalType = IntervalType.Month; - } - else - { - intervalType = IntervalType.Year; - } - break; - } - - timePeriods = SplitTimePeriod(startTime, endTime, intervalType); - return (startTime, endTime, timePeriods, intervalType); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs deleted file mode 100644 index 69facfa..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Calculation/EngeryCalculation.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Eventing.Reader; -using System.Text; - -namespace WeiCloud.Core.Calculation -{ - public static class EngeryCalculation - { - private static readonly float q = (float)34.9 * 1000; //天然气热值,单位为:kJ/m3 - - /// - /// 直燃机能效计算 - /// - /// 热量表取值 - /// 燃气消耗量 - /// 耗电量 - /// 能效值 - public static double DirectFireEngeryCalcu(double? heat, double? gas, double? elect) - { - double engValue = 0; - //单位:无量纲(kW/kW),供热时取%,供冷时取实际值,如1.23(取小数点后两位)其中为热量表取值,单位应为kW(瞬时量)/ kWh(累计量),首页取值可以取1小时的累计量;其中V为天燃气消耗量(m3 / h),q为天然气热值,单位为kJ / m3,暂取34.9×103 kJ / m3;Wp为直燃机耗电量, 单位应为kW(瞬时量)/ kWh(累计量)。 - var qg = gas * q / 3600; - if ((qg + elect) > 0) - { - var data = heat / (qg + elect); - if (data > 0) - { - engValue = (double)data; - } - } - return engValue; - } - /// - /// 冷热泵、冷却泵、冷却塔能效 - /// - /// 热量表取值 - /// 电耗 - /// 能效值 - public static double CoolHotPumpEngeryCalu(double? heat, double? elect) - { - double coolhotEng = 0; - if (elect > 0 && heat > 0) - { - coolhotEng = (double)heat / (double)elect; - } - return coolhotEng; - } - /// - /// 系统能效 - /// - /// - /// - /// - /// - public static double SysEnergyEfficiency(double heat, double gas, double elect) - { - double eer = 0; - var denominator = gas * q / 3600 + elect; - if (denominator != 0) - { - eer = heat / denominator; - } - return eer; - } - - /// - /// 气-等价电 - /// - /// - /// - public static double GasConvertEquivalentElectricity(double gas) - { - return 3.355 * gas; - } - - public static double kwhToCO2 = 0.0009970; - - - /// - /// 获取温湿度焓值计算公式 - /// - /// 温度 - /// 湿度 - /// 返回的焓值结果 - /// 比较值 当大于值返回flalse 小于值返回true - /// - public static bool GetTemHumiEnthalpy(double temperature, double humidity, out double enthalpy, double equalVal = 58.46) - { - //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 - //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) - - //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; - double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; - //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) - double b = humidity / 100 * a * 100; - double c = 101300 - humidity / 100 * a * 100; - //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) - enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); - return !(enthalpy > equalVal); - } - - /// - /// 获取温湿度焓值计算公式 - /// - /// 温度 - /// 湿度 - /// 返回的焓值结果 - /// 比较值 当大于值返回flalse 小于值返回true - /// 浮动值 在浮动值区间内都是正常 - /// 1 制热 2制冷 其他 - /// - public static bool GetTemHumiEnthalpyEx(double temperature, double humidity, out double enthalpy, double equalVal = 58.46, double floatingVal = 2, int? condition = null) - { - //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 - //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) - - //夏季舒适条件(如24℃、50 % 湿度)对应的焓值约为 48 - 50 kJ / kg ; 47.9 - //冬季舒适条件(如20℃、40 % 湿度)对应的焓值约为 35 - 38 kJ / kg 。 34.91 - - - //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; - double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; - //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) - double b = humidity / 100 * a * 100; - double c = 101300 - humidity / 100 * a * 100; - //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) - enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); - if (condition == 1) //冬天是 > 焓值是舒适 否则是不舒适 - { - if (enthalpy >= (equalVal - floatingVal)) - { - return true; - } - return false; - } - else if (condition == 2)//夏天是 < 焓值是舒适 否则是不舒适 - { - if (enthalpy <= (equalVal + floatingVal)) - { - return true; - } - return false; - } - else //其他情况就是在波动区间是舒适的 非波动区间是不舒适的 - { - if (enthalpy >= (equalVal - floatingVal) && enthalpy <= (equalVal + floatingVal)) - { - return true; - } - return false; - } - - } - - - /// - /// 获取湿球温度 - /// - /// - /// - /// - public static double GetWetBulbTemp(double temperature, double humitity) - { - if (temperature == 0 && humitity == 0) - { - return 0; - } - // 湿球温度 = ((温度 + 21.82 - ((100 - 湿度) / 8.842) ^ (1 / 0.8718)) ^ 2 - (温度 - 21.82) ^ 2) / 86.88 - double d = (Math.Pow(temperature + 21.82 - Math.Pow(((100 - humitity) / 8.842), (1 / 0.8718)), 2) - Math.Pow((temperature - 21.82), 2)) / 86.88; - //湿球温度=((温度+21.82-((100-湿度)/8.842)^(1/0.8718))^2-(温度-21.82)^2)/86.88 - //(d)/86.88 - //d = (b)^2-c - // b = 温度+21.82-((100-湿度)/8.842)^(1/0.8718) - //c= (温度-21.82)^2 - //(Math.Pow(S1 + 21.82 - Math.Pow(((100 - S2) / 8.842), (1 / 0.8718)), 2) - Math.Pow((S1 - 21.82), 2)) / 86.88; - return d; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs deleted file mode 100644 index 6cca599..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Calculation/ExpressionFunc.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels; - -namespace WeiCloud.Core.Calculation -{ - public class QueryExpressionFunc - { - private List GetCSharp(GetExpressionFuncVo input) - { - var items = new List(); - if (input.FuncTypes.Contains(2)) - { - var mathFunc = new ExpressionFuncVo - { - FuncTypeName = "数学", - Functions = new List - { - new ExpressionFuncViewModel { Func="Math.Abs",Desc="获取指定数值(number)的绝对值",Syntax="Abs(number)"}, - new ExpressionFuncViewModel { Func="Math.Floor",Desc="返回小于或等于number的最大整数",Syntax="Floor(number)"}, - new ExpressionFuncViewModel { Func="Math.Ceiling",Desc="返回大于或等于number的最小整数值",Syntax="Ceiling(number)"}, - new ExpressionFuncViewModel { Func="Math.Round",Desc="将值舍入到最接近的整数或指定的小数位数",Syntax="Round(number)"}, - new ExpressionFuncViewModel { Func="Math.Sqrt",Desc="返回指定数字的平方根",Syntax="Sqrt(number)"}, - new ExpressionFuncViewModel { Func="Math.Pow",Desc="返回指定数字的指定次幂",Syntax="Pow(number)"} - } - }; - items.Add(mathFunc); - } - if (input.FuncTypes.Contains(1)) - { - var statisticsFunc = new ExpressionFuncVo - { - FuncTypeName = "统计", - Functions = new List - { - new ExpressionFuncViewModel { Func="Math.Max",Desc="返回字段(number)中的最大值",Syntax="Max(number1,number2)"}, - new ExpressionFuncViewModel { Func="Math.Min",Desc="返回字段(number)中的最小值",Syntax="Min(number1,number2)"} - } - }; - items.Add(statisticsFunc); - } - if (input.FuncTypes.Contains(3)) - { - var dateFun = new ExpressionFuncVo - { - FuncTypeName = "日期", - Functions = new List - { - new ExpressionFuncViewModel { Func="ADDDATE",Desc="计算起始日期 d 加上 n 天的日期",Syntax="ADDDATE(d,n)"}, - new ExpressionFuncViewModel { Func="ADDTIME",Desc="n 是一个时间表达式,时间 t 加上时间表达式 n",Syntax="ADDTIME(t,n)"}, - new ExpressionFuncViewModel { Func="DATE_ADD",Desc="计算起始日期 d 加上一个时间段后的日期",Syntax="DATE_ADD(d,INTERVAL expr type)"}, - new ExpressionFuncViewModel { Func="DATEDIFF",Desc="计算日期 d1->d2 之间相隔的天数",Syntax="DATEDIFF(d1,d2)"}, - new ExpressionFuncViewModel { Func="DATE_FORMAT",Desc="按表达式 f的要求显示日期 d",Syntax="DATE_FORMAT(d,f)"}, - new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, - new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, - new ExpressionFuncViewModel { Func="HOUR",Desc="返回 t 中的小时值",Syntax="HOUR(t)"}, - new ExpressionFuncViewModel { Func="MONTH",Desc="返回日期d中的月份值,1 到 12",Syntax="MONTH(t)"}, - new ExpressionFuncViewModel { Func="YEAR",Desc="返回年份,1 到 12",Syntax="YEAR(t)"} - } - }; - items.Add(dateFun); - } - return items; - } - private List GetSql(GetExpressionFuncVo input) - { - var items = new List(); - if (input.FuncTypes.Contains(1)) - { - var statisticsFunc = new ExpressionFuncVo - { - FuncTypeName = "数字", - Functions = new List - { - new ExpressionFuncViewModel { Func="FLOOR",Desc="返回小于或等于 x 的最大整数",Syntax="FLOOR(1.5)"}, - new ExpressionFuncViewModel { Func="CEIL",Desc="返回大于或等于 x 的最小整数",Syntax="CEIL(1.5)"}, - new ExpressionFuncViewModel { Func="ROUND",Desc="返回离 x 最近的整数,可选参数 y 表示要四舍五入的小数位数,如果省略,则返回整数",Syntax="ROUND(345.156, 2)"}, - new ExpressionFuncViewModel { Func="SUM",Desc="返回指定字段的总和",Syntax="SUM(Quantity)"}, - new ExpressionFuncViewModel { Func="MAX",Desc="返回字段 expression 中的最大值",Syntax="MAX(expression)"}, - new ExpressionFuncViewModel { Func="MIN",Desc="返回字段 expression 中的最小值",Syntax="MIN(expression)"}, - } - }; - items.Add(statisticsFunc); - } - if (input.FuncTypes.Contains(2)) - { - var statisticsFunc = new ExpressionFuncVo - { - FuncTypeName = "日期", - Functions = new List - { - new ExpressionFuncViewModel { Func="ADDDATE",Desc="计算起始日期 d 加上 n 天的日期",Syntax="ADDDATE(d,n)"}, - new ExpressionFuncViewModel { Func="DATE",Desc="从日期或日期时间表达式中提取日期值",Syntax="DATE()"}, - new ExpressionFuncViewModel { Func="DAY",Desc="返回日期值 d 的日期部分",Syntax="DAY(d)"}, - new ExpressionFuncViewModel { Func="HOUR",Desc="返回 t 中的小时值",Syntax="HOUR(t)"}, - new ExpressionFuncViewModel { Func="MINUTE",Desc="返回 t 中的分钟值",Syntax="MINUTE(t)"}, - new ExpressionFuncViewModel { Func="YEAR",Desc="返回年份",Syntax="YEAR(d)"}, - new ExpressionFuncViewModel { Func="MONTH",Desc="返回日期d中的月份值,1 到 12",Syntax="MONTH(d)"}, - new ExpressionFuncViewModel { Func="SECOND",Desc="返回 t 中的秒钟值,1 到 12",Syntax="SECOND(t)"}, - } - }; - items.Add(statisticsFunc); - } - return items; - } - public List GetExpressions(GetExpressionFuncVo input) - { - if (input.ProgramLanguage == 1) - { - return GetCSharp(input); - } - else if (input.ProgramLanguage == 3) - { - return GetSql(input); - } - return new List { }; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs deleted file mode 100644 index 997491d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Calculation/UnitConvertUtil.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Calculation -{ - public class UnitConvertUtil - { - /// - /// 单位转换 - /// - /// 原单位 - /// 原值 - /// 目标单位 - /// 目标值 - public static double ParamConvert(string sUnit, double sValue, string dUnit) - { - float sValue_F = Convert.ToSingle(sValue); - var r = ParamConvert(sUnit, sValue_F, dUnit); - return Convert.ToDouble(r); - } - /// - /// 单位转换 - /// - /// 原单位 - /// 原值 - /// 目标单位 - /// 目标值 - public static float ParamConvert(string sUnit, float sValue, string dUnit) - { - float realvalue = 0; - if (dUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("L/s", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue * 1000 / 3600; - } - else if (dUnit.Equals("L/s", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue * 3600 / 1000; - } - else if (dUnit.Equals("kwh", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kj", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 3600; - } - else if (dUnit.Equals("kj", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kwh", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue * 3600; - } - else if (dUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/s", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 3600; - } - else if (dUnit.Equals("m³/s", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³/h", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue * 3600; - } - else if (dUnit.Equals("MWh", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kWh", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - else if (dUnit.Equals("kt", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - else if (dUnit.Equals("km³", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("m³", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - else if (dUnit.Equals("KJ", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("J", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - else if (dUnit.Equals("GJ", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("MJ", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - //标煤千克换算吨 - else if (dUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("kg", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - //标煤吨换算千吨 - else if (dUnit.Equals("kt", StringComparison.InvariantCultureIgnoreCase) && sUnit.Equals("t", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - //标煤千吨换算兆吨 - else if (dUnit.ToLower().Equals("mt", StringComparison.InvariantCultureIgnoreCase) && sUnit.ToLower().Equals("kt", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000; - } - //标煤吨换算兆吨 - else if (dUnit.ToLower().Equals("mt", StringComparison.InvariantCultureIgnoreCase) && sUnit.ToLower().Equals("t", StringComparison.InvariantCultureIgnoreCase)) - { - realvalue = sValue / 1000000; - } - else - { - realvalue = sValue; - } - return realvalue; - } - - - - /// - /// 计算比率 - /// - /// 分子 - /// 分母 - /// 是否乘以100 - /// 保留小数位 - /// - public static decimal CalRate(decimal fenzi, decimal fenmu, bool x100 = true, int decimalPlace = 2) - { - if (x100) - { - return decimal.Round((fenmu > 0 ? fenzi / fenmu : 0) * 100, decimalPlace); - } - else - { - return decimal.Round((fenmu > 0 ? fenzi / fenmu : 0), decimalPlace); - } - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs deleted file mode 100644 index eb5d77d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/AppConstant.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core -{ - public class AppConstant - { - public static string TIMESTAMP { get => "TIMESTAMP"; private set { } } - /// - /// 采集时间和服务器时间间隔 - /// - /// - private static int alarmInterval = 15; - public static int AlarmInterval { get => GetAlarmInterval("AlarmInterval"); private set { } } - /// - /// 是否生成报警 - /// - public static bool IsGeneAlarm { get => true; private set { } } - - public static int RDHInterval { get => -5; private set { } } - - public static int GetAlarmInterval(string key) - { - if (int.TryParse(ConfigHelper.GetSectionValue(key), out alarmInterval)) - { - return alarmInterval; - } - else - { - return alarmInterval; - } - } - public static readonly Dictionary DicTimeMapId = new Dictionary(); - - #region 补漏数据 0-缺失,99-正常 - /// - /// 正常 - /// - public static readonly short EquipData_State_Normal = 99; - /// - /// 缺失 - /// - public static readonly short EquipData_State_Abnormal = 0; - /// - /// 原始数据丢失 - /// - - public static readonly short EquipData_State_LoseOriginal = 1; - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs deleted file mode 100644 index 8539798..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/AxHelper.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public static class AxHelper - { - public static string RemoveHost(string fullFile) - { - if (string.IsNullOrEmpty(fullFile)) - { - return null; - } - - string keyword = "upload"; - int index = fullFile.ToLower().IndexOf(keyword); - - // 如果找到了关键字,则截取关键字及其后面的内容 - string result = index >= 0 ? fullFile.Substring(index) : fullFile; - return result; - } - - - - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs deleted file mode 100644 index c473627..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/BaseDataCodeRule.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - /// - /// 元数据code生成规则 - /// - public static class BaseDataCodeRule - { - /// - /// 根据类型,id以及parentid获取数据的code - /// - /// 标识类型 - /// 标识数据的id - /// 标识数据的父id - /// 生成规则的code - public static string GetBaseDataCode(string type,long? id,long? parentId) - { - string returnStr = string.Empty; - string parentCode = string.Empty; - string code = string.Empty; - if (id > 0&&!string.IsNullOrEmpty(type)) - { - if (parentId > 0) - { - parentCode = String.Format("{0:D3}", parentId); - } - code= String.Format("{0:D3}", id); - returnStr = type + parentCode + code; - } - return returnStr; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs deleted file mode 100644 index 068fbb6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/CertStatus.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - /// - /// 运行状态 - /// - public static class CertStatus - { - public static bool Status { get; set; } - } - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs deleted file mode 100644 index eacb804..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/ComComparer.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -namespace WeiCloud.Core.Common -{ - public class ComComparer : IEqualityComparer - { - public bool Equals(T x, T y) - { - if (x == null || y == null) - { - return false; - } - //if (Newtonsoft.Json.JsonConvert.SerializeObject(x)?.Length== Newtonsoft.Json.JsonConvert.SerializeObject(y)?.Length) - //{ - // return true; - //} - var result = CompareType(x, y); - if (result == false) - { - var d = x; - var u = y; - } - return result; - } - - public int GetHashCode(T obj) - { - if (Object.ReferenceEquals(obj, null)) - { - return 0; - } - return HashCode(obj); - - } - - private int HashCode(T t) - { - if (Object.ReferenceEquals(t, null)) - { - return 0; - } - Type typeOne = t.GetType(); - PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) - var list = new List(); - for (int i = 0; i < pisOne.Length; i++) - { - string oneName = pisOne[i].Name; - object oneValue = pisOne[i].GetValue(t, null); - int hashvalue = oneName == null ? 0 : oneName.GetHashCode(); - list.Add(hashvalue); - } - return AllTypeValueHash(list); - - } - - private int AllTypeValueHash(List list) - { - var result = 0; - foreach (var item in list) - { - result = result ^ item; - } - return result; - } - - private bool CompareType(T oneT, T twoT) - { - if (oneT == null || twoT == null) - { - return false; - } - bool result = true;//两个类型作比较时使用,如果有不一样的就false - Type typeOne = oneT.GetType(); - Type typeTwo = twoT.GetType(); - //如果两个T类型不一样 就不作比较 - if (!typeOne.Equals(typeTwo)) { return false; } - PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) - PropertyInfo[] pisTwo = typeTwo.GetProperties(); - //如果长度为0返回false - if (pisOne.Length <= 0 || pisTwo.Length <= 0) - { - return false; - } - //如果长度不一样,返回false - if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; } - //遍历两个T类型,遍历属性,并作比较 - for (int i = 0; i < pisOne.Length; i++) - { - //获取属性名 - string oneName = pisOne[i].Name; - string twoName = pisTwo[i].Name; - //获取属性的值 - object oneValue = pisOne[i].GetValue(oneT, null); - object twoValue = pisTwo[i].GetValue(twoT, null); - //比较,只比较值类型 - if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String"))) - { - if (oneName.Equals(twoName)) - { - if (oneValue == null) - { - if (twoValue != null) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - else if (oneValue != null) - { - if (twoValue != null) - { - if (!oneValue.Equals(twoValue)) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - else if (twoValue == null) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - } - else - { - result = false; - break; - } - } - else - { - //如果对象中的属性是实体类对象,递归遍历比较 - bool b = CompareType(oneValue, twoValue); - if (!b) { result = b; break; } - } - } - return result; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs deleted file mode 100644 index e630f68..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/ConfigHelper.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace WeiCloud.Core -{ - public static class ConfigHelper - { - private static IConfiguration _configuration; - - static ConfigHelper() - { - //在当前目录或者根目录中寻找appsettings.json文件 - var fileName = "appsettings.json"; - - var directory = AppContext.BaseDirectory; - directory = directory.Replace("\\", "/"); - - var filePath = $"{directory}/{fileName}"; - if (!File.Exists(filePath)) - { - var length = directory.IndexOf("/bin"); - filePath = $"{directory.Substring(0, length)}/{fileName}"; - } - - var builder = new ConfigurationBuilder() - .AddJsonFile(filePath, false, false); - - _configuration = builder.Build(); - } - - public static string GetSectionValue(string key) - { - return _configuration.GetSection(key).Value; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs deleted file mode 100644 index 05c889e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/CurrentContext.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels; - -namespace WeiCloud.Core.Common -{ - //public interface CurrentContext - //{ - // CurrentUser GetContext(); - // void SetContext(CurrentUser currentUser); - //} - public class CurrentContext - { - private readonly IHttpContextAccessor httpContext; - public CurrentContext(IHttpContextAccessor httpContext) - { - this.httpContext = httpContext; - } - public CurrentUser GetContext() - { - CurrentUser result = null; - try - { - //var httpContext = ServiceLocator.ServiceProvider.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor; - //object currentUserStr = Orleans.Runtime.RequestContext.Get("CurrentUser"); - result = httpContext?.HttpContext?.Items["CurrentUser"] == null ? null : httpContext.HttpContext.Items["CurrentUser"] as CurrentUser; - //if (currentUserStr != null) - //{ - // return JsonConvert.DeserializeObject(currentUserStr.ToString()); - //} - } - catch (Exception ex) - { - - } - finally - { - if (result == null) - { - result = new CurrentUser { }; - } - } - - return result; - } - public void SetContext(CurrentUser currentUser) - { - try - { - if (currentUser != null) - { - //var httpContext = ServiceLocator.ServiceProvider.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor; - httpContext.HttpContext.Items["CurrentUser"] = currentUser; - //string currentUserStr = JsonConvert.SerializeObject(currentUser); - - //Orleans.Runtime.RequestContext.Set("CurrentUser", currentUserStr); - } - } - catch (Exception ex) - { - throw ex; - } - } - } - public class CurrentUser - { - public List ProjectIds { get; set; } - public List ConstIds { get; set; } - public string RoleCode { get; set; } - public List OwnerIds { get; set; } - public long UserId { get; set; } = 0; - public long UserGroupId { get; set; } - public string NickName { get; set; } - public long AdminId { get; set; } - public string Pwd { get; set; } - public string UserName { get; set; } - public string UserFullName { get; set; } - public string RoleName { get; set; } - public long RoleId { get; set; } - public string Token { get; set; } - public ProAndConstPression ProAndConstPression { get; set; } - public string WeChat { get; set; } - - public string RemoteIPAddress { get;set; } - - public long HeaderProjectId { get; set; } - - public string UserPhone { get; set; } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs deleted file mode 100644 index 706b87a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DataSetGroup/DataSetGroupMeta.cs +++ /dev/null @@ -1,45 +0,0 @@ -using MySqlX.XDevAPI.Common; -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.BasicGroup; - -namespace WeiCloud.Core.Common.DataSetGroup -{ - public static class DataSetGroupMeta - { - /// - /// 获取数据集组的标准参数代码 - /// - /// - public static List GetGroupStanderParamCodes() - { - var result = new List(); - result.Add(new GroupStanderParamCodeDto - { - Code = "ElePrice", - Name = "电价", - Unit = "元/kWh" - }); - result.Add(new GroupStanderParamCodeDto - { - Code = "WaterPrice", - Name = "水价", - Unit = "元/t" - }); - result.Add(new GroupStanderParamCodeDto - { - Code = "GasPrice", - Name = "气价", - Unit = "元/m³" - }); - result.Add(new GroupStanderParamCodeDto - { - Code = "buildArea", - Name = "建筑面积", - Unit = "㎡" - }); - return result; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs deleted file mode 100644 index 0dfddad..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/ParamConfigConst.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.DataStream -{ - public class ParamConfigConst - { - - } - public enum ParamConfigTypeEnum - { - Standard = 1, - RealData = 2, - ParamGroup = 3, - BreakOff = 4 - } - public class ParamConfigOperaConst - {//1-大于、2-大于等于、3-小于、4-小于等于 - public static Dictionary Dic = new Dictionary() { { 1, ">" }, { 2, ">=" }, { 3, "<" }, { 4, "<=" } }; - } - public enum DataStreamFrequencyUnitEnum - { - Year=6, - Month=5, - Day=4, - Hour=3 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs deleted file mode 100644 index 4c27715..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DataStream/QualityMethodTypeConst.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Const -{ - public class QualityMethodTypeConst - { - //1-大小值;2-补空值;3-正态分布;4-开箱;5-平衡;6-空值率 - public static readonly string DXZXZ = "DXZXZ"; - public static string BK = "BK"; - public static string ZTFB = "ZTFB"; - public static string KX = "KX"; - public static string PH = "PH"; - public static string KZL = "KZL"; - /// - /// 限幅滤波法(又称程序判断滤波法) - /// - public static string FTW = "FTW"; - /// - /// 中位值滤波法 - /// - public static string MFM = "MFM"; - } - public enum ProblemQualityTypeTypeEnum - { - Param = 1, - ParamGroup = 2 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs deleted file mode 100644 index d30efb5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DataTableHelper.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class DataTableHelper where T:new() - { - - - /// - /// datatable to list - /// - /// - /// - public static List ConvertToModel(DataTable dt) - { - - List ts = new List();// 定义集合 - Type type = typeof(T); // 获得此模型的类型 - string tempName = ""; - foreach (DataRow dr in dt.Rows) - { - T t = new T(); - PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性 - foreach (PropertyInfo pi in propertys) - { - tempName = pi.Name; - - if (dt.Columns.Contains(tempName)) - { - if (!pi.CanWrite) continue; - object value = dr[tempName]; - if (value != DBNull.Value) - pi.SetValue(t, value, null); - } - } - ts.Add(t); - } - - return ts; - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs deleted file mode 100644 index e11c200..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DateNowSession.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels; - -namespace WeiCloud.Core.Common -{ - public static class DateNowSession - { - #region 获取当前季节以及是否营业时间 - public static SessionAndBusiness GetSessionAndBuss(DateTime now) - { - SessionAndBusiness model = new SessionAndBusiness(); - short? session = 0; - short? bussiness = 0; - //供冷季 - var collSatar = Convert.ToDateTime(now.Year + "-" + "05-15"); - var collEnd = Convert.ToDateTime(now.Year + "-" + "09-15"); - //过渡季 - var transSatar1 = Convert.ToDateTime(now.Year + "-" + "03-15"); - var transEnd1 = Convert.ToDateTime(now.Year + "-" + "05-15"); - var transSatar2 = Convert.ToDateTime(now.Year + "-" + "09-15"); - var transEnd2 = Convert.ToDateTime(now.Year + "-" + "11-8"); - //供热季 - var hotSatar = Convert.ToDateTime(now.Year + "-" + "11-8"); - var hotEnd = Convert.ToDateTime(now.Year + "-" + "03-15"); - if (now >= collSatar && now < collEnd) - { - session = 1;//供冷季 - } - else if ((now >= transSatar1 && now < transEnd1) || (now >= transSatar2 && now < transEnd2)) - { - session = 3; //过渡季 - } - else if ((now < hotEnd) || (now >= hotSatar)) - { - session = 2;//供热季 - } - if (now.Hour >= 9 && now.Hour < 22) - { - bussiness = 1; - } - model.Session = session; - model.Business = bussiness; - return model; - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs deleted file mode 100644 index 9e03f01..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DateTimeTools.cs +++ /dev/null @@ -1,351 +0,0 @@ -using Microsoft.Extensions.Internal; -using System; -using System.Collections.Generic; -using System.Text; -using NodaTime; - -namespace WeiCloud.Core.Common -{ - public static class DateTimeTools - { - #region 获取系统当前时间的几个方法(返回时间+格式化后的时间字符串) - - /// - /// 获取系统当前时间 - /// - /// 系统当前时间 - public static DateTime GetSysDateTimeNow() - { - Instant now = NodaTime.SystemClock.Instance.GetCurrentInstant(); - var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"]; - return now.InZone(shanghaiZone).ToDateTimeUnspecified(); - } - - /// - /// 获取系统当前时间格式化字符串 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss.fff) - /// - /// 系统当前格式化的时间字符串(yyyy-MM-dd HH:mm:ss.fff) - public static string GetSysDateTimeNowStringYMD24HMSF() - { - return GetSysDateTimeNow().ToStringYMD24HMSF(); - } - - /// - /// 获取系统当前时间格式化字符串 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss.fff) - /// - /// 系统当前格式化的时间字符串(yyyy-MM-dd hh:mm:ss.fff) - public static string GetSysDateTimeNowStringYMD12HMSF(this DateTime time) - { - return GetSysDateTimeNow().ToStringYMD12HMSF(); - } - - /// - /// 获取系统当前时间格式化字符串 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss) - /// - /// 系统当前格式化的时间字符串(yyyy-MM-dd HH:mm:ss) - public static string GetSysDateTimeNowStringYMD24HMS(this DateTime time) - { - return GetSysDateTimeNow().ToStringYMD24HMS(); - } - - /// - /// 获取系统当前时间格式化字符串 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss) - /// - /// 系统当前格式化的时间字符串(yyyy-MM-dd hh:mm:ss) - public static string GetSysDateTimeNowStringYMD12HMS(this DateTime time) - { - return GetSysDateTimeNow().ToStringYMD12HMS(); - } - - /// - /// 获取系统当前时间格式化字符串 被格式化为 (yyyy-MM-dd) - /// - /// 系统当前格式化的时间字符串(yyyy-MM-dd) - public static string GetSysDateTimeNowStringYMD(this DateTime time) - { - return GetSysDateTimeNow().ToStringYMD(); - } - - #endregion - - #region DateTime 扩展几个 格式方法 - - /// - /// 时间 格式化 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss.fff) - /// - /// 被格式的时间 - /// 格式化后的时间字符串(yyyy-MM-dd HH:mm:ss.fff) - public static string ToStringYMD24HMSF(this DateTime time) - { - try - { - return time.ToString("yyyy-MM-dd HH:mm:ss.fff"); - } - catch (Exception ex) - { - return null; - } - - } - - /// - /// 时间 格式化 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss.fff) - /// - /// 被格式化时间 - /// 格式化后的时间字符串(yyyy-MM-dd hh:mm:ss.fff) - public static string ToStringYMD12HMSF(this DateTime time) - { - return time.ToString("yyyy-MM-dd hh:mm:ss.fff"); - } - - /// - /// 时间 格式化 24小时制 被格式化为 (yyyy-MM-dd HH:mm:ss) - /// - /// 被格式化时间 - /// 格式化后的时间字符串(yyyy-MM-dd HH:mm:ss) - public static string ToStringYMD24HMS(this DateTime time) - { - return time.ToString("yyyy-MM-dd HH:mm:ss"); - } - - /// - /// 时间 格式化 12小时制 被格式化为 (yyyy-MM-dd hh:mm:ss) - /// - /// 被格式化时间 - /// 格式化后的时间字符串(yyyy-MM-dd hh:mm:ss) - public static string ToStringYMD12HMS(this DateTime time) - { - return time.ToString("yyyy-MM-dd hh:mm:ss"); - } - - /// - /// 时间 格式化 被格式化为 (yyyy-MM-dd) - /// - /// 被格式化时间 - /// 连接符号 - /// 格式化后的时间字符串(yyyy-MM-dd) - public static string ToStringYMD(this DateTime time, string separator= null) - { - if (separator != null) - { - return time.ToString($"yyyy{separator}MM{separator}dd"); - } - return time.ToString("yyyy-MM-dd"); - - } - - public static string ToStringYMD(this DateTime time) - { - - return time.ToString("yyyy-MM-dd"); - - } - #endregion - - #region 获取时间戳 - - /// - /// 获取时间戳(秒) - /// - /// 秒时间戳 - public static long GetSecondTimestamp() - { - // 以1970-1-1 为时间开始 同系统当前时间的秒差值即为秒时间戳 - TimeSpan ts = GetSysDateTimeNow() - new DateTime(1970, 1, 1, 0, 0, 0, 0); - return Convert.ToInt64(ts.TotalSeconds); - } - - /// - /// 获取时间戳(毫秒) - /// - /// 毫秒时间戳 - public static long GetMilliSecondTimestamp() - { - // 以1970-1-1 为时间开始 同系统当前时间的毫秒差值即为毫秒时间戳 - TimeSpan ts = GetSysDateTimeNow() - new DateTime(1970, 1, 1, 0, 0, 0, 0); - return Convert.ToInt64(ts.TotalMilliseconds); - } - - #endregion - - #region 将一个时间戳转换为一个时间 - - /// - /// 将一个秒时间戳转换为时间格式(秒) - /// - /// 秒时间戳 - /// 转换后的时间 - public static DateTime? SecondStampToDateTime(long secondTimestamp) - { - // 做一个简单的判断 - if (secondTimestamp <= 0) - { - return null; - } - - // 以1970-1-1 为时间开始,通过计算与之的时间差,来计算其对应的时间 - DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); - dateTime = dateTime.AddSeconds(secondTimestamp).ToLocalTime(); - return dateTime; - } - - /// - /// 将一个字符串秒时间戳转换为时间格式(秒) - /// - /// 字符串秒时间戳 - /// 转换后的时间 - public static DateTime? SecondStampToDateTime(string secondTimestampStr) - { - // 如果为空,那么直接返回null - if (string.IsNullOrEmpty(secondTimestampStr)) - { - return null; - } - - // 首先将字符串时间戳转换为数字 - long secondTimestamp = 0; - long.TryParse(secondTimestampStr, out secondTimestamp); - - // 调用 - return SecondStampToDateTime(secondTimestamp); - } - - /// - /// 将一个字符串毫秒时间戳转换为时间格式(毫秒) - /// - /// 字符串毫秒时间戳 - /// 转换后的时间 - public static DateTime? MilliSecondStampToDateTime(long secondTimestamp) - { - // 做一个简单的判断 - if (secondTimestamp <= 0) - { - return null; - } - - // 以1970-1-1 为时间开始,通过计算与之的时间差,来计算其对应的时间 - DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); - dateTime = dateTime.AddMilliseconds(secondTimestamp).ToLocalTime(); - - return dateTime; - } - - /// - /// 将一个毫秒时间戳转换为时间格式(毫秒) - /// - /// 毫秒时间戳 - /// 转换后的时间 - public static DateTime? MilliSecondStampToDateTime(string milliSecondStampStr) - { - // 如果为空,那么直接返回null - if (string.IsNullOrEmpty(milliSecondStampStr)) - { - return null; - } - - // 首先将字符串时间戳转换为数字 - long milliSecondStamp = 0; - long.TryParse(milliSecondStampStr, out milliSecondStamp); - - // 调用 - return MilliSecondStampToDateTime(milliSecondStamp); - } - - #endregion - - /// - /// 获得当前某年的某一天 - /// - /// - /// - public static int GetYearDay( DateTime dateTime ) - { - return dateTime.DayOfYear; - } - /// - /// 获得一年多少天 - /// - /// - public static int GetYearDayCount(int year) - { - int count = 0; - try - { - for (int i = 1; i <= 12; i++) - { - count += DateTime.DaysInMonth(year, i); - } - return count; - } - catch (Exception ex) - { - return 365; - } - } - /// - /// 获得今年的第一天 - /// - /// - public static DateTime GetYearFirstDay() - { - DateTime dtFirstDay = new DateTime(GetSysDateTimeNow().Year, 1, 1); - return dtFirstDay; - } - /// - /// 获得今年的最后一天 - /// - /// - public static DateTime GetYearLastDay() - { - DateTime dtLastDay = new DateTime(GetSysDateTimeNow().Year, 1, 1).AddYears(1).AddDays(-1); - return dtLastDay; - } - /// - /// 将时间格式处理成 --- yyyy-MM-dd hh:00:00 - /// - /// - /// - public static DateTime? GetDateTimeCutHour(this DateTime? datetime) - { - if (datetime ==null) - { - return null; - } - return new DateTime(datetime.Value.Year,datetime.Value.Month,datetime.Value.Day,datetime.Value.Hour,0,0); - } - - - /// - /// 获取当前日期所属的季度、季度内的月份以及该月内的第几天。 - /// - /// 要判断的日期 - /// 包含季度、季度内的月份和该月内的天数的元组 - public static (int Quarter, int MonthInQuarter, int DayInMonth) GetQuarterInfo(DateTime date) - { - // 确定季度 - int quarter = (date.Month - 1) / 3 + 1; - - // 确定季度内的月份 - int monthInQuarter = (date.Month - 1) % 3 + 1; - - // 获取该月的天 - int dayInMonth = date.Day; - - return (quarter, monthInQuarter, dayInMonth); - } - - - - - // 指定周起始日的版本 - public static (DateTime Start, DateTime End) GetCurrentWeekRange(DayOfWeek startOfWeek) - { - DateTime today = DateTime.Today; - int diff = (7 + (today.DayOfWeek - startOfWeek)) % 7; - DateTime start = today.AddDays(-diff); - DateTime end = start.AddDays(6); - - return (start, end); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs deleted file mode 100644 index eb9a37d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/DatetimeJsonConverter.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace WeiCloud.Core.Common -{ - - public class DatetimeJsonConverter : JsonConverter - { - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType == JsonTokenType.String) - { - if (DateTime.TryParse(reader.GetString(), out DateTime date)) - return date; - } - return reader.GetDateTime(); - } - - public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs deleted file mode 100644 index 1d2b92c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/EnergyConsumPlan/EnergyConsumPlanConst.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.EnergyConsumPlan -{ - public class EnergyConsumPlanConst - { - } - public enum EnergyConsumPlanTypeEnum - { - Custom = 0, - Year = 1, - Month = 2, - Day = 3, - Hour = 4 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs deleted file mode 100644 index b8eb390..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/EnthalpyBase.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class EnthalpyBase - { - /// - /// 获取温湿度焓值计算公式 - /// - /// 温度 - /// 湿度 - /// 返回的焓值结果 - /// 比较值 当大于值返回flalse 小于值返回true - /// - public static double GetTemHumiEnthalpy(double temperature, double humidity) - { - //作为判断条件 当结果高于58.46的时候就停止,低于58.46的时候继续运算,当等于58.46的时候则是最合适的温湿度 - //焓值=1.01*温度+0.001*[湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100/(101300-湿度/100*(0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07)*100)*622]*(2501+1.84*温度) - - //a = 0.000004*温度^4+0.0002667*温度^3+0.0137*温度^2+0.4523*温度+6.07; - double a = 0.000004 * Math.Pow(temperature, 4) + 0.0002667 * Math.Pow(temperature, 3) + 0.0137 * Math.Pow(temperature, 2) + 0.4523 * temperature + 6.07; - //焓值=1.01*温度+0.001*[湿度/100*(a)*100/(101300-湿度/100*(a)*100)*622]*(2501+1.84*温度) - double b = humidity / 100 * a * 100; - double c = 101300 - humidity / 100 * a * 100; - //焓值=1.01*温度+0.001*[b/c*622]*(2501+1.84*温度) - var enthalpy = 1.01 * temperature + 0.001 * (b / c * 622) * (2501 + 1.84 * temperature); - return enthalpy; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs deleted file mode 100644 index 5807a0d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipGroup/EquipGroupConst.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.EquipGroup -{ - public class EquipGroupConst - { - } - /// - /// 分组能耗类型 - /// - public enum EquipGroupItemTypeEnum - { - Other = 0, - Ele = 1, - Water = 2, - Gas = 3, - Heat = 4 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs deleted file mode 100644 index 40f2b7e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/EquipPart/EquipPartConst.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.EquipPart -{ - public class EquipPartConst - { - } - public enum EquipPartApplyEnum - { - In = 1, - Out = 2, - /// - /// 外借 - /// - LentOut = 3 - } - public enum EquipPartApproveState - {//流程状态 已发起 1 已审批 7 已完成 5 已拒绝 8 - Applied = 1, - Approved = 7, - Completed = 5, - Refuse = 8 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs deleted file mode 100644 index 3d076a2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/ExceptionHelp.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public static class ExceptionHelp - { - public static int GetLineNumber(this Exception ex) - { - var line = 0; - try - { - var stackTrace = new StackTrace(ex, true); - var stackFrame = stackTrace.GetFrame(0); - line = stackFrame.GetFileLineNumber(); - } - catch (Exception innerex) - { - line = 0; - } - return line; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs deleted file mode 100644 index 472ab4a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/ExpandClass.cs +++ /dev/null @@ -1,677 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Linq; -using System.Text.RegularExpressions; -using System.Reflection; -using Org.BouncyCastle.Crypto.Agreement.Srp; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.Report; -using WeiCloud.Entity.LogicModels.HKPro; - -namespace WeiCloud.Core -{ - public static class ExpandClass - { - public static string ListToStr(this IEnumerable list, string separate = ",") - { - return string.Join(separate, list); - } - public static List StrArrayToLongArray(this string[] strList) - { - List list = new List(); - try - { - long n = 0; - foreach (var str in strList) - { - if (long.TryParse(str, out n)) - list.Add(n); - } - } - catch (Exception ex) - { - - } - return list; - } - public static List StrArrayToIntArray(this string[] strList) - { - List list = new List(); - try - { - int n = 0; - foreach (var str in strList) - { - if (int.TryParse(str, out n)) - list.Add(n); - } - } - catch (Exception ex) - { - - } - return list; - } - public static List StringToIntArray(this string strList, char splitchar) - { - List list = new List(); - try - { - var outresult = -1; - if (string.IsNullOrEmpty(strList)) - { - return new List { }; - } - var strArray = strList.Split(splitchar); - foreach (var str in strArray) - { - if (int.TryParse(str, out outresult)) - list.Add(outresult); - } - - - } - catch (Exception ex) - { - } - return list; - } - /// - /// 将字符串转为List int - /// - /// - /// - /// - public static List StringToIntList(this string str, char splitchar) - { - List list = new List(); - try - { - var outresult = -1; - if (String.IsNullOrEmpty(str)) - { - return null; - } - if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) - { - list.Add(outresult); - return list; - - } - var a = str.Split(splitchar); - for (int i = 0; i < a.Length; i++) - { - var result = -1; - int.TryParse(a[i], out result); - list.Add(result); - } - - return list; - } - catch (Exception ex) - { - return null; - } - - } - - public static List StringToStrList(this string str, char splitchar) - { - List list = new List(); - try - { - var outresult = -1; - if (String.IsNullOrEmpty(str)) - { - return null; - } - if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) - { - list.Add(outresult); - return list; - - } - var a = str.Split(splitchar); - for (int i = 0; i < a.Length; i++) - { - var result = -1; - int.TryParse(a[i], out result); - list.Add(result); - } - - return list; - } - catch (Exception ex) - { - return null; - } - - } - - - public static List StringToIntList1(this string str, char splitchar) - { - List list = new List(); - try - { - var outresult = -1; - if (String.IsNullOrEmpty(str)) - { - return null; - } - if (!str.Contains(splitchar.ToString()) && int.TryParse(str, out outresult)) - { - list.Add(outresult); - return list; - - } - var a = str.Split(splitchar); - for (int i = 0; i < a.Length; i++) - { - var result = -99; - if (int.TryParse(a[i], out result)) - { - list.Add(result); - } - - - } - - return list; - } - catch (Exception ex) - { - } - return list; - } - - - public static List StringToLongList(this string str, char splitchar) - { - List list = new List(); - try - { - long outresult = -1; - if (String.IsNullOrEmpty(str)) - { - return null; - } - if (!str.Contains(splitchar.ToString()) && long.TryParse(str, out outresult)) - { - list.Add(outresult); - return list; - - } - var a = str.Split(splitchar); - for (int i = 0; i < a.Length; i++) - { - long result = -1; - long.TryParse(a[i], out result); - list.Add(result); - } - - return list; - } - catch (Exception ex) - { - return null; - } - - } - public static List StringToLongList1(this string str, char splitchar) - { - List list = new List(); - try - { - long outresult = -1; - if (String.IsNullOrEmpty(str)) - { - return list; - } - if (!str.Contains(splitchar.ToString()) && long.TryParse(str, out outresult)) - { - list.Add(outresult); - return list; - - } - var a = str.Split(splitchar); - for (int i = 0; i < a.Length; i++) - { - long result = -1; - long.TryParse(a[i], out result); - list.Add(result); - } - - return list; - } - catch (Exception ex) - { - return null; - } - - } - public static string[] LongToStringList(this long[] str) - { - var results = new List { }; - for (var i = 0; i < str.Length; i++) - { - results[i] = str[i].ToString(); - } - return results.ToArray(); - } - public static string[] IntToStringList(this int[] str) - { - var results = new List { }; - for (var i = 0; i < str.Length; i++) - { - results[i] = str[i].ToString(); - } - return results.ToArray(); - } - /// - /// 将字符串转为string[] - /// - /// - /// - /// string[] - public static string[] StringToStringArray(this string str, char splitchar) - { - if (String.IsNullOrEmpty(str)) - { - return null; - } - if (!str.Contains(splitchar.ToString())) - { - return new string[] { str }; - } - return str.Split(splitchar); - } - public static List StringToStringList(this string str, char splitchar) - { - var result = new List { }; - if (String.IsNullOrEmpty(str)) - { - return result; - } - if (!str.Contains(splitchar.ToString())) - { - result.Add(str); - return result; - } - return str.Split(splitchar).ToList(); - } - /// - /// 判断两个字节数组是否相等 - /// - /// - /// - /// bool - public static bool BytesEquals(this byte[] b1, byte[] b2) - { - if (b1 == null || b2 == null) return false; - if (b1.Length != b2.Length) return false; - for (int i = 0; i < b1.Length; i++) - if (b1[i] != b2[i]) - return false; - return true; - } - - public static string ToLowerOnlyStart(this string str) - { - try - { - if (!string.IsNullOrEmpty(str)) - { - if (str.Length > 1) - { - return char.ToLower(str[0]) + str.Substring(1); - } - return char.ToLower(str[0]).ToString(); - } - return str; - } - catch (Exception ex) - { - return str; - } - } - -#if NETCOREAPP3_1 - public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector) - { - HashSet seenKeys = new HashSet(); - foreach (TSource element in source) - { - if (seenKeys.Add(keySelector(element))) - { - yield return element; - } - } - } -#endif - - public static double DoubleTakeRound(this double bl, int round = 0) - { - if (bl.ToString().Contains(".")) - { - return Math.Round(bl, round); - } - else - { - return bl; - } - } - - public static double? TakeRoundN(this double? b1, int round = 0) - { - if (b1 == null) - { - return null; - } - if (b1.Value.ToString().Contains(".")) - { - return Math.Round(b1.Value, round); - } - else - { - return b1; - } - } - - public static bool IsIpAddress(this string strIn) - { - try - { - if (String.IsNullOrEmpty(strIn)) - { - return false; - } - bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$"); - return b; - } - catch (Exception ex) - { - return false; - } - } - - public static bool IsIP(this string strIn) - { - try - { - if (String.IsNullOrEmpty(strIn)) - { - return false; - } - bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"); - return b; - } - catch (Exception ex) - { - return false; - } - } - - public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime) - { - return dateTime.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime - ? DateTimeOffset.MinValue - : new DateTimeOffset(dateTime); - } - /// - /// 截取一个字段中的ip:端口,失败的话返回空字符串 - /// - /// - /// - public static string ExtractIPAddressFStr(this string strIn) - { - try - { - if (string.IsNullOrEmpty(strIn)) - { - return string.Empty; - } - //@"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}" - //@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$" - Match m = Regex.Match(strIn, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:[0-9]{1,6}");// - if (m.Success) - { - return m.Value; - } - else - { - return string.Empty; - } - } - catch (Exception ex) - { - return string.Empty; - } - } - - public static bool IsIPAddress(string strIn) - { - bool b = Regex.IsMatch(strIn, @"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,6}$"); - return b; - } - - - public static bool CompareType(this T oneT, T twoT) - { - bool result = true;//两个类型作比较时使用,如果有不一样的就false - Type typeOne = oneT.GetType(); - Type typeTwo = twoT.GetType(); - //如果两个T类型不一样 就不作比较 - if (!typeOne.Equals(typeTwo)) { return false; } - PropertyInfo[] pisOne = typeOne.GetProperties(); //获取所有公共属性(Public) - PropertyInfo[] pisTwo = typeTwo.GetProperties(); - //如果长度为0返回false - if (pisOne.Length <= 0 || pisTwo.Length <= 0) - { - return false; - } - //如果长度不一样,返回false - if (!(pisOne.Length.Equals(pisTwo.Length))) { return false; } - //遍历两个T类型,遍历属性,并作比较 - for (int i = 0; i < pisOne.Length; i++) - { - //获取属性名 - string oneName = pisOne[i].Name; - string twoName = pisTwo[i].Name; - //获取属性的值 - object oneValue = pisOne[i].GetValue(oneT, null); - object twoValue = pisTwo[i].GetValue(twoT, null); - //比较,只比较值类型 - if ((pisOne[i].PropertyType.IsValueType || pisOne[i].PropertyType.Name.StartsWith("String")) && (pisTwo[i].PropertyType.IsValueType || pisTwo[i].PropertyType.Name.StartsWith("String"))) - { - if (oneName.Equals(twoName)) - { - if (oneValue == null) - { - if (twoValue != null) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - else if (oneValue != null) - { - if (twoValue != null) - { - if (!oneValue.Equals(twoValue)) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - else if (twoValue == null) - { - result = false; - break; //如果有不一样的就退出循环 - } - } - } - else - { - result = false; - break; - } - } - else - { - //如果对象中的属性是实体类对象,递归遍历比较 - bool b = CompareType(oneValue, twoValue); - if (!b) { result = b; break; } - } - } - return result; - } - /// - /// 对表达式进行格式化处理 - /// - /// - /// - public static string FormatExpress(this string ori) - { - var result = ori; - try - { - var upStr = ori.ToUpper().Replace(" ", ""); - //var strs = upStr.Split(seps); - //result= string.Join(" ", strs); - result = upStr.Replace("AND", " AND ").Replace("OR", " OR "); - - } - catch (Exception ex) - { - result = ori; - } - return result; - } - - public static double NumberKeepTwo(this double? dou, int keep = 2) - { - var data = Math.Round(dou.GetValueOrDefault(), keep); - return data; - } - - public static float NumberKeepTwo(this float? flo, int keep = 2) - { - var dv = Math.Round(flo.GetValueOrDefault(), 2); - return (float)dv; - } - - public static float NumberKeepTwo(this float flo, int keep = 2) - { - var dv = Math.Round(flo, 2); - return (float)dv; - } - - public static double NumberKeepTwo(this double dou, int keep = 2) - { - return Math.Round(dou, keep); - } - - public static decimal NumberKeepTwo(this decimal? dou, int keep = 2) - { - return Math.Round(dou.GetValueOrDefault(), keep); - } - - public static decimal NumberToTenThousand(this decimal dou, int keep = 2) - { - const decimal divisor = 10000.0M; - if (divisor == 0) - { - throw new DivideByZeroException("Divisor cannot be zero."); - } - decimal result = dou / divisor; - - // 使用 Math.Round 保留两位小数,MidpointRounding.AwayFromZero 可以避免银行家舍入 - return Math.Round(result, keep, MidpointRounding.AwayFromZero); - } - - public static decimal NumberKeepTwo(this decimal dou, int keep = 2) - { - return Math.Round(dou, keep); - } - - public static double StrDoubuleKeepTwo(this string strdou, int keep = 2) - { - double outdouble = 0; - try - { - if (double.TryParse(strdou, out outdouble)) - { - return Math.Round(outdouble, keep); - } - else - { - return outdouble; - } - - } - catch (Exception ex) - { - return outdouble; - } - } - - /// - /// 获取list中指定索引的数据 当索引超出范围时返回null - /// - /// - /// - /// - /// - public static T SafeGet(this IList list, int index) where T : class - { - if (index >= 0 && index < list.Count) - { - return list[index]; - } - else - { - return null; - } - } - - public static Decimal StrToDecimal(this string str) - { - decimal outd = 0; - decimal.TryParse(str, out outd); - return Math.Round(outd, 2); - } - - public static long StrToLong(this string str) - { - long outd = 0; - long.TryParse(str, out outd); - return outd; - } - - public static DateTime StrToSafeDateTime(this string dateString) - { - DateTime dateValue; - - bool success = DateTime.TryParse(dateString, out dateValue); - if (success) - { - return dateValue; - } - else - { - return DateTime.MinValue; - } - } - - public static IEnumerable FlattenHierarchy(this BuildingNodeDto node) - { - yield return node; - foreach (var child in node.Children.SelectMany(c => c.FlattenHierarchy())) - { - yield return child; - } - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs deleted file mode 100644 index 771100e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/FanCmdContextVo.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.CylmPro; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Common -{ - public class FanCmdContextVo - { - public FanCmdBo FanCmdBo { get; set; } - - public int TryTime { get; set; } - - public ContextModel ContextModel { get; set; } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs deleted file mode 100644 index 27a7304..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HealthLevel.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.BulletinBoard; - -namespace WeiCloud.Core.Common -{ - public class HealthLevel - { - public static HealthModel GetHealthLevel(double value, int type) - { - HealthModel en = new HealthModel(); - string str = string.Empty; - string goodName = "极佳"; - string comfortName = "舒适"; - string badName = "一般"; - var date = DateTime.Now; - var time1 = Convert.ToDateTime(date.Year + "-11-01"); - var time2 = Convert.ToDateTime(date.Year + "-05-01"); - var temp1 = 24; - var temp2 = 26; - var temp3 = 21; - var temp4 = 28; - var wet1 = 40; - var wet2 = 60; - var wet3 = 31; - var wet4 = 70; - var co21 = 500; - var co22 = 750; - //var co23 = 2000; - var jiaquan1 = 60; - var jiaquan2 = 80; - //var jiaquan3 = 2000; - var pm1 = 30; - var pm2 = 50; - var TVOCGoodLevelMinValue = 0; - var TVOCGoodLevelMaxValue = 400; - var TVOCComfortLevelMinValue = 401; - var TVOCComfortLevelMaxValue = 600; - //var pm3 = 500; - if (date < time2 || date >= time1)//供暖季 - { - temp1 = 20; - temp2 = 24; - temp3 = 18; - wet1 = 30; - wet3 = 11; - } - - if (type == 1)//温度 - { - if (value >= temp1 && value <= temp2) - { - str = goodName; - en.Pecent = 100; - en.Level = goodName; - } - else if ((value >= temp3 && value < temp1) || (value >= temp2 && value <= temp4)) - { - str = comfortName; - en.Pecent = 80; - - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - } - else if (type == 2)//湿度 - { - if (value >= wet1 && value <= wet2) - { - en.Pecent = 100; - en.Level = goodName; - } - else if ((value >= wet3 && value < wet1) || (value >= wet2 && value <= wet4)) - { - en.Pecent = 80; - - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - } - else if (type == 3)//co2 - { - if (value >= 0 && value < co21) - { - en.Pecent = 100; - en.Level = goodName; - } - else if ((value >= co21 && value <= co22)) - { - en.Pecent = 80; - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - } - else if (type == 5)//甲醛 - { - if (value >= 0 && value < jiaquan1) - { - en.Pecent = 100; - en.Level = goodName; - } - else if ((value >= jiaquan1 && value <= jiaquan2)) - { - en.Pecent = 70; - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - - } - else if (type == 4)//PM - { - if (value >= 0 && value < pm1) - { - en.Pecent = 100; - en.Level = goodName; - } - else if ((value >= pm1 && value < pm2)) - { - en.Pecent = 70; - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - } - else if (type == 6)//TVOC - { - if (value >= TVOCGoodLevelMinValue && value <= TVOCGoodLevelMaxValue) - { - en.Pecent = 100; - en.Level = goodName; - } - else if (value >= TVOCComfortLevelMinValue && value <= TVOCComfortLevelMaxValue) - { - en.Pecent = 70; - en.Level = comfortName; - } - else - { - en.Pecent = 20; - en.Level = badName; - } - } - return en; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs deleted file mode 100644 index 64aa980..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HolidayUtil.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Common -{ - public class HolidayUtil - { - /// 判断是不是周末/节假日 - /// - /// 日期 - /// 周末和节假日返回true,工作日返回false - public static async Task IsHolidayByDate(DateTime date) - { - var isHoliday = false; - //var webClient = new System.Net.WebClient(); - //var PostVars = new System.Collections.Specialized.NameValueCollection - //{ - // { "d", date.ToString("yyyyMMdd") }//参数 - //}; - try - { - var day = date.DayOfWeek; - - //判断是否为周末 - if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday) - return true; - - //0为工作日,1为周末,2为法定节假日 - //var byteResult = await webClient.UploadValuesTaskAsync("http://tool.bitefu.net/jiari/", "POST", PostVars);//请求地址,传参方式,参数集合 - //var result = Encoding.UTF8.GetString(byteResult);//获取返回值 - //if (result == "1" || result == "2") - // isHoliday = true; - } - catch - { - isHoliday = false; - } - return isHoliday; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs deleted file mode 100644 index 99eabf0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpClientHelper.cs +++ /dev/null @@ -1,162 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Common -{ - public class HttpClientHelper - { - public static int clientTimeOut { get; set; } = 2000; - - public string Url { get; private set; } - public string Payload { get; private set; } - public string AuthorizationScheme { get; private set; } - public string AuthorizationParameter { get; private set; } - public string Type { get; private set; } - - - private readonly ILogger _logger; - public HttpClientHelper(ILogger logger) - { - _logger = logger; - Type = GetSetting("WexflowApi:type", "application/json"); - } - - private string GetSetting(string v1, string v2) - { - try - { - var type = ConfigHelper.GetSectionValue("WexflowApi:type"); - if (string.IsNullOrEmpty(type)) - { - return v2; - } - return type; - } - catch (Exception) - { - return v2; - } - - } - - public static async Task GetRunAsync(string baseUrl, string actionName) - { - using (var client = new HttpClient()) - { - client.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); - client.BaseAddress = new Uri(baseUrl); - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - - // HTTP GET - var response = await client.GetAsync(actionName); - if (response.IsSuccessStatusCode) - { - var result = await response.Content.ReadAsStringAsync(); - return result; - } - else - { - return string.Empty; - } - - } - } - - public async System.Threading.Tasks.Task Post(string url, string authScheme, string authParam, string payload) - { - using (var httpContent = new StringContent(payload, Encoding.UTF8, Type)) - using (var httpClient = new HttpClient()) - { - httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); - if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) - { - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); - } - - var httpResponse = await httpClient.PostAsync(url, httpContent); - if (httpResponse.Content != null) - { - var responseContent = await httpResponse.Content.ReadAsStringAsync(); - return responseContent; - } - } - return string.Empty; - } - - public async System.Threading.Tasks.Task Delete(string url, string authScheme, string authParam) - { - using (var httpClient = new HttpClient()) - { - httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); - if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) - { - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); - } - - var httpResponse = await httpClient.DeleteAsync(url); - if (httpResponse.Content != null) - { - var responseContent = await httpResponse.Content.ReadAsStringAsync(); - return responseContent; - } - } - return string.Empty; - } - - public async System.Threading.Tasks.Task Put(string url, string authScheme, string authParam, string payload) - { - using (var httpContent = new StringContent(payload, Encoding.UTF8, Type)) - using (var httpClient = new HttpClient()) - { - httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); - if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) - { - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); - } - - var httpResponse = await httpClient.PutAsync(url, httpContent); - if (httpResponse.Content != null) - { - var responseContent = await httpResponse.Content.ReadAsStringAsync(); - return responseContent; - } - } - return string.Empty; - } - - public async System.Threading.Tasks.Task Get(string url, string authScheme, string authParam) - { - try - { - //_logger.LogError(new NlogMessageHelper("yafo1", url).GetNlogMessage()); - using (var httpClient = new HttpClient()) - { - httpClient.Timeout = TimeSpan.FromMilliseconds(clientTimeOut); - if (!string.IsNullOrEmpty(authScheme) && !string.IsNullOrEmpty(authParam)) - { - httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, authParam); - } - - var httpResponse = await httpClient.GetAsync(url); - if (httpResponse.Content != null) - { - var responseContent = await httpResponse.Content.ReadAsStringAsync(); - return responseContent; - } - } - return string.Empty; - } - catch (Exception) - { - return string.Empty; - } - - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs deleted file mode 100644 index 93b7e4d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/StaticHttpContextExtensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.WEIHttpContext -{ - public static class StaticHttpContextExtensions - { - - public static void AddHttpContextAccessor(this IServiceCollection services) - { - services.AddSingleton(); - } - - - public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app) - { - var httpContextAccessor = app.ApplicationServices.GetRequiredService(); - WEIHttpContext.Configure(httpContextAccessor); - return app; - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs deleted file mode 100644 index e887fe1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContext/WEIHttpContext.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common.WEIHttpContext -{ - public static class WEIHttpContext - { - private static IHttpContextAccessor _httpContextAccessor; - - public static Microsoft.AspNetCore.Http.HttpContext Current => _httpContextAccessor.HttpContext; - - internal static void Configure(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs deleted file mode 100644 index 418f0ac..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpContextHelper.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core -{ - public class HttpContextHelper - { - - public async Task GetContextInfo(HttpContext httpContext) - { - if (httpContext == null) - { - return await Task.FromResult(new ContextModel()); - } - long userId = 0; - string userName = "系统"; - string actionName = httpContext.Request.Path; - if (httpContext.User.Claims != null) - { - foreach (var item in httpContext.User.Claims) - { - if (item.Type == "sub") - { - userId = long.Parse(item.Value); - } - if (item.Type == "name") - { - userName = item.Value; - } - } - } - string machineIp = httpContext.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + httpContext.Connection.RemotePort; - ContextModel contextModel = new ContextModel() - { - userId = userId, - userName = userName, - actionName = actionName, - machineIp = machineIp - }; - return await Task.FromResult(contextModel); - } - } - - - - public class BackGroudContextModel - { - public static ContextModel GetBackGroudContextModel() - { - return new ContextModel() - { - userId = 1, - userName = "admin", - actionName = "BackGroud", - machineIp = "127.0.0.1" - }; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs deleted file mode 100644 index 36075b3..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpHelper.cs +++ /dev/null @@ -1,875 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core -{ - public class HttpHelper - { - public bool Debug { get; set; } - public CookieCollection Cookies - { - get { return _cookies; } - } - - public void ClearCookies() - { - _cookies = new CookieCollection(); - } - - CookieCollection _cookies = new CookieCollection(); - - private static readonly string DefaultUserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; - /// - /// 创建GET方式的HTTP请求 - /// - /// 请求的URL - /// 请求的超时时间 - /// 请求的客户端浏览器信息,可以为空 - /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 - /// - /// - /// - public HttpWebResponse CreateGetHttpResponse(string url, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Get Url:{0} ", url); - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - - HttpWebRequest request; - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); - request = WebRequest.Create(url) as HttpWebRequest; - request.ProtocolVersion = HttpVersion.Version11; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - - request.Method = "GET"; - request.Headers["Pragma"] = "no-cache"; - request.Accept = "text/html, application/xhtml+xml, */*"; - request.Headers["Accept-Language"] = "en-US,en;q=0.5"; - request.ContentType = "application/x-www-form-urlencoded"; - request.UserAgent = DefaultUserAgent; - request.Referer = Referer; - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - var v = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - return v; - } - - /// - /// 创建POST方式的HTTP请求 - /// - /// 请求的URL - /// 随同请求POST的参数名称及参数值字典 - /// 请求的超时时间 - /// 请求的客户端浏览器信息,可以为空 - /// 发送HTTP请求时所用的编码 - /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 - /// - public HttpWebResponse CreatePostHttpResponse(string url, IDictionary parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Post Url:{0} ", url); - - foreach (KeyValuePair keyValuePair in parameters) - { - Console.Write(",{0}:{1}", keyValuePair.Key, keyValuePair.Value); - } - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - if (requestEncoding == null) - { - throw new ArgumentNullException("requestEncoding"); - } - HttpWebRequest request = null; - //如果是发送HTTPS请求 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); - request = WebRequest.Create(url) as HttpWebRequest; - request.ProtocolVersion = HttpVersion.Version10; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - request.Method = "POST"; - request.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; - request.Referer = Referer; - request.Headers["Accept-Language"] = "en-US,en;q=0.5"; - request.UserAgent = DefaultUserAgent; - request.ContentType = "application/x-www-form-urlencoded"; - request.Headers["Pragma"] = "no-cache"; - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - else - { - request.UserAgent = DefaultUserAgent; - } - - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - - request.Expect = string.Empty; - - //如果需要POST数据 - if (!(parameters == null || parameters.Count == 0)) - { - var buffer = CraeteParameter(parameters); - byte[] data = requestEncoding.GetBytes(buffer.ToString()); - using (Stream stream = request.GetRequestStream()) - { - stream.Write(data, 0, data.Length); - } - } - var v = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - return v; - } - - /// - /// 创建POST方式的HTTP请求 - /// - /// 请求的URL - /// 随同请求POST的参数名称及参数值字典 - /// 请求的超时时间 - /// 请求的客户端浏览器信息,可以为空 - /// 发送HTTP请求时所用的编码 - /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 - /// - public HttpWebResponse CreatePostHttpResponse(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); - - - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - if (requestEncoding == null) - { - throw new ArgumentNullException("requestEncoding"); - } - HttpWebRequest request = null; - //如果是发送HTTPS请求 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); - request = WebRequest.Create(url) as HttpWebRequest; - request.ProtocolVersion = HttpVersion.Version10; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - - request.Method = "POST"; - request.Headers.Add("Accept-Language", "zh-CN,en-GB;q=0.5"); - request.Accept = "text/html, application/xhtml+xml, */*"; - request.Referer = Referer; - request.Headers["Accept-Language"] = "en-US,en;q=0.5"; - request.UserAgent = DefaultUserAgent; - //request.ContentType = "application/x-www-form-urlencoded"; - request.ContentType = "multipart/form-data"; - - request.Headers["Pragma"] = "no-cache"; - - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - else - { - request.UserAgent = DefaultUserAgent; - } - - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - - request.Expect = string.Empty; - - //如果需要POST数据 - if (!string.IsNullOrEmpty(parameters)) - { - byte[] data = requestEncoding.GetBytes(parameters); - using (Stream stream = request.GetRequestStream()) - { - stream.Write(data, 0, data.Length); - } - } - - var v = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - - return v; - } - - - - /// - /// 创建post请求,获取token - /// - /// 请求的URL - /// 随同请求POST的参数名称及参数值字典 - /// 请求的超时时间 - /// 请求的客户端浏览器信息,可以为空 - /// 发送HTTP请求时所用的编码 - /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 - /// - public HttpWebResponse CreatePostHttpResponseJson(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - if (requestEncoding == null) - { - throw new ArgumentNullException("requestEncoding"); - } - HttpWebRequest request = null; - //如果是发送HTTPS请求 设置安全协议 不同的.NET framework安全协议版本不一样 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => - { - return true; //总是接受 - }); - ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; - request = WebRequest.Create(url) as HttpWebRequest; - } - - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - - - request.Method = "POST"; - request.ContentType = "application/json"; - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - else - { - request.UserAgent = DefaultUserAgent; - } - - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - - request.Expect = string.Empty; - - //如果需要POST数据 - - try - { - if (!string.IsNullOrEmpty(parameters)) - { - byte[] data = requestEncoding.GetBytes(parameters); - using (Stream stream = request.GetRequestStream()) - { - stream.Write(data, 0, data.Length); - } - } - var v = request.GetResponse() as HttpWebResponse; - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - - return v; - } - catch(Exception ex) - { - return null; - } - - - - - } - - /// - /// 华为云检测 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public HttpWebResponse CreatePostHttpResponseHW(string token,string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters); - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - if (requestEncoding == null) - { - throw new ArgumentNullException("requestEncoding"); - } - HttpWebRequest request = null; - //如果是发送HTTPS请求 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => - { - return true; //总是接受 - }); - ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; - request = WebRequest.Create(url) as HttpWebRequest; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - - request.Method = "POST"; - request.Headers.Add("X-Auth-Token", token); - - request.ContentType = "application/json"; - //request.AuthenticationLevel: - - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - else - { - request.UserAgent = DefaultUserAgent; - } - - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - - request.Expect = string.Empty; - - //如果需要POST数据 - if (!string.IsNullOrEmpty(parameters)) - { - byte[] data = requestEncoding.GetBytes(parameters); - request.ContentLength = data.Length; - using (Stream stream = request.GetRequestStream()) - { - stream.Write(data, 0, data.Length); - } - } - - var v = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - - return v; - - } - - /// - /// 创建POST方式的HTTP请求 - /// - /// 请求的URL - /// 随同请求POST的参数名称及参数值字典 - /// 请求的超时时间 - /// 请求的客户端浏览器信息,可以为空 - /// 发送HTTP请求时所用的编码 - /// 随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空 - /// - public HttpWebResponse CreatePostFileHttpResponse(string url, string filePath, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - if (Debug) - { - Console.Write("Start Post Url:{0} ", url); - - } - - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - - HttpWebRequest request = null; - //如果是发送HTTPS请求 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); - request = WebRequest.Create(url) as HttpWebRequest; - request.ProtocolVersion = HttpVersion.Version10; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - request.Method = "POST"; - request.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; - request.Referer = Referer; - request.Headers["Accept-Language"] = "en-US,en;q=0.5"; - request.UserAgent = DefaultUserAgent; - request.ContentType = "application/x-www-form-urlencoded"; - request.Headers["Pragma"] = "no-cache"; - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - else - { - request.UserAgent = DefaultUserAgent; - } - - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - - request.Expect = string.Empty; - - //如果需要POST数据 - if (!string.IsNullOrEmpty(filePath)) - { - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - BinaryReader r = new BinaryReader(fs); - - //时间戳 - string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); - byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); - - //请求头部信息 - StringBuilder sb = new StringBuilder(); - sb.Append("--"); - sb.Append(strBoundary); - sb.Append("\r\n"); - sb.Append("Content-Disposition: form-data; name=\"media\""); - sb.Append("file"); - sb.Append("\"; filename=\""); - sb.Append(fs.Name); - sb.Append("\""); - sb.Append("\r\n"); - sb.Append("Content-Type: "); - sb.Append("application/octet-stream"); - sb.Append("\r\n"); - sb.Append("\r\n"); - string strPostHeader = sb.ToString(); - byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); - - - request.ContentType = "multipart/form-data; boundary=" + strBoundary; - long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length; - - request.ContentLength = length; - - //开始上传时间 - DateTime startTime = DateTime.Now; - - byte[] filecontent = new byte[fs.Length]; - - fs.Read(filecontent, 0, filecontent.Length); - - using (Stream stream = request.GetRequestStream()) - { - - //发送请求头部消息 - stream.Write(postHeaderBytes, 0, postHeaderBytes.Length); - - stream.Write(filecontent, 0, filecontent.Length); - - //添加尾部的时间戳 - stream.Write(boundaryBytes, 0, boundaryBytes.Length); - } - - } - } - var v = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - - Cookies.Add(v.Cookies); - - if (Debug) - { - Console.WriteLine("OK"); - } - - return v; - } - - - public static string CraeteParameter(IDictionary parameters) - { - StringBuilder buffer = new StringBuilder(); - foreach (string key in parameters.Keys) - { - buffer.AppendFormat("&{0}={1}", key, parameters[key]); - } - return buffer.ToString().TrimStart('&'); - } - - private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) - { - return true; //总是接受 - } - - - - public string Post(string url, IDictionary parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - HttpWebResponse response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, Referer, headers); - - try - { - using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) - { - return reader.ReadToEnd(); - } - } - catch (Exception) - { - return null; - } - finally - { - response.Close(); - } - } - - - - public string Post(string url, string parameters, Encoding requestEncoding, Encoding responseEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - HttpWebResponse response = CreatePostHttpResponse(url, parameters, requestEncoding, timeout, userAgent, cookies, Referer, headers); - - try - { - using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) - { - return reader.ReadToEnd(); - } - } - catch (Exception) - { - return null; - } - finally - { - response.Close(); - } - } - - public string PostFile(string url, string filePath, Encoding responseEncoding, - int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", - Dictionary headers = null) - { - HttpWebResponse response = CreatePostFileHttpResponse(url, filePath, timeout, userAgent, cookies, Referer, - headers); - - try - { - using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) - { - return reader.ReadToEnd(); - } - } - catch (Exception) - { - return null; - } - finally - { - response.Close(); - } - } - - public string Get(string url, Encoding responseEncoding, Dictionary headers = null, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "") - { - HttpWebResponse response = CreateGetHttpResponse(url, timeout, userAgent, cookies, Referer, headers); - - try - { - using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) - { - return reader.ReadToEnd(); - } - } - catch (Exception) - { - return null; - } - finally - { - response.Close(); - } - } - - public byte[] GetFile(string url, out Dictionary header, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary headers = null) - { - HttpWebResponse response = CreateGetHttpResponse(url, timeout, userAgent, cookies, Referer, headers); - - header = new Dictionary(); - - foreach (string key in response.Headers.AllKeys) - { - header.Add(key, response.Headers[key]); - } - - try - { - System.IO.Stream st = response.GetResponseStream(); - - byte[] by = new byte[response.ContentLength]; - - st.Read(by, 0, by.Length); - - st.Close(); - - return by; - } - catch (Exception) - { - return null; - } - - } - - string _AddressIP = String.Empty; - public string GetComputerIP() - { - try - { - foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList) - { - if (_IPAddress.AddressFamily.ToString() == "InterNetwork") - { - _AddressIP = _IPAddress.ToString(); - } - } - } - catch (Exception ex) - { - - throw; - } - - return _AddressIP; - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs deleted file mode 100644 index 849f9d5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/HttpUtils.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class HttpUtils - { - private static readonly string DefaultUserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; - private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) - { - return true; //总是接受 - } - - public static string Get(string url, Encoding responseEncoding, Dictionary headers = null, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "") - { - HttpWebResponse response = null; - HttpWebRequest request = null; - try - { - CookieCollection Cookies = new CookieCollection(); - if (string.IsNullOrEmpty(url)) - { - throw new ArgumentNullException("url"); - } - - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); - request = WebRequest.Create(url) as HttpWebRequest; - request.ProtocolVersion = HttpVersion.Version11; - } - else - { - request = WebRequest.Create(url) as HttpWebRequest; - } - - request.Method = "GET"; - request.Headers["Pragma"] = "no-cache"; - request.Accept = "text/html, application/xhtml+xml, */*"; - request.Headers["Accept-Language"] = "en-US,en;q=0.5"; - request.ContentType = "application/x-www-form-urlencoded"; - request.UserAgent = DefaultUserAgent; - request.Referer = Referer; - - if (headers != null) - { - foreach (var header in headers) - { - request.Headers.Add(header.Key, header.Value); - } - } - - - if (!string.IsNullOrEmpty(userAgent)) - { - request.UserAgent = userAgent; - } - if (timeout.HasValue) - { - request.Timeout = timeout.Value * 1000; - } - if (cookies != null) - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(cookies); - } - else - { - request.CookieContainer = new CookieContainer(); - request.CookieContainer.Add(Cookies); - } - response = request.GetResponse() as HttpWebResponse; - - Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host))); - Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host))); - Cookies.Add(response.Cookies); - - using (StreamReader reader = new StreamReader(response.GetResponseStream(), responseEncoding)) - { - return reader.ReadToEnd(); - } - } - catch (Exception ex) - { - throw ex; - } - finally - { - if (response != null) - response.Close(); - } - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs deleted file mode 100644 index cd6d96f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/IPUtil.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class IPUtil - { - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs deleted file mode 100644 index 1a4dbb5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/Interceptor/SlowQueryInterceptor.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Microsoft.EntityFrameworkCore.Diagnostics; -using System; -using System.Collections.Generic; -using System.Data.Common; -using System.Diagnostics; -using System.Text; -using System.Threading.Tasks; -using System.Threading; -using WeiCloud.Core.NlogTools; -using System.Linq; -using Microsoft.Extensions.Options; -using NLog; -using Microsoft.Extensions.Logging; -using Microsoft.IdentityModel.Tokens; - -namespace WeiCloud.Core.Common.Interceptor -{ - public static class CallContext - { - private static readonly AsyncLocal _context = new AsyncLocal { }; - - public static string? CurrentMethod - { - get => _context.Value; - set => _context.Value = value; - } - } - public class EfMonitorOptions - { - public int EnableSlowQueryMonitor { get; set; } - public int SlowQueryThresholdMs { get; set; } = 1000; - } - - public class SlowQueryInterceptor : DbCommandInterceptor - { - private readonly ILogger _logger; - private readonly EfMonitorOptions _options; - - public SlowQueryInterceptor(IOptions options, ILogger logger) - { - _options = options.Value; - _logger = logger; - } - public override async ValueTask ReaderExecutedAsync(DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default) - { - if (_options.EnableSlowQueryMonitor == 1 && eventData.Duration.TotalMilliseconds >= _options.SlowQueryThresholdMs) - { - var caller = CallContext.CurrentMethod ?? "Unknown"; - _logger.LogWarning($@"⚠️ EF慢查询:耗时={eventData.Duration.TotalMilliseconds}ms -调用方法: {caller} -SQL: -{command.CommandText}"); - } - - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs deleted file mode 100644 index ccd5d93..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/LocalCache.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace WeiCloud.Core.Common -{ - public static class LocalCache - { - /// - /// 报警个数 - /// - public static int AlarmCount { get; set; } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs deleted file mode 100644 index 37f8421..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/MathExpandClass.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public static class MathExpandClass - { - public static double KeepTwodig(this double num) - { - if (Math.Abs(num - num.ToInt()) <= 0.01){ - return num; - } - else - { - return Math.Round(num, 2); - } - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs deleted file mode 100644 index ab295fa..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/MyAllowAnonymous.cs +++ /dev/null @@ -1,87 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Authorization.Infrastructure; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Common -{ - public class MyAllowAnonymous : AuthorizeFilter - { - private static AuthorizationPolicy _policy_ = new AuthorizationPolicy(new[] { new DenyAnonymousAuthorizationRequirement() }, new string[] { }); - - public MyAllowAnonymous() : base(_policy_) { } - - public override async Task OnAuthorizationAsync(AuthorizationFilterContext context) - { - #region 第三方验证 - ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; - //bool isActionAuthDescriptor = ad.MethodInfo.IsDefined(typeof(ThirdPartyAuthorizeAttribute), false); - var actionAuthDescriptor = ad.MethodInfo.GetCustomAttributes(typeof(ThirdPartyAuthorizeAttribute), false).FirstOrDefault(); - var controllerAuthDescriptor = ((ThirdPartyAuthorizeAttribute[])((ControllerActionDescriptor)context.ActionDescriptor).ControllerTypeInfo.GetCustomAttributes(typeof(ThirdPartyAuthorizeAttribute), false)).FirstOrDefault(); - //[0].ProjectNam; - if (actionAuthDescriptor != null || controllerAuthDescriptor != null) - {//x8duU2lvTLahXP2x - try - { - var requestTime = DateTime.Parse(context.HttpContext.Request.Headers["RequestTime"].FirstOrDefault()); - if (requestTime >= DateTime.Now.AddMinutes(-15) && requestTime < DateTime.Now.AddMinutes(15)) - { - var requestTimeStr = requestTime.ToString("yyyyMMddHHmmss"); - var customerSign = context.HttpContext.Request.Headers["RequestSign"].FirstOrDefault(); - string key = $"x8duU2lvTLahXP2x{requestTimeStr}"; - var sign = MD5Helper.GetMd5String(key); - if (sign.Equals(customerSign)) - { - return; - } - } - } - catch (Exception ex) - { - } - context.Result = new JsonResult(new { Code = (int)HttpStatusCode.Unauthorized }); - //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; - return; - } - #endregion - - await base.OnAuthorizationAsync(context); - if (!context.HttpContext.User.Identity.IsAuthenticated || - context.Filters.Any(item => item is IAllowAnonymousFilter)) return; - - //var url = context.HttpContext.url; - //解析url - // {/ Home / Index} - //var url = context.HttpContext.Request.Path.Value; - //if (string.IsNullOrWhiteSpace(url)) - //{ - // return; - //} - - //var list = url.Split("/"); - //if (list.Length <= 0 || url == "/") - //{ - // return; - //} - //var controllerName = list[1].ToString().Trim(); - //var actionName = list[2].ToString().Trim(); - } - } - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true)] - public class ThirdPartyAuthorizeAttribute : Attribute - { - public ThirdPartyAuthorizeAttribute(string projectName) => ProjectName = projectName; - - // Get or set the Age property by manipulating the underlying Policy property - public string ProjectName { get; set; } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs deleted file mode 100644 index c54a6ee..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/NumberCharConvert.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class NumberCharConvert - { - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs deleted file mode 100644 index 8dbbd7b..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/PolicyContextModel.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Common -{ - public class PolicyContextModel - { - private readonly IConfiguration configuration; - public PolicyContextModel(IConfiguration configuration) - { - this.configuration = configuration; - } - - public ContextModel GetPolicyContextModel() - { - return new ContextModel() - { - userId = string.IsNullOrEmpty(configuration["PolicyConfig:BackUserId"]) ? 1 : configuration["PolicyConfig:BackUserId"].ToLong(), - userName = string.IsNullOrEmpty(configuration["PolicyConfig:BackUserName"]) ? "admin" : configuration["PolicyConfig:BackUserName"], - actionName = "控制策略", - machineIp = "127.0.0.1" - }; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs deleted file mode 100644 index cf8c351..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/PostUniClientModel.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public class PostUniClientModel - { - public long UserId { get; set; } - public string ClientId { get; set; } - } - - - - /// - /// 修改用户信息 - /// - public partial class PutUserDto - { - public long Id { get; set; } - public string Userfullname { get; set; } - - public short? Sex { get; set; } - - public string Userpost { get; set; } - - public string Phone { get; set; } - - public string Email { get; set; } - public string Wechat { get; set; } - } - - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs deleted file mode 100644 index a54afad..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/QueryConst.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Common -{ - public class QueryConst - { - public static List GetOwnerInitPermissions(long parentId, List allPermissions) - { - var result = new List { }; - var childs = allPermissions.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetOwnerInitPermissions(child.Id, allPermissions); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - /// - /// 获取所有建筑物 - /// - /// - /// - /// - public static List GetChilds(long parentId, List allConsts) - { - var result = new List(); - var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetChilds(child.Id, allConsts); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - - public static List GetChilds(long parentId, List allConsts) - { - var result = new List(); - var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetChilds(child.Id, allConsts); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - - public static List GetParents(long id, List allConsts) - { - var result = new List(); - var parentItem = allConsts.FirstOrDefault(t => t.Id == id); - if (parentItem != null) - { - result.Add(parentItem); - if (parentItem.Parentid != null && parentItem.Parentid > 0) - { - var _parentItems = GetParents(parentItem.Parentid ?? 0, allConsts); - if (_parentItems != null && _parentItems.Count > 0) - result.AddRange(_parentItems); - } - } - return result; - } - - public static ConstructionInfo GetConstParent(long id, List allConsts) - { - var result = new ConstructionInfo(); - try - { - var p = allConsts.FirstOrDefault(t => t.Id == id); - if (p == null) - { - return new ConstructionInfo { Id = id }; - } - else if (p.Parentid == null || p.Parentid == 0) - { - return p; - } - return GetConstParent((long)p.Parentid, allConsts); - } - catch (Exception ex) - { - } - return result; - } - - public static List GetTenementAreaChilds(long parentId, List allConsts) - { - var result = new List(); - var childs = allConsts.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetTenementAreaChilds(child.Id, allConsts); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - - public static List GetUserRoles(long parentId, List allRoles) - { - var result = new List(); - var childs = allRoles.Where(t => t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetUserRoles(child.Id, allRoles); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - - public static short CheckDataChangeStateTypeByTable(string tableName, string fieldName) - { - short result = 0; - if (tableName.Equals("Tb_Ammeter_History", System.StringComparison.OrdinalIgnoreCase)) - { - if (fieldName.Equals("Am_Parm_029", System.StringComparison.OrdinalIgnoreCase)) - { - result = DataChangeStateAccum; - } - } - - if (tableName.Equals("Tb_WaterMeter_History", System.StringComparison.OrdinalIgnoreCase)) - { - if (fieldName.Equals("Wm_Parm_003", System.StringComparison.OrdinalIgnoreCase)) - { - result = DataChangeStateAccum; - } - } - - if (tableName.Equals("Tb_GasMeter_History", System.StringComparison.OrdinalIgnoreCase)) - { - if (fieldName.Equals("Gm_Parm_002", System.StringComparison.OrdinalIgnoreCase)) - { - result = DataChangeStateAccum; - } - } - - if (tableName.Equals("Tb_HeatMeter_History", System.StringComparison.OrdinalIgnoreCase)) - { - if (fieldName.Equals("Hm_Parm_002", System.StringComparison.OrdinalIgnoreCase)) - { - result = DataChangeStateAccum; - } - } - return result; - } - /// - /// 累计值 - /// - public static short DataChangeStateAccum = 1; - - public static TenementArea GetParentTenementArea(long id, List allAreas) - { - try - { - var currentArea = allAreas.FirstOrDefault(t => t.Id == id); - if (currentArea == null) - { - return null; - } - else if (currentArea.Parentid == null || currentArea.Parentid == 0) - { - return currentArea; - } - var parentArea = allAreas.FirstOrDefault(t => t.Id == currentArea.Parentid); - if (parentArea == null) - { - return currentArea; - } - if (parentArea.Parentid == null || parentArea.Parentid == 0) - { - return parentArea; - } - return GetParentTenementArea(parentArea.Parentid ?? 0, allAreas); - } - catch (Exception ex) - { - - } - return null; - } - } - public class QueryEquipType - { - public static List GetChilds(long parentId, List all) - { - var result = new List(); - var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetChilds(child.Id, all); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - public static List GetAll(List parentEqTypes, List all) - { - var equipTypes = new List { }; - foreach (var parentEqType in parentEqTypes) - { - equipTypes.Add(parentEqType); - var childs = GetChilds(parentEqType.Id, all); - if (childs != null && childs.Count() > 0) - { - equipTypes.AddRange(childs); - } - } - return equipTypes; - } - } - public class QueryUserGroupType - { - public static List GetChilds(long parentId, List all) - { - var result = new List(); - var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetChilds(child.Id, all); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - } - public class QueryItem - { - /// - /// 获取分项下所有设备 - /// - /// - /// - /// - /// - public static List GetItemEquips(long id, List constEnergyItems, List allEquipmentInfos) - { - var equips = new List { }; - var childItems = constEnergyItems.Where(t => t.Parentid == id).ToList(); - if (childItems != null && childItems.Count() > 0) - { - foreach (var childItem in childItems) - { - var equipmentInfos = allEquipmentInfos.Where(t => t.Itemid == childItem.Id).ToList(); - if (equipmentInfos != null && equipmentInfos.Count() > 0) - { - var equipmentInfoIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); - equips.AddRange(equipmentInfoIds); - } - else - { - var _equips = GetItemEquips(childItem.Id, constEnergyItems, allEquipmentInfos); - if (_equips != null && _equips.Count() > 0) - { - equips.AddRange(_equips); - } - } - } - } - return equips; - } - } - public class QueryGroup - { - public static List GetParents(long id, List allConsts) - { - var result = new List(); - var parentItem = allConsts.FirstOrDefault(t => t.Id == id); - if (parentItem != null) - { - result.Add(parentItem); - if (parentItem.ParentId > 0) - { - var _parentItems = GetParents(parentItem.ParentId, allConsts); - if (_parentItems != null && _parentItems.Count > 0) - result.AddRange(_parentItems); - } - } - return result; - } - public static List GetParentRds(long id, List allConsts) - { - var result = new List(); - var parentItem = allConsts.FirstOrDefault(t => t.Id == id); - if (parentItem != null) - { - result.Add(parentItem); - if (parentItem.ParentId > 0) - { - var _parentItems = GetParentRds(parentItem.ParentId, allConsts); - if (_parentItems != null && _parentItems.Count > 0) - result.AddRange(_parentItems); - } - } - return result; - } - public static List GetChilds(long parentId, List all) - { - var result = new List(); - var childs = all.Where(t => t.Parentid != null && t.Parentid == parentId).ToList(); - foreach (var child in childs) - { - result.Add(child); - var _childs = GetChilds(child.Id, all); - if (_childs != null && _childs.Count > 0) - result.AddRange(_childs); - } - return result; - } - } - public class QueryFunPermission - { - public static List GetParents(long parentId, List allFunPermissions) - { - var result = new List { }; - var parent = allFunPermissions.FirstOrDefault(t => t.Id == parentId); - if (parent == null) - { - return result; - } - else - { - result.Add(parent); - var parents = GetParents(parent.ParentId, allFunPermissions); - if (parents != null && parents.Count() > 0) - { - result.AddRange(parents); - } - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs deleted file mode 100644 index 02e030e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/RandomNumberCreate.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - /// - /// 生成随机数 ccx 20200731 - /// - public static class RandomNumberCreate - { - //随机数内容 - private static char[] constant = - { - '0','1','2','3','4','5','6','7','8','9', - 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', - 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' - }; - /// - /// 生成随机数 - /// - /// 随机数位数 - /// 指定位数的随机数 - public static string GenerateRandomNumber(int Length) - { - System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62); - Random rd = new Random(); - for (int i = 0; i < Length; i++) - { - newRandom.Append(constant[rd.Next(62)]); - } - return newRandom.ToString(); - } - public static string getRandomizer(int intLength, bool booNumber, bool booSign, bool booSmallword, bool booBigword) - { - //定义 - Random ranA = new Random(); - int intResultRound = 0; - int intA = 0; - string strB = ""; - while (intResultRound < intLength) - { - //生成随机数A,表示生成类型 - //1=数字,2=符号,3=小写字母,4=大写字母 - intA = ranA.Next(1, 5); - //如果随机数A=1,则运行生成数字 - //生成随机数A,范围在0-10 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 1 && booNumber) - { - intA = ranA.Next(0, 10); - strB = intA.ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - //如果随机数A=2,则运行生成符号 - //生成随机数A,表示生成值域 - //1:33-47值域,2:58-64值域,3:91-96值域,4:123-126值域 - if (intA == 2 && booSign == true) - { - intA = ranA.Next(1, 5); - //如果A=1 - //生成随机数A,33-47的Ascii码 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 1) - { - intA = ranA.Next(33, 48); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - //如果A=2 - //生成随机数A,58-64的Ascii码 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 2) - { - intA = ranA.Next(58, 65); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - - //如果A=3 - //生成随机数A,91-96的Ascii码 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 3) - { - intA = ranA.Next(91, 97); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - - //如果A=4 - //生成随机数A,123-126的Ascii码 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 4) - { - intA = ranA.Next(123, 127); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - } - - //如果随机数A=3,则运行生成小写字母 - //生成随机数A,范围在97-122 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 3 && booSmallword == true) - { - intA = ranA.Next(97, 123); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - - //如果随机数A=4,则运行生成大写字母 - //生成随机数A,范围在65-90 - //把随机数A,转成字符 - //生成完,位数+1,字符串累加,结束本次循环 - if (intA == 4 && booBigword == true) - { - intA = ranA.Next(65, 89); - strB = ((char)intA).ToString() + strB; - intResultRound = intResultRound + 1; - continue; - } - } - return strB; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs deleted file mode 100644 index e8c09e5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/RealValueMean.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Common -{ - public static class RealValueMean - { - #region 获取实时值相对应的含义 - public static string GetParamMean(string value, string paramMean) - { - string returnStr = string.Empty; - if (string.IsNullOrEmpty(paramMean)) - { - return returnStr; - } - if (paramMean.Contains(";")) - { - string[] arr = paramMean.Split(';'); - foreach (string s in arr) - { - if (!string.IsNullOrEmpty(s) && s.Contains(':')) - { - string[] ar = s.Split(':'); - - if (ar.Length == 2) - { - if (string.Equals(value.Trim(), ar[0].Trim(), StringComparison.OrdinalIgnoreCase)) - { - returnStr = ar[1]; - break; - } - } - - } - } - } - - return returnStr; - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs deleted file mode 100644 index 6142b3e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/SteamHeatCalculate.cs +++ /dev/null @@ -1,15 +0,0 @@ -using NPOI.Util; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Common -{ - public static class SteamHeatCalculate - { - - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs b/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs deleted file mode 100644 index 1b24eed..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Common/Tasks/TaskManager.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; - -namespace WeiCloud.Core.Common.Tasks -{ - public class TaskManager - { - private static ConcurrentDictionary TasksCancel = new ConcurrentDictionary(); - public static void AddTask(long key, CancellationTokenSource cancellationTokenSource) - { - TasksCancel.AddOrUpdate(key, (key) => - { - return cancellationTokenSource; - }, (key, value) => - { - value.Cancel(); - return cancellationTokenSource; - }); - } - public static List GetTasks() - { - return TasksCancel.Keys.ToList(); - } - public static bool StopTask(long key) - { - var result = true; - try - { - CancellationTokenSource cancellationTokenSource = null; - TasksCancel.TryRemove(key, out cancellationTokenSource); - cancellationTokenSource.Cancel(); - } - catch (Exception ex) - { - result = false; - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs deleted file mode 100644 index cd44f40..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AirQuantityEnum.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 空气质量类型 - /// - public static class AirQuantityEnum - { - /// - /// 温度 - /// - public static readonly short Temperature = 1; - /// - /// 湿度 - /// - public static readonly short Humidity = 2; - /// - /// 二氧化碳 - /// - public static readonly short CO2 = 3; - /// - /// 挥发性有机物 - /// - public static readonly short TVOC = 4; - /// - /// PM2.5 - /// - public static readonly short PM = 5; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs deleted file mode 100644 index 0f13fd1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/AssetTypeEnum.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class AssetTypeEnum - { - public static readonly string VideoMonitor = "VideoMonitor"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs deleted file mode 100644 index b6078e0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/CarbonEnum.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public enum CarbonEnum - { - } - public enum CarbonQuotaAdjustEnum - { - /// - /// 未提交 - /// - NotSubmitted = 0, - /// - /// 已发布待审核 - /// - Published = 1, - /// - /// 已审核 - /// - Audited = 2, - /// - /// 已审核调整中 - /// - AuditedAdjust = 3, - /// - /// 已完成 - /// - Completed = 4 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs deleted file mode 100644 index b09f20f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ClimNum.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class ClimNum - { - public static readonly long SevereCold = 1; - public static readonly long Cold = 2; - public static readonly long HotAndCold = 3; - public static readonly long HotAndWarm = 4; - public static readonly long Warm = 5; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs deleted file mode 100644 index 3dc119a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConModelEnum.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class ConModelEnum - { - /// - /// 暖通系统 - /// - public static readonly long HVACSystem = 1; - /// - /// 配电系统 - /// - public static readonly long DistributionSystem = 2; - /// - /// 照明系统 - /// - public static readonly long LightSystem = 3; - /// - /// 电梯系统 - /// - public static readonly long LiftSystem = 4; - /// - /// 给排水系统 - /// - public static readonly long WaterSupplyAndDrainageSystem = 5; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs deleted file mode 100644 index 90e866a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ConstTypeEnum.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 建筑物类型 - /// - public static class ConstTypeEnum - { - /// - /// 室外 - /// - public const string OutRoomCode = "ct011"; - /// - /// 配电室 - /// - public const string ElectronicConstCode = "ct005"; - /// - /// 生活水泵房 - /// - public const string LifeWaterConstCode = "ct006"; - /// - /// 污水泵房 - /// - public const string SewageConstCode = "ct007"; - /// - /// 卫生间污水泵房 - /// - public const string BathWaterConstCode = "ct009"; - /// - /// 区域 - /// - public const string AreaConstCode = "ct017"; - /// - /// 楼层 - /// - public const string FloorCode = "ct002"; - /// - /// 楼栋 - /// - public const string BuildingCode = "ct001"; - /// - /// 楼栋 - /// - public const string HVACSystemCode = "ct004"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs deleted file mode 100644 index 1eb7567..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/DataSetGroupEnum.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Entity.LogicModels.BasicGroup; - -namespace WeiCloud.Core.EnumTools -{ - public enum DataSetGroupIntervalTypeEnum - { - RealData = 1, - Hour = 2, - Day = 3, - Week = 4, - Month = 5, - Year = 6 - } - public enum AggregateEnum - { - Sum = 1, - Average = 2, - Max = 3, - Min = 4, - Count = 5, - First = 6, - Last = 7 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs deleted file mode 100644 index 30d8df9..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnergyItemEnum.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// ccx 能源分项元数据code - /// - public static class EnergyItemEnum - { - /// - /// 暖通空调用电 - /// - public static readonly string ElectForAirCondition = "it002"; - /// - /// 暖通空调用气 - /// - public static readonly string GasForAirCondition = "it031"; - /// - /// 生活用水 - /// - public static readonly string DomesticWater = "it023"; - /// - /// 中水 洁净卫生用水 - /// - public static readonly string NormalWater = "it024"; - /// - /// 照明插座用电 - /// - public static readonly string LightItem = "it001"; - /// - /// 动力用电 - /// - public static readonly string PowerItem = "it003"; - /// - /// 其他用电 - /// - public static readonly string OtherItem = "it021"; - - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs deleted file mode 100644 index 6239faf..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryBillingType.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 能源计费方式 - /// - public static class EngeryBillingType - { - /// - /// 平均价 - /// - public static readonly short Average = 1; - /// - /// 谷峰平 - /// - public static readonly short Fengguping = 3; - /// - /// 阶梯 - /// - public static readonly short Ladder = 2; - } - /// - /// 谷峰平类型 - /// - public static class FenggupingType - { - /// - /// 尖峰 - /// - public static readonly short Peak = 1; - /// - /// 峰 - /// - public static readonly short PeakShort = 2; - /// - /// 平 - /// - public static readonly short Flat = 3; - /// - /// 谷 - /// - public static readonly short Valley = 4; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs deleted file mode 100644 index a192936..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EngeryTypeEnum.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 能源类型枚举,水电气 - /// - public static class EngeryTypeEnum - { - /// - /// 电 - /// - public static readonly short ElectEngery = 1; - /// - /// 水 - /// - public static readonly short WaterEngery = 3; - /// - /// 气 - /// - public static readonly short GasEngery = 2; - /// - /// 热表 - /// - public static readonly short HeatEngery = 4; - /// - /// 蒸汽 - /// - public static readonly short Steam = 5; - /// - /// 煤气 - /// - public static readonly short CoalGas = 6; - /// - /// 柴油 - /// - public static readonly short Oil = 7; - /// - /// 热水 - /// - public static readonly short HotWater = 8; - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs deleted file mode 100644 index 67f4202..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumHelper.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Reflection; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class ZrhEnumHelper - { - public static string GetDescription(int value) where TEnum : Enum - { - var type = typeof(TEnum); - var name = Enum.GetName(type, value); - if (name == null) return null; - - var field = type.GetField(name); - if (field == null) return null; - - var attr = field.GetCustomAttribute(); - return attr?.Description ?? name; - } - public static List<(int Value, string Description)> GetEnumValueDescriptionList() where TEnum : Enum - { - var type = typeof(TEnum); - var result = new List<(int, string)>(); - - foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static)) - { - int value = (int)field.GetValue(null); - var attr = field.GetCustomAttribute(); - string desc = attr?.Description ?? field.Name; - - result.Add((value, desc)); - } - - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs deleted file mode 100644 index 3724f67..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EnumSystemModel.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class EnumSystemModel - { - /// - /// 暖通系统id - /// - public const int HVACSystem = 1; - /// - /// 照明系统 - /// - public const int LightingSystem = 3; - /// - /// 配电系统 - /// - public const int ElectricalSystem = 2; - /// - /// 电梯系统 - /// - public const int LiftSystem = 4; - /// - /// 给排水系统 - /// - public const int WaterSystem = 5; - /// - /// 能源系统 - /// - public const int EnergySystem = 11; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs deleted file mode 100644 index 6cf939f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/Enumeration2.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; - -namespace WeiCloud.Core.EnumTools -{ - - [Serializable] - [DebuggerDisplay("{DisplayName} - {Value}")] - public abstract class Enumeration2 : IComparable, IEquatable - where TEnumeration : Enumeration2 - where TValue : IComparable - { - private static readonly Lazy Enumerations = new Lazy(GetEnumerations); - - [DataMember(Order = 1)] private readonly string _displayName; - - [DataMember(Order = 0)] private readonly TValue _value; - - protected Enumeration2(TValue value, string displayName) - { - if (value == null) throw new ArgumentNullException(nameof(value)); - - _value = value; - _displayName = displayName; - } - - public TValue Value => _value; - - public string DisplayName => _displayName; - - public int CompareTo(TEnumeration other) - { - return Value.CompareTo(other == default(TEnumeration) ? default(TValue) : other.Value); - } - - public bool Equals(TEnumeration other) - { - return other != null && ValueEquals(other.Value); - } - - public sealed override string ToString() - { - return DisplayName; - } - - public static TEnumeration[] GetAll() - { - return Enumerations.Value; - } - - private static TEnumeration[] GetEnumerations() - { - var enumerationType = typeof(TEnumeration); - return enumerationType - .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) - .Where(info => enumerationType.IsAssignableFrom(info.FieldType)) - .Select(info => info.GetValue(null)) - .Cast() - .ToArray(); - } - - public override bool Equals(object obj) - { - return Equals(obj as TEnumeration); - } - - public override int GetHashCode() - { - return Value.GetHashCode(); - } - - public static bool operator ==(Enumeration2 left, - Enumeration2 right) - { - return Equals(left, right); - } - - public static bool operator !=(Enumeration2 left, - Enumeration2 right) - { - return !Equals(left, right); - } - - public static TEnumeration FromValue(TValue value) - { - return Parse(value, "value", item => item.Value.Equals(value)); - } - - public static TEnumeration Parse(string displayName) - { - return Parse(displayName, "display name", item => item.DisplayName == displayName); - } - - private static bool TryParse(Func predicate, out TEnumeration result) - { - result = GetAll().FirstOrDefault(predicate); - return result != null; - } - - private static TEnumeration Parse(object value, string description, Func predicate) - { - if (TryParse(predicate, out var result)) - return result; - return null; - } - - public static bool TryParse(TValue value, out TEnumeration result) - { - return TryParse(e => e.ValueEquals(value), out result); - } - - public static bool TryParse(string displayName, out TEnumeration result) - { - return TryParse(e => e.DisplayName == displayName, out result); - } - - protected virtual bool ValueEquals(TValue value) - { - return Value.Equals(value); - } - - public static bool Any(Func predicate) - { - return GetAll().Any(predicate); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs deleted file mode 100644 index da60124..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EqGroupTypeEnum.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Core.RulesEngine.RulesModels; - -namespace WeiCloud.Core.EnumTools -{ - public static class EqGroupTypeEnum - { - /// - /// 分区能耗 - /// - public const short Digital_EnergyConsumZone = 20;//分区能耗 - /// - /// 分区能耗 - /// - public const short EnergyConsumZone = 1;//分区能耗 - /// - /// 规则引擎 - /// - public static short RuleEngine = 2;//规则引擎 - /// - /// 计算引擎 - /// - public static short EalculationEngine = 3;//计算引擎 - /// - /// 其他 - /// - public static short Other = 99;//其他 - /// - /// 支路 - /// - public static short AccessRd = 14; - /// - /// 数字孪生设备运行分组 - /// - public static short EquipRun = 15; - /// - /// 电梯系统 - /// - public static short ElevatorZone = 17; - /// - /// 照明系统 - /// - public static short LightingZone = 18; - /// - /// 能效分区 - /// - - public static short EnergyEfficiencyConsumZone = 19; - - /// - /// 系统评价 - /// - - public static short GroupType_SysDiagnosis = 12; - /// - /// 分项 - /// - public static short SubItem = 25; - /// - /// 历史参数 - /// - public static short HisParm = 26; - /// - /// 项目总能耗 - /// - public static short ProjectTotalEnergyConsum = 32; - /// - /// 能效分区(能耗模型) - /// - - public static short EnergyEfficiencyConsumZoneV02 = 50; - /// - /// 能效分区(能效看板) - /// - - public static short EnergyEfficiencyConsumZoneBulletinBoard = 51; - /// - /// App视频监控 - /// - - public static short AppVideo = 200; - /// - /// 数据分析-分项 - /// - public static short EngeryAnalisysItem = 201; - /// - /// 园区企业能耗 - /// - public static short IndustrialParkEnergy = 46; - - /// - /// AI 工况巡优 - /// - public static short AIConOpt { get; set; } = 399; - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs deleted file mode 100644 index f7531c0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipRuningStatus.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public class EquipRuningStatus : Enumeration - { - //设备运行状态枚举表示 - public EquipRuningStatus(int value, string displayName) : base(value, displayName) - { - } - //停止 - public static readonly EquipRuningStatus stop = new EquipRuningStatus(0, nameof(stop).ToLowerInvariant()); - //启动 - public static readonly EquipRuningStatus start = new EquipRuningStatus(1, nameof(start).ToLowerInvariant()); - //故障 - public static readonly EquipRuningStatus fail = new EquipRuningStatus(2, nameof(fail).ToLowerInvariant()); - //中断 - public static readonly EquipRuningStatus signal = new EquipRuningStatus(3, nameof(signal).ToLowerInvariant()); - ////电梯上行 - //public static readonly EquipRuningStatus up = new EquipRuningStatus(3, nameof(up).ToLowerInvariant()); - ////电梯下行 - //public static readonly EquipRuningStatus down = new EquipRuningStatus(4, nameof(down).ToLowerInvariant()); - ////直梯当前楼层 - //public static readonly EquipRuningStatus num = new EquipRuningStatus(4, nameof(down).ToLowerInvariant()); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs deleted file mode 100644 index eac0135..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/EquipTypeEnum.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class EquipTypeEnum - { - /// - /// 仪表类型Code - /// - public const string InstrumentTypeCode = "eq128"; - /// - /// 电表类型Code - /// - public const string ElectricityMeterTypeCode = "eq128016"; - /// - /// 水表类型Code - /// - public const string WaterMeterTypeCode = "eq128017"; - /// - /// 气表类型Code - /// - public const string GasMeterTypeCode = "eq128018"; - /// - /// 热表类型Code - /// - public const string HeatMeterTypeCode = "eq128019"; - /// - /// 通讯模块 - /// - public const string PLCTypeCode = "eq038"; - - /// - /// 空调主机 - /// - public const string AirHostCode = "eq126001"; - /// - /// 冷却水循环泵 - /// - public const string FCCCode = "eq002005"; - /// - /// 冷却水补水泵 - /// - public const string CoolingWaterMakeUpCode = "eq002006"; - /// - /// 冷温水循环泵 - /// - public const string ColdWarmWaterCirculatingCode = "eq002003"; - /// - /// 冷温水补水泵 - /// - public const string ColdWarmWaterMakeUpCode = "eq002004"; - /// - /// 热水循环泵 - /// - public const string HPKCode = "eq002078"; - /// - /// 末端新风 - /// - public const string TerminalFreshAirCode = "eq013059"; - /// - /// 风机盘管 - /// - public const string FCUCode = "eq013014"; - /// - /// 热风幕 - /// - public const string HotAirCurtainCode = "eq013031"; - /// - /// 污水排水泵 - /// - public const string SewageDrainagePumpCode = "eq002033"; - /// - /// 生活水给水泵 - /// - public const string DomesticWaterSupplyPumpCode = "eq137"; - /// - /// 变压器温控器 - /// - public const string TransfTemperControCode = "eq125061"; - /// - /// 中交世通变压器温控器 - /// - public const string STTransfTemperControCode = "eq471718840970272"; - /// - /// 高压综保 - /// - public const string HighVoltageIntegProteCode = "eq125062"; - /// - /// 低压柜 - /// - public const string LowVoltageCabinetCode = "eq125065"; - /// - /// 给排水设备 - /// - public const string WaterSupplyDraeEquipCode = "eq002"; - /// - /// 室内照明 - /// - public const string IndoorLightingCode = "eq136069"; - /// - /// 室外照明 - /// - public const string OutdoorLightingCode = "eq136070"; - /// - /// 广告灯箱 - /// - public const string AdvertisingLightBoxCode = "eq136071"; - /// - /// 照明设备 - /// - public const string LightEquipCode = "eq136"; - /// - /// 空调风系统 - /// - public const string AirConditioningSystemCode = "eq126013"; - /// - /// 纯新风空调机组 - /// - public const string OnlyAirGroupCode = "eq013122"; - /// - /// 纯新风空调机组 - /// - public const string ReturnBackAirGroupCode = "eq013123"; - /// - /// 组合式空调机组 - /// - public const string ColectionAirGroupCode = "eq013124"; - - /// - /// 电梯 - /// - public const string ElevatorCode = "eq028"; - /// - /// 直梯 - /// - public const string VerticalLadderCode = "eq028029"; - /// - /// 货梯 - /// - public const string CargoLift = "eq028029479591567333920"; - /// - /// 客梯 - /// - public const string Elevator = "eq028029479591577861664"; - /// - /// 扶梯 - /// - public const string EscalatorCode = "eq028030"; - /// - /// 温湿度传感器 - /// - public const string TempHumSensorCode = "eq020036"; - /// - /// 照度传感器 - /// - public const string IllumSensorCode = "eq020037"; - /// - /// 高压综保 - /// - public const string HighVoltageProtection = "eq125062"; - /// - /// 液位传感器 - /// - public const string LiqueLevelCode = "eq020023"; - /// - /// 光伏并网柜 - /// - public const string PVCode = "eq468321121415712"; - /// - /// 燃气内燃发电机组 - /// - public const string OilElectricEngineCode = "468276635161120"; - /// - /// 直燃型吸收式机组 - /// - public const string DirectFiredUnitCode = "eq001039"; - /// - /// 开关阀 - /// - public const string OpenCloseSwichCode = "eq127109"; - /// - /// 冷却塔风扇 - /// - public const string CoolingTower = "eq126032"; - /// - /// 空气质量传感器 - /// - public const string AirQuatity = "eq020097"; - /// - /// 温度传感器 - /// - public const string TempEquip = "eq020075"; - /// - /// 压力传感器 - /// - public const string PressEquip = "eq020113"; - /// - /// 虚拟设备/控制柜 - /// - public const string AbstractEquip = "eq470527720737824"; - /// - /// 控制面板 - /// - public const string ControlEquip = "eq470577169286176"; - /// - /// 视频摄像头 - /// - public const string ViewCode = "eq104"; - /// - /// 中水泵 - /// - public const string CWarterPump = "eq471054413443104"; - /// - /// 风冷机组 - /// - public const string AirCooledUnit = "eq001120"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs deleted file mode 100644 index 41d72c0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FamilyDecorationEnum.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public class FamilyDecorationEnum - { - public static Dictionary ProjectContractDocDic = new Dictionary { { 1, "合同文件" }, { 2, "报价单" }, { 3, "施工单" }, { 4, "设计图纸" } }; - /// - /// 家装管理员 - /// - public static readonly long FamilyDecorationAdminId = 484988093582368; - /// - /// 国润丰泽-业主 - /// - public static readonly long FamilyDecorationOwnerId = 482689495630880; - #region 部门 - /// - /// 国润丰泽-部门 - /// - public static readonly long FamilyDecorationGroupId = 482689495703584; - /// - /// 客户-部门 - /// - public static readonly long FamilyDecorationCustomerGroupId = 486331178355744; - /// - /// 销售-部门 - /// - public static readonly long FamilyDecorationSaleGroupId = 483536378644000; - #endregion - - #region 角色 - /// - /// 客户-角色 - /// - public static readonly long FamilyDecorationCustomerRoleId = 484284962365984; - /// - /// admin-角色 - /// - public static readonly long FamilyDecorationAdminRoleId = 483536405638176; - #endregion - /// - /// 角色权限,缓存key - /// - public static readonly string RoleFunPermissionCacheKey = "RoleFunPermission_{0}"; - /// - /// 项目角色权限,缓存key - /// - public static readonly string ProjectRoleFunPermissionCacheKey = "ProjectRoleFunPermission_{0}"; - } - public enum FamilyDecorationFormDocType - {//1-text、2-textarea、3-fileupload - Text = 1, - TextArea = 2, - FileUpload = 3 - } - public enum ProjectPlanStatusEnum - { - /// - /// 未开始 - /// - NotStarted = 0, - /// - /// 进行中 - /// - Processing = 1, - Completed = 2 - } - public enum ProjectStatusEnum - { - /// - /// 未进场 - /// - NotMobilized = 1, - /// - /// 已进场 - /// - AlreadyMobilized = 2, - /// - /// 已完工 - /// - Completed = 3 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs deleted file mode 100644 index bbfa3d1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FauabnormalEnum.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public class FauabnormalEnum - { - /// - /// 设备故障 - /// - public const long EquipDamage = 1; - /// - /// 参数超限 - /// - public const long ParamBeyond = 2; - /// - /// 视频报警 - /// - public const long ViewAlarm = 3; - /// - /// 能耗异常 - /// - public const long EnergyAbnormal = 4; - /// - /// 通讯中断 - /// - public const long Comloss = 5; - /// - /// 事件报警 - /// - public const long EventAlarm = 6; - /// - /// 维保报警 - /// - public const long MaintenAlarm = 7; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs deleted file mode 100644 index 1e8521f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultHandleEnum.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class FaultHandleEnum - { - /// - /// 误报 - /// - public const long ErrorInfo = 1; - /// - /// 设备调试 - /// - public const long Handdle = 2; - /// - /// 转工单 - /// - public const long TurnWorkFlow = 3; - /// - /// 忽略 - /// - public const long Ignore = 4; - /// - /// 复位 - /// - public const long Reset= 5; - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs deleted file mode 100644 index 8a57098..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FaultStatusEnum.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class FaultStatusEnum - { - /// - /// 发生故障 - /// - public const long FaultHappen = 1; - /// - /// 忽略 - /// - public const long Ignore = 2; - /// - /// 处理中 - /// - public const long Handle = 3; - /// - /// 已复位 - /// - public const long ArtificialHandle= 4; - /// - /// 已压制 - /// - public const long SystemHandle = 5; - /// - /// 关闭 - /// - public const long CloseHandle = 6; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs deleted file mode 100644 index 35b75d5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/FunPermissionEnum.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public enum FunPermissionEnum - { - Page = 1, - Func = 2, - Form = 3 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs deleted file mode 100644 index de2cfa3..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/GearEnum.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 控制面板的低档、中档、高档、自动设定 ccx202012-15 - /// - public static class GearEnum - { - //低档 - public static readonly short LowGear = 1; - //中档 - public static readonly short MiddleGear = 2; - //高档 - public static readonly short HightGear = 3; - //自动 - public static readonly short AutomoGear = 4; - - } - public static class ModeEnum - { - //制冷 - public static readonly short CoolMode = 1; - //制热 - public static readonly short HeatMode = 2; - //送风 - public static readonly short WindMode = 3; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs deleted file mode 100644 index ac6e190..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/HandWritetenEnum.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class HandWritetenEnum - { - public const short Month=1; - public const short Day =2; - public const short Hour = 3; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs deleted file mode 100644 index 02143cd..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/InfoApiEnum.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core -{ - /// - /// infoapi所有枚举值 - /// - internal class InfoApiEnum - { - } - /// - /// 0-自定义,1-时,2-天,3-月,4-年(查询时日期类型) - /// - public enum QueryTimeTypeEnum - { - Custom = 0, - Hour = 1, - Day = 2, - Month = 3, - Year = 4 - } - /// - /// 1-项目、2-空间、3-设备、4-参数 - /// - public enum IOTThingTypeEnum - { - Project = 1, - Construct = 2, - Equip = 3, - Param = 4 - } - public enum IOTLabelTypeEnum - { - /// - /// 能耗 - /// - EnergyConsum = 1 - } - /// - /// Equip\Consturct\Time - /// - public class IOTLabelDimensionEnum - { - /// - /// 设备 - /// - public static string Equip = "Equip"; - /// - /// 建筑物 - /// - public static string Consturct = "Consturct"; - /// - /// 时间(小时) - /// - public static string TimeHour = "TimeHour"; - /// - /// 时间(天) - /// - public static string TimeDay = "TimeDay"; - /// - /// 时间(月) - /// - public static string TimeMonth = "TimeMonth"; - /// - /// 时间(年) - /// - public static string TimeYear = "TimeYear"; - } - public enum IOTLabelCalculateEnum - { - Sum = 1, - Count = 2, - Max = 3, - Min = 4, - Average = 5, - /// - /// 去重 - /// - DuplicateRemoval = 6 - } - #region 策略 - public enum StratePlanGroupExecStateEnum - { - /// - /// 未开始 - /// - Unexecuted = 0, - /// - /// 已开始 - /// - Started = 1, - /// - /// 执行成功 - /// - ExecutionSucceeded = 2, - /// - /// 执行失败 - /// - ExecutionFailed = 3 - } - #endregion - - #region 参数类型 - /// - /// 实时参数类型 - /// - public enum RealPointTypeEnum - { - /// - /// 实时点 - /// - Real = 1, - /// - /// 计算点 - /// - Cal = 2, - Target = 3 - } - /// - /// 指标参数类型 - /// - public enum LabelPointTypeEnum - { - /// - /// 能耗值 - /// - EnergyConsum = 1, - /// - /// 当日能耗 - /// - TodayEnergyConsum = 2 - } - #endregion - - #region 舒适home - public enum ConformHomeTenantAuthCacheEnum - { - /// - /// 业主 - /// - ActivateOwner = 1, - /// - /// 其他成员 - /// - ActivateMember = 2 - } - #endregion - - #region 指标 - public enum TargetCalculationTypeEnum - { - /// - /// 物联参数聚合 - /// - ThingParam = 1, - /// - /// 多指标公式 - /// - MultipleIndicatorFormula = 2, - /// - /// 平台引用 - /// - PlatformRef = 3 - } - public enum TargetCalculateParamCalIntervalEnum - { - /// - /// 每小时 - /// - EveryHour = 1, - /// - /// 每天 - /// - EveryDay = 2 - } - public class TargetCalculateParamCalCronEnum - { - /// - /// 每小时 - /// - public static string EveryHour = "0 0 0/1 * * ?"; - /// - /// 每天 - /// - public static string EveryDay = "0 0 0 1/1 * ?"; - } - /// - /// 参数取值类型 - /// - public enum TargetCalculateParamCalTypeEnum - { - /// - /// 最大值 - /// - Max = 1, - /// - /// 最小值 - /// - Min = 2, - /// - /// 平均值 - /// - Avg = 3, - /// - /// 计数 - /// - Count = 4, - /// - /// 差值 - /// - DValue = 5, - /// - /// 求和 - /// - Sum = 6 - } - public enum PlatformDataTypeEnum - { - /// - /// 能源计费 - /// - EnergyBilling = 1, - /// - /// 能耗定额 - /// - EnergyConsumQuota = 2 - } - #endregion - #region 节能量 - public enum EnergySavingTimeTypeEnum - { - Custom = 0, - Month = 1, - Year = 2 - } - #endregion -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs deleted file mode 100644 index d9dd109..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/IotDsEnum.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - internal class IotDsEnum - { - } - /// - /// 标签类型 - /// - public enum IotDsLabelTypeEnum - { - Type = 1, - ParamType = 2, - Extend = 3 - } - /// - /// 参数扩展标签 - /// - public class IotDsParamExtendLabelEnum - { - /// - /// 能耗计算 - /// - public static string DWCode = "DW"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs deleted file mode 100644 index 8145d74..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/KBEnum.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class KBCategoryEnum - { - public const short QA = 1; - public const short Article = 2; - public const short Sys = 3; - } - public static class KBContentTypeEnum - { - public const short Text = 1; - public const short Word = 2; - public const short Mp4 = 3; - public const short Html = 4; - public const short Pdf = 5; - } - public static class KBFileEnum - { - public const string FilePath = "KB"; - } - public static class KBUserActionTypeEnum - { - public const short Like = 1; - public const short Collection = 2; - } - public static class KBEnum - { - public const int ContentShowLen = 200; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs deleted file mode 100644 index f5cfc90..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MenuTypeEnum.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class MenuTypeEnum - { - //平台模块 - public static readonly short Model = 0; - //第三方 - public static readonly short Other = 1; - //组态3 - public static readonly short Config = 2; - //看板 - public static readonly short Board = 3; - //第三方嵌入 - public static readonly short OtherEmbed = 4; - //组态4 - public static readonly short Config4 = 5; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs deleted file mode 100644 index cae0780..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/MsgServiceEnum.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public enum MsgServiceEnum - { - - } - /// - /// 服务商 - /// - public enum MsgServiceProviderEnum - { - /// - /// 自定义 - /// - Custom = 1, - /// - /// 阿里云 - /// - Aliyun = 2 - } - /// - /// 服务商 - /// - public enum MsgServiceTypeEnum - { - /// - /// 自定义 - /// - Custom = 0, - /// - /// 阿里云 - /// - Aliyun = 1 - } - public enum MsgTemplateTypeEnum - { - /// - /// 站内消息 - /// - [Description("站内消息")] - Internal = 1, - /// - /// 短信 - /// - [Description("短信")] - SMS = 2, - /// - /// App - /// - [Description("App")] - App = 3, - /// - /// 语音 - /// - [Description("语音")] - Voice = 4 - } - public enum MsgServiceApplyEnum - { - [Description("邮件")] - Email = 1, - [Description("短信")] - SMS = 2, - [Description("APP")] - App = 3, - [Description("语音")] - Voice = 4 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs deleted file mode 100644 index 6b5475f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NlogTypeNum.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class NlogTypeNum - { - //普通日志 - public static readonly int Normal = 1; - //设备操作日志 - public static readonly int EquipControl = 2; - //设备超权日志 - public static readonly int EquipPress = 3; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs deleted file mode 100644 index 99341cb..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/NormUnitNum.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class NormUnitNum - { - /// - /// 每平方米年均能耗千瓦时 - /// - public static string YearAvergAqueraEnergyKwh = "kWh/(㎡*a)"; - - public static string YearAvergAqueraEnergyGJ = "GJ/(㎡*a)"; - public static string YearAvergAqueraEnergyKgce = "kgce/(㎡*a)"; - public static string YearAvergAqueraEnergyNm3 = "Nm³/(㎡*a)"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs deleted file mode 100644 index 7fbd4c4..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/PayEnum.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 付款方式 - /// - public enum PayMethodEnum - { - /// - /// 微信付款码 - /// - WxAuthCode = 1, - /// - /// 微信支付 - /// - Wx = 2, - /// - /// 现金 - /// - Cash = 3 - } - public enum PayOrderStateEnum - { - Unpaid = 0, - Paid = 1, - } - /// - /// 付款结果 - /// - public enum PayResultEnum - { - Success = 1, - Fail = 2 - } - public enum PayCustomerTypeEnum - { - /// - /// 供热 - /// - HeatMeter = 1 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs deleted file mode 100644 index de8ff75..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/ProAlarm.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public enum ProAlarmLevelEnum - { - /// - /// 重大 - 最高级别,需要立即处理 - /// - [Description("重大")] - Critical = 1, - - /// - /// 严重 - 严重问题,需尽快处理 - /// - [Description("严重")] - Major = 2, - - /// - /// 一般 - 中等优先级,需跟踪处理 - /// - [Description("一般")] - Minor = 3, - - /// - /// 轻微 - 低优先级,观察即可 - /// - [Description("轻微")] - Warning = 4 - } - public enum ProAlarmStatus - { - /// - /// 未处理 - 报警尚未被查看或确认 - /// - [Description("未处理")] - Unhandled = 0, - - /// - /// 处理中 - 报警已被确认,处理进行中 - /// - [Description("处理中")] - InProgress = 1, - - /// - /// 无需处理 - 判断无需干预或响应 - /// - [Description("无需处理")] - NoActionRequired = 2, - - /// - /// 误报 - 报警是错误的或无效的 - /// - [Description("误报")] - FalseAlarm = 3, - - /// - /// 已完成 - 报警处理流程已完成 - /// - [Description("已完成")] - Completed = 4 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs deleted file mode 100644 index 6cf32a0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/RealDataValueTypeEnum.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core -{ - public class RealDataValueTypeEnum : Enumeration - { - public RealDataValueTypeEnum(int value, string displayName) : base(value, displayName) - { - } - public static readonly RealDataValueTypeEnum allEnum = new RealDataValueTypeEnum(0, nameof(boolEnum).ToLowerInvariant()); - //1. 开关量 - public static readonly RealDataValueTypeEnum boolEnum = new RealDataValueTypeEnum(1, nameof(boolEnum).ToLowerInvariant()); - //2. 十进制码 - public static readonly RealDataValueTypeEnum intEnum = new RealDataValueTypeEnum(2, nameof(intEnum).ToLowerInvariant()); - //3. 01串 - public static readonly RealDataValueTypeEnum stringEnum = new RealDataValueTypeEnum(3, nameof(stringEnum).ToLowerInvariant()); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs deleted file mode 100644 index 875600b..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/STTargetCategoryEnum.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 指标枚举值 - /// - public class STTargetCategoryEnum : Enumeration2 - { - - /// - /// 能效体检冷源类型数据分类 - /// - public static readonly STTargetCategoryEnum ColdSourceType = new STTargetCategoryEnum(6, "冷源类型"); - - - /// - /// 能源体检指标名称数据分类 - /// - public static readonly STTargetCategoryEnum EnergyExamTargetNameType = new STTargetCategoryEnum(9, "能源体检指标名称数据"); - - - private STTargetCategoryEnum(int value, string displayName) : base(value, displayName) - { - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs deleted file mode 100644 index ab7ee65..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SafetyEnum.cs +++ /dev/null @@ -1,619 +0,0 @@ -using Google.Protobuf.WellKnownTypes; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - - /// - /// 报警处置状态枚举 - /// - public class AlarmStatusEnum : Enumeration2 - { - - public static readonly AlarmStatusEnum NoAccept = new AlarmStatusEnum(0, "未受理"); - public static readonly AlarmStatusEnum Accepted = new AlarmStatusEnum(1, "已受理"); - public static readonly AlarmStatusEnum HasSendWork = new AlarmStatusEnum(2, "已派工"); - public static readonly AlarmStatusEnum FinishedJob = new AlarmStatusEnum(3, "已完成"); - - - private AlarmStatusEnum(int value, string displayName) : base(value, displayName) - { - } - } - - - - //m, 逗号11 - - - /// - /// 报警受理结果枚举 - /// - public class AlarmAcceptRes : Enumeration2 - { - - - /// - /// 确警 - /// - public static readonly AlarmAcceptRes AlarmYes = new AlarmAcceptRes(1, "确警"); - - /// - /// 误报 - /// - public static readonly AlarmAcceptRes AlarmFalse = new AlarmAcceptRes(2, "误报"); - - /// - /// 演习 - /// - public static readonly AlarmAcceptRes AlarmDrill = new AlarmAcceptRes(3, "演习"); - - - private AlarmAcceptRes(int value, string displayName) : base(value, displayName) - { - } - } - - - - - /// - /// 消防预案执行状态枚举 - /// - public class ExeStatusEnum : Enumeration2 - { - /// - /// 未开始 - /// - public static readonly ExeStatusEnum NoBegin = new ExeStatusEnum(1, "未开始"); - - /// - /// 进行中 - /// - public static readonly ExeStatusEnum Exeing = new ExeStatusEnum(2, "进行中"); - - /// - /// 已完成 - /// - public static readonly ExeStatusEnum ExeOver = new ExeStatusEnum(3, "已完成"); - - - private ExeStatusEnum(int value, string displayName) : base(value, displayName) - { - } - } - - - /// - /// 预案流程步骤执行状态枚举 - /// - public class PlanProcessStepEnum : Enumeration2 - { - //[{"Key":1,"Value":"报警推送"},{"Key":2,"Value":"确警推送"},{ "Key":3,"Value":"拨打报警电话"},{ "Key":4,"Value":"派送任务至应急队伍"},{ "Key":5,"Value":"派送任务至附近人员"}] - - /// - /// 报警推送 - /// - public static readonly PlanProcessStepEnum AlarmPush = new PlanProcessStepEnum(1, "报警推送"); - - /// - /// 确警推送 - /// - public static readonly PlanProcessStepEnum AlarmYesPush = new PlanProcessStepEnum(2, "确警推送"); - - /// - /// 拨打报警电话 - /// - public static readonly PlanProcessStepEnum AlarmCall = new PlanProcessStepEnum(3, "拨打报警电话"); - - /// - /// 派送任务至应急队伍 - /// - public static readonly PlanProcessStepEnum SendToEmergency = new PlanProcessStepEnum(4, "派送任务至应急队伍"); - - /// - /// 派送任务至附近人员 - /// - public static readonly PlanProcessStepEnum SendToNearby = new PlanProcessStepEnum(5, "派送任务至附近人员"); - - - - - private PlanProcessStepEnum(int value, string displayName) : base(value, displayName) - { - } - } - - /// - /// 预案流程执行动作枚举 - /// - public class PushTypeEnum : Enumeration2 - { - - - /// - /// 自动 - /// - public static readonly PushTypeEnum Auto = new PushTypeEnum(1, "自动"); - - /// - /// 手动 - /// - public static readonly PushTypeEnum Manual = new PushTypeEnum(2, "手动"); - - - - - private PushTypeEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - /// - /// 警情级别 - /// - public class AlarmLevelEnum : Enumeration2 - { - - //[{"Key":1,"Value":"紧急"},{"Key":2,"Value":"重要"},{ "Key":3,"Value":"一般"},{ "Key":4,"Value":"轻微"}] - - /// - /// 紧急 - /// - public static readonly AlarmLevelEnum Urgency = new AlarmLevelEnum(1, "紧急"); - - /// - /// 重要 - /// - public static readonly AlarmLevelEnum Importance = new AlarmLevelEnum(2, "重要"); - - /// - /// 一般 - /// - public static readonly AlarmLevelEnum Ordinary = new AlarmLevelEnum(3, "一般"); - - /// - /// 轻微 - /// - public static readonly AlarmLevelEnum Slight = new AlarmLevelEnum(4, "轻微"); - - - - - private AlarmLevelEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - - - /// - /// 预案流程执行动作枚举 - /// - public class CallStatusEnum : Enumeration2 - { - - - /// - /// 接通 - /// - public static readonly CallStatusEnum Auto = new CallStatusEnum(1, "接通"); - - /// - /// 未接通 - /// - public static readonly CallStatusEnum Manual = new CallStatusEnum(2, "未接通"); - - - - - private CallStatusEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - - /// - /// 出入口设备类型 - /// - public class CarAssetTypeEnum : Enumeration2 - { - - /// - /// 入场 - /// - public static readonly CarAssetTypeEnum Entry = new CarAssetTypeEnum(1, "入场"); - - /// - /// 出场 - /// - public static readonly CarAssetTypeEnum Out = new CarAssetTypeEnum(2, "出场"); - - private CarAssetTypeEnum(int value, string displayName) : base(value, displayName) - { - } - } - - /// - /// 车辆设备类型 1未出场 2已出场 - /// - public class CarStatusEnum : Enumeration2 - { - - /// - /// 未出场 - /// - public static readonly CarStatusEnum InPark = new CarStatusEnum(1, "未出场"); - - /// - /// 已出场 - /// - public static readonly CarStatusEnum OutPark = new CarStatusEnum(2, "已出场"); - - private CarStatusEnum(int value, string displayName) : base(value, displayName) - { - } - } - - - /// - /// 巡检要点类型 - /// - public class KeyPointTypeEnum : Enumeration2 - { - - - /// - /// 无 - /// - public static readonly KeyPointTypeEnum NoThing = new KeyPointTypeEnum(1, "无"); - - /// - /// 数值填空 - /// - public static readonly KeyPointTypeEnum NumericalRangeFilling = new KeyPointTypeEnum(2, "数值填空"); - - /// - /// 选项填空 - /// - public static readonly KeyPointTypeEnum OptionFilling = new KeyPointTypeEnum(3, "选项填空"); - - /// - /// 文本填空 - /// - public static readonly KeyPointTypeEnum TextFilling = new KeyPointTypeEnum(4, "文本填空"); - - private KeyPointTypeEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - /// - /// 巡检要点类型 - /// - public class TaskPointTypeEnum : Enumeration2 - { - - - /// - /// 设备任务点 - /// - public static readonly TaskPointTypeEnum AssetType = new TaskPointTypeEnum(1, "设备任务点"); - - /// - /// 空间任务点 - /// - public static readonly TaskPointTypeEnum PositionType = new TaskPointTypeEnum(2, "空间任务点"); - - /// - /// 风险点任务点 - /// - public static readonly TaskPointTypeEnum FxType = new TaskPointTypeEnum(3, "风险点任务点"); - - - private TaskPointTypeEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - - - /// - /// 任务计划周期类型 - /// - public class PeriodTypeDescEnum : Enumeration2 - { - - - /// - /// 单次 - /// - public static readonly PeriodTypeDescEnum Once = new PeriodTypeDescEnum(1, "单次"); - - /// - /// 每日 - /// - public static readonly PeriodTypeDescEnum Daily = new PeriodTypeDescEnum(2, "每日"); - - /// - /// 每周 - /// - public static readonly PeriodTypeDescEnum Weekly = new PeriodTypeDescEnum(3, "每周"); - - /// - /// 每月 - /// - public static readonly PeriodTypeDescEnum Monthy = new PeriodTypeDescEnum(4, "每月"); - - /// - /// 每季度 - /// - public static readonly PeriodTypeDescEnum Quarterly = new PeriodTypeDescEnum(5, "每季度"); - - /// - /// 每年 - /// - public static readonly PeriodTypeDescEnum Yearly = new PeriodTypeDescEnum(6, "每年"); - - - private PeriodTypeDescEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - - // 0未开始 1未完成 2已完成 3已超时 - /// - /// 任务计划周期类型 - /// - public class XjTaskInstanceExeStatusEnum : Enumeration2 - { - - - /// - /// 未开始 - /// - public static readonly XjTaskInstanceExeStatusEnum NoBegin = new XjTaskInstanceExeStatusEnum(0, "未开始"); - - /// - /// 未完成 - /// - public static readonly XjTaskInstanceExeStatusEnum NoCompleted = new XjTaskInstanceExeStatusEnum(1, "未完成"); - - /// - /// 已完成 - /// - public static readonly XjTaskInstanceExeStatusEnum Compeleted = new XjTaskInstanceExeStatusEnum(2, "已完成"); - - /// - /// 已超时 - /// - public static readonly XjTaskInstanceExeStatusEnum Timeout = new XjTaskInstanceExeStatusEnum(3, "已超时"); - - private XjTaskInstanceExeStatusEnum(int value, string displayName) : base(value, displayName) - { - } - - - } - - - /// - /// 巡检结果 - /// - public class InspectResultEnum : Enumeration2 - { - /// - /// 已巡 - /// - public static readonly InspectResultEnum HasInspect = new InspectResultEnum(1, "已巡"); - - /// - /// 未巡 - /// - public static readonly InspectResultEnum NoInspect = new InspectResultEnum(0, "未巡"); - - - - private InspectResultEnum(int value, string displayName) : base(value, displayName) - { - } - - } - - - - /// - /// 巡检是否合格 - /// - public class ScanResultEnum : Enumeration2 - { - /// - /// 已巡 - /// - public static readonly ScanResultEnum Pass = new ScanResultEnum(1, "合格"); - - /// - /// 未巡 - /// - public static readonly ScanResultEnum NoPass = new ScanResultEnum(0, "不合格"); - - - - private ScanResultEnum(int value, string displayName) : base(value, displayName) - { - } - - } - - - - /// - /// 警情上报临界值是否在阈值内 - /// - public class OperatorEnum : Enumeration2 - { - - /// - /// 等于 - /// - public static readonly OperatorEnum EQ = new OperatorEnum("=", "等于"); - - /// - /// 不等于 - /// - public static readonly OperatorEnum NE = new OperatorEnum("!=", "不等于"); - - /// - /// 小于 - /// - public static readonly OperatorEnum LT = new OperatorEnum("<", "小于"); - - /// - /// 小于等于 - /// - public static readonly OperatorEnum LE = new OperatorEnum("<=", "小于等于"); - - /// - /// 大于 - /// - public static readonly OperatorEnum GT = new OperatorEnum(">", "大于"); - - /// - /// 大于等于 - /// - public static readonly OperatorEnum GE = new OperatorEnum(">=", "大于等于"); - - - private OperatorEnum(string value, string displayName) : base(value, displayName) - { - } - - } - - //m, wdds - - /// - /// 工单状态 - /// - public class WoOrderStatusEnum : Enumeration2 - { - //m,指数/产品排序/,3001 - //m, 逗号11222 - /// - /// 未派工 - /// - public static readonly WoOrderStatusEnum Created = new WoOrderStatusEnum(1, "未派工"); - - - /// - /// 已派工 - /// - public static readonly WoOrderStatusEnum HasDistributed = new WoOrderStatusEnum(2, "已派工"); - - - /// - /// 部分完工 - /// - public static readonly WoOrderStatusEnum PartFinished = new WoOrderStatusEnum(3, "部分完工"); - - /// - /// 已完工 - /// - public static readonly WoOrderStatusEnum Finished = new WoOrderStatusEnum(4, "已完工"); - - /// - /// 已挂单 - /// - public static readonly WoOrderStatusEnum HangingOrder = new WoOrderStatusEnum(5, "已挂单"); - - /// - /// 已取消 - /// - public static readonly WoOrderStatusEnum Canceled = new WoOrderStatusEnum(6, "已取消"); - - - - private WoOrderStatusEnum(int value, string displayName) : base(value, displayName) - { - } - } - - - /// - /// 工单类型 - /// - - public class WoOrderTypeEnum : Enumeration2 - { - //1:警情处置 2:设备维修 3:设备保养 - - /// - /// 警情处置 - /// - public static readonly WoOrderTypeEnum AlarmDeal = new WoOrderTypeEnum(1, "警情处置"); - - - /// - /// 设备维修 - /// - public static readonly WoOrderTypeEnum AssetMaintain = new WoOrderTypeEnum(2, "设备维修"); - - - /// - /// 设备保养 - /// - public static readonly WoOrderTypeEnum AssetKeepInGood = new WoOrderTypeEnum(3, "设备保养"); - - - private WoOrderTypeEnum(int value, string displayName) : base(value, displayName) - { - } - } - - - /// - /// 工单来源 - /// - - public class WoOrderSourceEnum : Enumeration2 - { - - //1:事件报警 2:巡检报修 3:设备报警 - - /// - /// 事件报警 - /// - public static readonly WoOrderSourceEnum EventAlarm = new WoOrderSourceEnum(1, "事件报警"); - - /// - /// 巡检报修 - /// - public static readonly WoOrderSourceEnum AssetCheck = new WoOrderSourceEnum(2, "巡检报修"); - - /// - /// 设备报警 - /// - public static readonly WoOrderSourceEnum AssetAlarm = new WoOrderSourceEnum(3, "设备报警"); - - - private WoOrderSourceEnum(int value, string displayName) : base(value, displayName) - { - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs deleted file mode 100644 index 0c01c16..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/StandardCoalEnum.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 标煤换算 ccx 2020-09-17 - /// - public static class StandardCoalEnum - { - /// - /// 电能换算标煤 1 kWh=0.123 标煤 - /// - public static readonly double Electronic = 0.123; - /// - ///水能换算标煤 1t=0.086 标煤 - /// - public static readonly double Water = 0.086; - /// - /// 气能换算标煤 1 m³ =1.330 标煤 - /// - public static readonly double Gas = 1.330; - /// - /// 热力(当量值) kgce/MJ 0.03412 - /// - public static readonly double Heat = 0.034; - /// - /// 标煤换算二氧化碳 1吨标煤能量=2.6885吨CO2 - /// - public static readonly double CO2 = 2.6885; - /// - /// 每亩树林年减排CO2 1.336吨 - /// - public static readonly double EngeryChangeCO2 = 1.336; - /// - /// 亩换算公顷 1亩=0.0667公顷 - /// - public static readonly double MuChangeHectare = 0.0667; - - } - /// - /// 等效电法折算 - /// - public static class EquivalentElectricEnum - { - public static readonly double Water = 0; - /// - /// 气转电kWh - /// - public static readonly double Gas = 10;//7.133; - - public static readonly double StandardCoal = 3.691; - /// - /// 原煤 - /// - public static readonly double RawCoal = 2.640; - /// - /// 原油 - /// - public static readonly double Crude = 7.663; - /// - /// 柴油 - /// - public static readonly double DieselOil = 1.4571; - } - public class StandardCoalEnumNew - { - /// - /// 电能换算标煤 1 kWh=0.326 kg 标煤 - /// - public static readonly double Electronic = 0.326; - ///// - /////水能换算标煤 tce/m3 标煤 - ///// - public static readonly double Water = 0.0000857; - /// - /// 气能换算标煤 1 m³ =1.2286kg标煤 - /// - public static readonly double Gas = 1.2286; - /// - /// 柴油 1吨油当量=1.4286吨标准煤 - /// - public static readonly double Oil = 1.4286; - /// - /// 蒸汽 tce/ton - /// - public static readonly double Stream = 0.1286; - /// - /// 煤气 tce/m3 - /// - public static readonly double CoalGas = 0.00133; - /// - /// 热水 tce/m3 - /// - public static readonly double HotWater = 0.0000857; - /// - /// 1kWh= 0.0036GJ - /// - public static readonly double HotGJ = 0.0036; - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs deleted file mode 100644 index 23a5196..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SyaConfigNameEnum.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 全局参数名称 - /// - public static class SyaConfigNameEnum - { - /// - /// 集团云平台名称 - /// - public static readonly string OrganizationName = "OrganizationName"; - /// - /// 集团云平台中文名称 - /// - public static readonly string OrganizationChinaName = "集团云平台名称"; - /// - /// 项目云平台名称 - /// - public static readonly string ProjectStageName = "ProjectStageName"; - /// - /// 项目云平台中文名称 - /// - public static readonly string ProjectStageChinaName = "项目云平台名称"; - /// - /// 平台Logo - /// - public static readonly string StageLogo = "StageLogo"; - /// - /// 平台Logo中文名称 - /// - public static readonly string StageLogoLable = "平台Logo"; - /// - /// 系统参数类型 - /// - public static readonly long ConfigType = 0; - - public static readonly string Showlable = "是否显示网站备案信息"; - public static readonly string IsShow = "IsShowRecord"; - //public static readonly short? Show; - public static readonly string ShowMessagelable = "是否显示网站备案信息"; - public static readonly string ShowMessage = "RecordMessage"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs deleted file mode 100644 index a0ff828..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysBaseCodeMeta.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - /// - /// 系统元数据 - /// - public class SysBaseCodeMeta - { - /// - /// 类别 - /// - public static readonly string ProjectCodeTypePrefix = "pj"; - - public static readonly string ConstCodeTypePrefix = "cs"; - - public static readonly string AdminCode = "rl001"; - public static readonly string OwnerAdminCode = "rl002"; - - - //sysConfig - public static readonly int ParamType = 3; - /// - /// 碳排放因子 - /// - public static readonly long CarbonEmissionFactor = 506405592524320; - - //菜单 - public static readonly string MenuCode_YXJK = "c001";//运行监控 - public static readonly string MenuCode_PZGL = "x001";//配置管理 - /// - /// 管理员业主Id - /// - - public static readonly long AdminOwnerId = 0; - /// - /// 模块菜单关联 - /// - - public static readonly string SysModuleMenuMapHashId = "SysModuleMenuMap"; - #region 分组类型 - /// - /// 组-冷温水供水&回水温度 - /// - public static readonly short GroupType_LWS = 4; - /// - /// 组-冷却水供水&回水温度 - /// - public static readonly short GroupType_LQS = 5; - /// - /// 组-室外气象温度 - /// - public static readonly short GroupType_SWQX = 6; - - /// - /// 组-总能耗气 - /// - public static readonly short GroupType_ZNH_Q = 7; - /// - /// 组-总能耗电 - /// - public static readonly short GroupType_ZNH_D = 8; - - - /// - /// 组-主机-表 - /// - public static readonly short GroupType_ZJ_B = 9; - - /// - /// 组-系统-表 - /// - public static readonly short GroupType_XT_B = 10; - - /// - /// 组-室内空气传感器 - /// - public static readonly short GroupType_SNKQ = 11; - - - #endregion - - #region 企业 - public static readonly short EnterpriseType_Owner = 0;//业主 - public static readonly short EnterpriseType_PlatformManager = 1;//平台 - public static readonly short EnterpriseType_ThirdParty = 2;//第三方运维公司 - #endregion - - #region 系统诊断 - /// - /// 能效配置 - /// - public static readonly short SysDiagnosis_ConfigType_EnergyEffic = 1; - /// - /// 诊断配置 - /// - public static readonly short SysDiagnosis_ConfigType_Diagnosis = 2; - - /// - /// 优良值 - /// - public static readonly short SysDiagnosis_ValueType_YL = 1; - /// - /// 较差值 - /// - public static readonly short SysDiagnosis_ValueType_JC = 2; - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs deleted file mode 100644 index b87abd8..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/SysModuleEnum.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class SysModuleEnum - { - public const string FilePath = "sysmodule"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs deleted file mode 100644 index 78d6d77..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TaskApiEnum.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - internal class TaskApiEnum - { - } - public enum TimeTypeEnum - { - Hour = 1, - Day = 2, - Month = 3 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs deleted file mode 100644 index 179964e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TenantPayEnum.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core -{ - /// - /// 租户费用支付方式 - /// - public static class TenantPayWayEnum - { - /// - /// 线下支付 - /// - public static readonly short Offline = 1; - /// - /// 线上支付 - /// - public static readonly short ONline = 2; - } - public static class TenantPayTypeEnum - { - /// - /// 预付费 - /// - public static readonly int PrePay = 1; - /// - /// 线上支付 - /// - public static readonly int LastPay = 2; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs deleted file mode 100644 index caad043..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/TimeSpanEnum.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class TimeSpanEnum - { - /// - /// 5分钟 - /// - public static readonly short FiveMinute = 5; - /// - /// 10分钟 - /// - public static readonly short TenMinute = 10; - /// - /// 半小时 - /// - public static readonly short HalfHour = 30; - /// - /// 一小时 - /// - public static readonly short Hour = 60; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs deleted file mode 100644 index 88fda4d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/UserCenterApiEnum.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - internal class UserCenterApiEnum - { - } - /// - /// 账号登录状态 - /// - public enum AccountLoginEnum - { - /// - /// 在线 - /// - Online = 1, - /// - /// 离线 - /// - Offline = 2 - } - public enum UserMapClientTypeEnum - { - App = 1, - PC = 2, - SMS = 3 - } - //消息类型:1.工单 2.知识库,3.报警,4.计划,5.物业 6.场景通知消息 - public enum MsgTypeEnum - { - [Description("工单")] - WorkOrder = 1, - [Description("知识库")] - Knowledge = 2, - [Description("设备报警")] - Alarm = 3, - [Description("计划任务")] - Plan = 4, - [Description("物业通知")] - Scene = 5, - [Description("通知消息")] - Notice = 6, - [Description("场景通知消息")] - SceneNotice = 7, - [Description("安消报警")] - SafeFireProAlarm = 8, //消防报警 - } - public enum SysModuleTypeEnum - { - /// - /// 平台模块 - /// - Platform = 1, - /// - /// 项目模块 - /// - Project = 2, - /// - /// 个人中心 - /// - PersonCenter = 3 - } - /// - /// 日志分类 - /// - public enum LogTypeEnum - { - /// - /// 登录 - /// - Login = 1, - /// - /// 控制 - /// - Control = 2, - /// - /// 操作(模块功能) - /// - ModuleOper = 3, - /// - /// 用户行为 - /// - CustomerBehavior = 4 - } - public enum TerminalTypeEnum - { - /// - /// PC端 - /// - PC = 1, - /// - /// 移动端 - /// - APP = 2, - /// - /// 中控屏 - /// - CentralControlScreen = 3 - } - #region 中控屏 - public enum ConformHomeIdentityCodeEnum - { - - } - public class ConformHomeEnum - { - /// - /// 中控屏角色 - /// - public static readonly long CentralControlScreenRoleId = 509639289174048; - } - #endregion -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs b/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs deleted file mode 100644 index 3ce8224..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EnumTools/WorkOrderProConfig.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EnumTools -{ - public static class WorkOrderProConfig - { - - } - /// - /// 备品备件工单流程类型枚举 - /// - public static class ETEquipPartWorkOrderEnum - { - /// - /// 出库工单 - /// - public const short OutWorkOrder=1; - /// - /// 入库工单 - /// - public const short InWorkOrder = 2; - /// - /// 外借工单 - /// - public const short BorrowWorkOrder = 3; - } - /// - /// 计划管理工单流程类型枚举 - /// - public static class MaintenPLanWorkOrderEnum - { - /// - /// 巡检工单 - /// - public const short InspectionWorkOrder = 1; - /// - /// 维保工单 - /// - public const short MaintenanceWorkOrder = 2; - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs deleted file mode 100644 index 99e6a46..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/CapPublisherService.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using AutoMapper.Configuration; -using DotNetCore.CAP; -using Microsoft.Extensions.Logging; -using WeiCloud.Core.EventBus; -using Newtonsoft.Json; -using Microsoft.Extensions.Configuration; -using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration; - -namespace WeiCloud.Core.EventBus -{ - public class CapPublisherService : IPublisherService - { - private readonly ICapPublisher _capPublisher; - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - public CapPublisherService(ICapPublisher capPublisher, ILogger logger,IConfiguration configuration) - { - _capPublisher = capPublisher ?? throw new ArgumentNullException(nameof(capPublisher)); - _logger = logger ?? throw new ArgumentNullException(nameof(_logger)); - _configuration = configuration ?? throw new ArgumentNullException(nameof(_configuration)); - } - - public async Task PublishNoticeMsg(ProduceMsgModel notice) - { - notice.MsgTopic = "msgcenter.services.msg.notice"; - await _capPublisher.PublishAsync("msgcenter.services.msg.notice", notice); - - } - - public async Task PublishNoticeMsgByApi(ProduceMsgModel notice) - { - notice.MsgTopic = "msgcenter.services.msg.notice"; - if (string.IsNullOrEmpty(notice.Extend))//Extend不为空 - { - notice.Extend = ""; - - } - var message2 = JsonConvert.SerializeObject(notice); - string result = string.Empty; - Uri postUrl = new Uri(_configuration["CapPublishUrl"]); - - using (HttpContent httpContent = new StringContent(message2)) - { - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - using (var httpClient = new HttpClient()) - { - httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8"); - httpClient.Timeout = new TimeSpan(0, 0, 30); - HttpResponseMessage responseMessage = await httpClient.PostAsync(postUrl, httpContent); - if (responseMessage.IsSuccessStatusCode) - { - result = responseMessage.Content.ReadAsStringAsync().Result; - } - else - { - result = ""; - } - } - } - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs deleted file mode 100644 index adcd3e6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/FaultMsgModel.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EventBus -{ - public class ProduceMsgModel - { - public List UserIds { get; set; } - public long? EquId { get; set; } - public long Id { get; set; } - public string Content { get; set; } - public long? ProjectId { get; set; } - public string Title { get; set; } - public string Extend { get; set; } - public List SendTypes { get; set; } - public string MsgTopic { get; set; } - /// - /// 紧急程度 0正常 1紧急 2一般 3非常紧急 - /// - public short? EmergencyType { get; set; } = 0; - - /// - /// 消息类型1.工单 2.知识库,3.报警,4.计划 - /// - public short MsgType { get; set; } - - /// - /// 对应的业务Id - /// - public long? MainId { get; set; } - - /// - /// 设备名称 - /// - public string EquName { get; set; } - /// - /// 项目名称 - /// - public string ProjectName { get; set; } - /// - /// 项目简称 - /// - public string ProjectShortName { get; set; } - #region websocket - public string SubscribeAction { get; set; } - public string SubscribeFilter { get; set; } - #endregion - public DateTime CreatedAt { get; set; } = DateTime.Now; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs deleted file mode 100644 index 567192e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IBusinessMessageSubscriberEventBus.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.DataModels; - -namespace WeiCloud.Core.EventBus -{ - public interface IBusinessMessageSubscriberEventBus - { - Task BusinessNoticeMsg(BusinessNoticeMsgDto message); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs deleted file mode 100644 index 555c15a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IMessageSubscriberEventBus.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.DataModels; - -namespace WeiCloud.Core.EventBus -{ - public interface IMessageSubscriberEventBus - { - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs deleted file mode 100644 index 08e9c15..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/IPublisherService.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.EventBus -{ - /// - /// 消息总线 生产发布者 - /// - public interface IPublisherService - { - - public Task PublishNoticeMsgByApi(ProduceMsgModel notice); - /// - /// 发布通知消息 - /// - /// 消息内容 主要以 ProduceMsgModel - /// - public Task PublishNoticeMsg(ProduceMsgModel notice); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs deleted file mode 100644 index 2283c1f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MessageSubscriberEventBus.cs +++ /dev/null @@ -1,134 +0,0 @@ -using DotNetCore.CAP; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Threading.Tasks; -using WeiCloud.Core.Services.EquipPart; -using WeiCloud.Core.Services.Message; -using WeiCloud.Entity.LogicModels.DataModels; -using WeiCloud.Entity.LogicModels.EquipPart; - -namespace WeiCloud.Core.EventBus -{ - public class BusinessMessageSubscriberEventBus : IBusinessMessageSubscriberEventBus, ICapSubscribe - { - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - public BusinessMessageSubscriberEventBus(ILogger logger, IServiceScopeFactory serviceScopeFactory) - { - _logger = logger; - _serviceScopeFactory = serviceScopeFactory; - } - [CapSubscribe("info.services.business.msg")] - public async Task BusinessNoticeMsg(BusinessNoticeMsgDto message) - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"BusinessNoticeMsg in message:{JsonConvert.SerializeObject(message)}").GetNlogMessage().ToString()); - try - { - using var scope = _serviceScopeFactory.CreateScope(); - switch (message.BusinessType) - { - case 0: // 预留 暂时不处理 - break; - case 1: // 报警业务处理 - /*var faultHistoryService = ServiceLocator1.Instance.GetService(typeof(IFaultHistoryService)) as IFaultHistoryService; - await faultHistoryService.PutFaultHistoryReadStatus(businessMsg.BusinessId, 1);*/ - break; - case 2: // 巡检业务处理 - break; - case 3: // 维保业务处理 - break; - case 4: // 备品备件业务处理 - //调用service - _logger.LogInformation($"备品备件业务处理{JsonConvert.SerializeObject(message)}"); - var input = new ApproveItemModel - { - OrderId = message.OrderId, - ApplyId = message.BusinessId, - ApproverUserId = message.UserId, - ApproverTime = message.ExecTime, - Status = (short)message.Status - }; - var equipPartStockService = scope.ServiceProvider.GetRequiredService(); - await equipPartStockService.ApproveItem(input); - break; - default: - break; - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - } - public class MessageSubscriberEventBus : IMessageSubscriberEventBus, ICapSubscribe - { - - private readonly ILogger _logger; - private readonly IMessageService _messageService; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IMsgCenterCoreService _msgCenterCoreService; - public MessageSubscriberEventBus(ILogger logger, IMessageService messageService, IServiceScopeFactory serviceScopeFactory, IMsgCenterCoreService msgCenterCoreSerivce) - { - _logger = logger; - _messageService = messageService; - _serviceScopeFactory = serviceScopeFactory; - _msgCenterCoreService = msgCenterCoreSerivce; - } - //public MessageSubscriberEventBus(ILogger logger, IServiceScopeFactory serviceScopeFactory) - //{ - // _logger = logger; - // _serviceScopeFactory = serviceScopeFactory; - //} - -#if RELEASE - /// - /// 消息 - /// - /// - /// - - [CapSubscribe("msgcenter.services.msg.notice")] - public async Task SaveMsg(ProduceMsgModel dto) - { - try - { - var age = DateTime.Now - dto.CreatedAt; - - if (age > TimeSpan.FromMinutes(2)) - { - // 消息已过期,记录日志或直接忽略 - _logger.LogWarning("消息过期,已忽略: {MainId} {Id}, Age: {Age}", dto.MainId, dto.Id, age); - return; - } - await _messageService.SendMsg(dto); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } -#endif - - /// - /// 发送消息 - /// - /// - /// - [CapSubscribe("msgcenter.services.msgv2")] - public async Task ReceivedMsg(object msgObj) - { - try - { - MsgTempateEventDto msg = JsonConvert.DeserializeObject(msgObj.ToString()); - await _msgCenterCoreService.SendMsg(msg); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs deleted file mode 100644 index 9c17119..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/MsgTempateEventDto.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.EventBus -{ - public class MsgTempateEventDto - { - /// - /// 消息模板ID - /// - public string MsgTempateId { get; set; } - /// - /// 消息名称 - /// - public string? Title { get; set; } - /// - /// 属性值 - /// - //public JObject? Fields { get; set; } - public JToken? Fields { get; set; } - /// - /// 扩展信息 - /// - public object? Extend { get; set; } - /// - /// 用户ID - /// - public List UserIds { get; set; } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs b/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs deleted file mode 100644 index 31d611f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/EventBus/SendTypeMeta.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace WeiCloud.Core.EventBus -{ - public enum SendTypeMeta - { - [Description("App消息")] - AppMsg = 1, - [Description("PC消息")] - PcMsg = 2, - [Description("短信消息")] - SMSMsg = 3 - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs deleted file mode 100644 index cd1cd8e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Extension/ExceptionExtension.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Core.NlogTools; - -namespace WeiCloud.Core.Extension -{ - public static class ExceptionExtension - { - #region 获取最底层异常 - /// - /// 获取最底层异常 - /// - public static Exception GetDeepestException(this Exception ex) - { - var innerException = ex.InnerException; - var resultExcpetion = ex; - while (innerException != null) - { - resultExcpetion = innerException; - innerException = innerException.InnerException; - } - - return resultExcpetion; - } - #endregion - - - #region 异常文本日志 - public static void WriteErrorLog(this Exception ex, string message, string platHost = "") - { - LoggerHelper.Error(message, ex, platHost: platHost); - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs deleted file mode 100644 index 54fb68c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Extension/FriendlyException.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Extension -{ - public class FriendlyException : Exception - { - - public FriendlyException(string friendlyMessage) : base(friendlyMessage) - { - } - - public FriendlyException(string friendlyMessage, Exception innerException) : base(friendlyMessage, innerException) - { - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs deleted file mode 100644 index 061d608..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Extension/IQueryableExtensions.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Linq; -using System.Text; - -namespace WeiCloud.Core.Extension -{ - public static class IQueryableExtensions - { - public static IQueryable WhereIf(this IQueryable query, bool condition, Expression> predicate) - { - return condition - ? query.Where(predicate) - : query; - } - - - public static IQueryable TakePage(this IQueryable source, int pageSize, int pageIndex) => source.Skip((pageIndex - 1) * pageSize).Take(pageSize); - - - /// - /// 动态添加多个 OR 条件 - /// - /// 实体类型 - /// 查询对象 - /// 条件列表 - /// 包含动态 OR 条件的查询对象 - public static IQueryable WhereAny(this IQueryable query, IEnumerable>> conditions) - { - if (conditions == null || !conditions.Any()) - return query; - - // 动态构建 OR 条件 - Expression> combinedCondition = null; - - foreach (var condition in conditions) - { - if (combinedCondition == null) - { - combinedCondition = condition; // 第一个条件 - } - else - { - // 使用 Expression.OrElse 连接条件 - var newCondition = Expression.Lambda>( - Expression.OrElse( - combinedCondition.Body, - new ReplaceParameterVisitor(condition.Parameters[0], combinedCondition.Parameters[0]).Visit(condition.Body) - ), - combinedCondition.Parameters - ); - - combinedCondition = newCondition; - } - } - - return query.Where(combinedCondition); - } - - /// - /// 用于替换表达式参数的帮助类 - /// - private class ReplaceParameterVisitor : ExpressionVisitor - { - private readonly ParameterExpression _oldParameter; - private readonly ParameterExpression _newParameter; - - public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter) - { - _oldParameter = oldParameter; - _newParameter = newParameter; - } - - protected override Expression VisitParameter(ParameterExpression node) - { - if (node == _oldParameter) - return _newParameter; - return base.VisitParameter(node); - } - } - } - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs deleted file mode 100644 index e8256b9..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Extension/TryConvertExtension.cs +++ /dev/null @@ -1,198 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace WeiCloud.Core.Extension -{ - public static class TryConvertExtension - { - #region 类型转换 - /// - /// string转int - /// - /// 输入 - /// 转换失败默认 - /// - public static int TryInt(this object input, int defaultNum = 0) - { - if (input == null) - { - return defaultNum; - } - - return int.TryParse(input.ToString(), out var num) ? num : defaultNum; - } - /// - /// string转long - /// - /// 输入 - /// 转换失败默认 - /// - public static long TryLong(this object input, long defaultNum = 0) - { - if (input == null) - { - return defaultNum; - } - - return long.TryParse(input.ToString(), out var num) ? num : defaultNum; - } - /// - /// string转double - /// - /// 输入 - /// 转换失败默认值 - /// - public static double TryDouble(this object input, double defaultNum = 0) - { - if (input == null) - { - return defaultNum; - } - - return double.TryParse(input.ToString(), out var num) ? num : defaultNum; - } - /// - /// string转decimal - /// - /// 输入 - /// 转换失败默认值 - /// - public static decimal TryDecimal(this object? input, decimal defaultNum = 0) - { - if (input == null) - { - return defaultNum; - } - - return decimal.TryParse(input.ToString(), out decimal num) ? num : defaultNum; - } - /// - /// string转decimal - /// - /// 输入 - /// 转换失败默认值 - /// - public static float TryFloat(this object input, float defaultNum = 0) - { - if (input == null) - { - return defaultNum; - } - - return float.TryParse(input.ToString(), out var num) ? num : defaultNum; - } - /// - /// string转bool - /// - /// 输入 - /// - /// 转换失败默认值 - /// - /// - public static bool TryBool(this object input, bool defaultBool = false, string trueVal = "1", string falseVal = "0") - { - if (input == null) - { - return defaultBool; - } - - var str = input.ToString(); - if (bool.TryParse(str, out var outBool)) - { - return outBool; - } - - outBool = defaultBool; - if (trueVal == str) - { - return true; - } - - if (falseVal == str) - { - return false; - } - - return outBool; - } - /// - /// 值类型转string - /// - /// 输入 - /// 转换失败默认值 - /// - public static string TryString(this ValueType inputObj, string defaultStr = "") - { - var output = inputObj == null ? defaultStr : inputObj.ToString(); - return output; - } - /// - /// 字符串转时间 - /// - /// 输入 - /// 默认值 - /// - public static DateTime TryDateTime(this string inputStr, DateTime defaultValue = default) - { - if (inputStr.IsNullOrEmpty()) - { - return defaultValue; - } - - try - { - var result = DateTime.TryParse(inputStr, out var outPutDateTime); - if (result) - { - return outPutDateTime; - } - - return DateTime.FromOADate(double.Parse(inputStr)); - } - catch - { - return defaultValue; - } - } - /// - /// 字符串转时间 - /// - /// 输入 - /// - /// 默认值 - /// - public static DateTime TryDateTime(this string inputStr, string formater, DateTime defaultValue = default) - { - if (inputStr.IsNullOrEmpty()) - { - return defaultValue; - } - - return DateTime.TryParseExact(inputStr, formater, CultureInfo.InvariantCulture, DateTimeStyles.None, out var outPutDateTime) ? outPutDateTime : defaultValue; - } - /// - /// 字符串去空格 - /// - /// 输入 - /// - public static string TryTrim(this string inputStr) - { - var output = inputStr.IsNullOrEmpty() ? inputStr : inputStr.Trim(); - return output; - } - /// - /// 字符串转枚举 - /// - /// 输入 - /// - /// - /// - public static T TryEnum(this string str, T t = default) where T : struct - { - return Enum.TryParse(str, out var result) ? result : t; - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs deleted file mode 100644 index e284dc5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiIgnoreAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Filters -{ - /// - /// 忽略统一返回结果特性 - /// - public class ApiIgnoreAttribute : Attribute - { - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs deleted file mode 100644 index c762a06..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/ApiResultFilter.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Filters -{ - /// - /// 统一返回数据 - /// - public class ApiResultFilter : Attribute, IActionFilter - { - /// - /// 执行方法体之后 - /// 返回结果为JsonResult的请求进行Result包装 - /// - /// - public void OnActionExecuted(ActionExecutedContext context) - { - //特殊处理:对有ApiIgnoreAttribute标签的,不进行返回结果包装,原样输出 - var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; - if (controllerActionDescriptor != null) - { - var isDefined = controllerActionDescriptor.EndpointMetadata.Any(a => a.GetType().Equals(typeof(ApiIgnoreAttribute))); - if (isDefined) - { - return; - } - - } - // 返回结果为JsonResult的请求进行Result包装 - if (context.Result != null) - { - - if (context.Result is ObjectResult) - { - var result = context.Result as ObjectResult; - string str = JsonConvert.SerializeObject(result.Value); - if (!str.Contains("\"Code\":") && !str.Contains("\"Msg\":")) - { - context.Result = new JsonResult(new { code =200, msg = "操作成功", data = result.Value }); - } - - } - else if (context.Result is EmptyResult) - { - context.Result = new JsonResult(new { code = 200, msg = "操作成功", data = new { } }); - } - else if (context.Result is ContentResult) - { - var result = context.Result as ContentResult; - context.Result = new JsonResult(new { code = 200, msg = result.Content }); - } - - - } - - } - - /// - /// 执行方法体之前 - /// - /// - public void OnActionExecuting(ActionExecutingContext context) - { - //不做修改 - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs deleted file mode 100644 index f4973f3..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/AuthActionFilter.cs +++ /dev/null @@ -1,175 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using WeiCloud.Core.Common; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Utils; -using WeiCloud.Core.Services; -using WeiCloud.Core.Services.Permission; -using Castle.Core.Logging; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Microsoft.Extensions.DependencyInjection; -using System.IO; -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using NewLife.Reflection; -using Autofac; - -namespace WeiCloud.Core.Filters -{ - internal class AuthActionFilter - { - } - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] - public class ActionAuthAttribute : System.Attribute - { - /// - /// 权限Id - /// - public long PermissionId { get; set; } - public ActionAuthAttribute(long permissionId) - { - PermissionId = permissionId; - } - public ActionAuthAttribute() - { - - } - } - public class ActionFilter : IActionFilter//ActionFilterAttribute - { - private readonly CurrentContext _currentContext; - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - public ActionFilter(IServiceScopeFactory serviceScopeFactory, ILogger logger, CurrentContext currentContext) - { - _serviceScopeFactory = serviceScopeFactory; - _logger = logger; - _currentContext = currentContext; - } - - public void OnActionExecuted(ActionExecutedContext context) { } - - public void OnActionExecuting(ActionExecutingContext context) - { - try - { - var currentUser = _currentContext.GetContext(); - if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) - { - //var lifetimeScope = context.HttpContext.RequestServices.GetService(); - //var funPermissionCoreService = lifetimeScope.Resolve(); - - using var scope = _serviceScopeFactory.CreateScope(); - var funPermissionCoreService = scope.ServiceProvider.GetRequiredService(); - - #region 添加接口权限验证 - long projectId = 0; - //var projectIdStr = string.Empty; - context.HttpContext.Request.Headers.TryGetValue("projectid", out var projectIdHeader); - if (projectIdHeader.Any()) - { - if (long.TryParse(projectIdHeader.FirstOrDefault(), out long parsedProjectId)) - { - if (currentUser.ProjectIds.Contains(parsedProjectId)) - { - projectId = parsedProjectId; - } - } - } - IDictionary actionArguments = context.ActionArguments; - if (actionArguments != null) - { - string method = context.HttpContext.Request.Method.ToUpper(); - if (method == "GET") - { - foreach (KeyValuePair item in actionArguments) - { - var key = item.Key; //参数名 - var val = item.Value; //参数值 - if (key.ToLower() == "projectid") - { - var id = long.Parse(item.Value.ToString()); - if (currentUser.ProjectIds.Contains(id)) - { - projectId = id; - break; - } - } - } - } - else - { - var it = actionArguments.Values.First().ToDictionary(); - foreach (var i in it) - { - if (i.Key.ToLower() == "projectid") - { - var id = long.Parse(i.Value.ToString()); - projectId = id; - break; - } - } - } - } - //if (projectId > 0) - //{ - if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) - { - string actionName = controllerActionDescriptor.ActionName; - string controllerName = controllerActionDescriptor.ControllerName; - string path = controllerName + "/" + actionName; - long menuId = 0;//菜单id - var pars = context.ActionArguments.ToList(); - //if(pars!=null&&pars.Count>0) - //{ - // var menu=pars.FirstOrDefault(t => t.Key == "menuId"); - // menuId= menu.Value==null?0:long.Parse(menu.Value.ToString()); - //} - var res = funPermissionCoreService.GetCurrentUserFun(projectId, path).Result; - if (res == 0) - { - var result = new JsonResult(new ApiResult { Code = RequestBackStatuEnum.diy.Value, Data = string.Empty, Msg = "没有分配权限" }); - result.ContentType = "application/json"; - result.StatusCode = StatusCodes.Status200OK; - context.Result = result; - return; - } - } - //} - #endregion - ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; - bool isActionAuthDescriptor = ad.MethodInfo.IsDefined(typeof(ActionAuthAttribute), false); - if (isActionAuthDescriptor) - { - var authAttr = ad.MethodInfo.GetCustomAttributes(typeof(ActionAuthAttribute), false).FirstOrDefault() as ActionAuthAttribute; - long permissionId = authAttr.PermissionId; - - var currentUserFunPermissions = funPermissionCoreService.GetCurrentUserFunPermissions().Result; - - if (currentUserFunPermissions == null || !currentUserFunPermissions.Any(t => t == permissionId)) - { - var result = new JsonResult(new ApiResult { Code = RequestBackStatuEnum.diy.Value, Data = string.Empty, Msg = "没有分配权限" }); - result.ContentType = "application/json"; - result.StatusCode = StatusCodes.Status200OK; - context.Result = result; - return; - } - } - // - - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs deleted file mode 100644 index c368ca3..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/FunctionAttribute.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Filters -{ - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] - public class FunctionAttribute : System.Attribute - { - public string ControllerDesc { get; set; } - public string MathodDesc { get; set; } - public FunctionAttribute( string controllerDesc = "", string mathodDesc = "") - { - controllerDesc = ControllerDesc; - mathodDesc = MathodDesc; - } - public FunctionAttribute() - { - - } - } - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs deleted file mode 100644 index 3dc6964..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/GlobalExceptionsFilter.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Extension; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Common -{ - public class GlobalExceptionsFilter : IExceptionFilter - { - - private readonly IHostingEnvironment _env; - private readonly ILogger _loggerHelper; - - public GlobalExceptionsFilter(IHostingEnvironment env, ILogger loggerHelper) - { - _env = env; - _loggerHelper = loggerHelper; - - } - - - - public void OnException(ExceptionContext context) - { - if (context.Exception is FriendlyException friendlyException) - { - context.Result = new OkObjectResult(ApiResult.IsFail(friendlyException.Message)); - return; - } - - string strController = context.RouteData.Values["controller"].ToString(); - string strAction = context.RouteData.Values["action"].ToString(); - //3.记录异常日志 - string errMsg = String.Format("千牛卫网站错误:控制器:{0};功能方法:{1};异常信息:{2};堆栈:{3};内部异常信息:{4};源:{5};", - strController, - strAction, - context.Exception.Message, - context.Exception.StackTrace, - context.Exception.GetDeepestException(), - context.Exception.Source - ); - _loggerHelper.LogError($"全局捕获异常: {errMsg}"); - - ContentResult result = new ContentResult - { - StatusCode = 500, - ContentType = "application/json; charset=utf-8" - }; - - var result1 = new ApiResult { }; - result1.Msg = "系统错误"; - result1.Code = 500; - result.Content = JsonConvert.SerializeObject(result1); - context.Result = result; - context.ExceptionHandled = true; - context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - } - } - - public static class ExceptionExtension - { - #region 获取最底层异常 - /// - /// 获取最底层异常 - /// - public static Exception GetDeepestException(this Exception ex) - { - var innerException = ex.InnerException; - var resultExcpetion = ex; - while (innerException != null) - { - resultExcpetion = innerException; - innerException = innerException.InnerException; - } - - return resultExcpetion; - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs deleted file mode 100644 index 21535fc..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/SkipMyGlobalActionFilter.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Filters; -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Filters -{ - /// - /// 这是一个空过滤器 用于过滤全局Filter的执行 - /// - public class SkipMyGlobalActionFilter : ActionFilterAttribute - { - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs deleted file mode 100644 index 6ede1a2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/TenantAccessCheckFilter.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using MySqlX.XDevAPI.Common; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.Tenant; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Filters -{ - public interface ITenantAccessContextProvider - { - TenantAccessDto Current { get; set; } - } - public class TenantAccessContextProvider : ITenantAccessContextProvider - { - private static readonly AsyncLocal _current = new AsyncLocal(); - - public TenantAccessDto Current - { - get - { - if (_current.Value == null) - { - _current.Value = new TenantAccessDto(); - } - return _current.Value; - } - set - { - _current.Value = value; - } - } - } - - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] - public class TenantAccessCheckFilter : Attribute, IAsyncActionFilter - { - private readonly ITenantAccessContextProvider _contextProvider; - public TenantAccessCheckFilter(ITenantAccessContextProvider contextProvider) - { - _contextProvider = contextProvider ?? throw new ArgumentNullException(nameof(contextProvider)); - } - public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - var httpContext = context.HttpContext; - var headers = httpContext.Request.Headers; - - if (!headers.TryGetValue("AccessKey", out var accessKey) || - !headers.TryGetValue("AccessSign", out var accessSign)) - { - context.Result = new UnauthorizedObjectResult("Missing AccessKey or AccessSign"); - return; - } - // 假设有一个服务可以做签名验证 - var _userCenterContext = httpContext.RequestServices.GetRequiredService(); - var tenant = _userCenterContext.MsgTenant.Where(t => t.AccessKey == accessKey.ToString() && t.IsDeleted == false).AsNoTracking().FirstOrDefault(); - if (tenant == null) - { - context.Result = new UnauthorizedObjectResult("无效的accessKey"); - return; - } - //验证签名 - var sign = MD5Helper.getMd5Hash($"{tenant.AccessKey}{tenant.SecretKey}{DateTime.Now.ToString("yyyyMMddHHmm")}"); - if (!accessSign.Equals(sign)) - { - context.Result = new UnauthorizedObjectResult("无效的签名"); - return; - } - // 设置自定义上下文信息,比如用户信息 - _contextProvider.Current = new TenantAccessDto - { - Id = tenant.Id, - Name = tenant.Name, - AccessKey = tenant.AccessKey - }; - await next(); // 验签通过,继续执行 Action - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs deleted file mode 100644 index 8c89c9f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Filters/ValidateFieldsMiddleware.cs +++ /dev/null @@ -1,89 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System; -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Filters -{ - public class ValidateFieldsMiddleware - { - private readonly RequestDelegate _next; - - public ValidateFieldsMiddleware(RequestDelegate next) - { - _next = next; - } - private bool IsJsonRequest(HttpContext context) - { - // 判断是否是 Content-Type 为 application/json 的请求 - return context.Request.ContentType != null && - context.Request.ContentType.Contains("application/json", StringComparison.OrdinalIgnoreCase); - } - public async Task Invoke(HttpContext context) - { - if ((context.Request.Method == HttpMethods.Post || context.Request.Method == HttpMethods.Put) && IsJsonRequest(context)) - { - context.Request.EnableBuffering(); - var body = await new StreamReader(context.Request.Body).ReadToEndAsync(); - if (!string.IsNullOrEmpty(body)) - { - context.Request.Body.Position = 0; - - //var jsonObject = JsonConvert.DeserializeObject(body); - var jsonObject = System.Text.Json.JsonSerializer.Deserialize(body); - if (jsonObject.ValueKind.ToString() != "Array") - { - - var properties = jsonObject.EnumerateObject(); - - // 获取当前的路由信息 - var endpoint = context.GetEndpoint(); - var controllerAction = endpoint?.Metadata.GetMetadata(); - - if (controllerAction != null) - { - // 获取方法参数类型 - var parameterInfo = controllerAction.Parameters.FirstOrDefault(); - if (parameterInfo != null) - { - var entityType = parameterInfo.ParameterType; - var entityProperties = entityType.GetProperties().Select(p => p.Name.ToLower()).ToList(); - - // 检查传入字段 - foreach (var property in properties) - { - if (property.Name.ToLower() == "projectid") - { - try - { - var projectIdStr = property.Value.ToString(); - if (projectIdStr.Length > 20) - { - context.Response.StatusCode = StatusCodes.Status400BadRequest; - await context.Response.WriteAsync($"Invalid field: {property.Name}"); - return; - } - } - catch (System.Exception) - { - } - } - if (!entityProperties.Contains(property.Name.ToLower())) - { - context.Response.StatusCode = StatusCodes.Status400BadRequest; - await context.Response.WriteAsync($"Invalid field: {property.Name}"); - return; - } - } - } - } - } - } - } - - await _next(context); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs deleted file mode 100644 index 2911fbd..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/HostService/LogHostedService.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.Extensions.Hosting; -using NLog; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace WeiCloud.Core.HostService -{ - public class LogHostedServiceHost : IHostedService, IAsyncDisposable - { - private Timer RunTimer { get; set; } - public ValueTask DisposeAsync() - { - return this.RunTimer.DisposeAsync(); - } - - public Task StartAsync(CancellationToken cancellationToken) - { - LogManager.Configuration.Install(new NLog.Config.InstallationContext());//启动后执行一次 - this.RunTimer = new Timer(LogInstall, null, DateTime.Now.AddDays(1).Date - DateTime.Now, TimeSpan.FromDays(1)); - return Task.CompletedTask; - } - public void LogInstall(object state) - { - LogManager.Configuration.Install(new NLog.Config.InstallationContext());//每天0点执行一次 - } - - public Task StopAsync(CancellationToken cancellationToken) - { - this.RunTimer?.Change(Timeout.Infinite, 0); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs deleted file mode 100644 index 84508aa..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLog.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using MonitorAopLog.Util; -using MonitorAopLog.Util.Model; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.HostService -{ - public class MonitorLogFlush : MonitorLogManager - { - private readonly WeiCloudDBUserCenterContext _userCenterContext; - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - private readonly string InstanceName; - public MonitorLogFlush(ILogger logger, IConfiguration configuration, WeiCloudDBUserCenterContext userCenterContext) : base(logger) - { - _configuration = configuration; - _logger = logger; - _userCenterContext = userCenterContext; - InstanceName = _configuration["MonitorLog:Instance"]; - } - - protected override async Task FlushAsync(List list, CancellationToken token) - { - try - { - if (!string.IsNullOrEmpty(InstanceName)) - { - foreach (var item in list) - { - _userCenterContext.MonitorLog.Add(new Entity.Context.UserCenter.MonitorLog - { - InstanceName = InstanceName, - MethodName = item.MethodName, - Arguments = item.Arguments, - ElapsedMilliseconds = item.ElapsedMilliseconds, - StartTime = item.StartTime, - EndTime = item.EndTime, - CreateTime = DateTime.Now - }); - } - await _userCenterContext.SaveChangesAsync(); - } - } - catch (Exception ex) - { - _logger.LogError(ex.Message, ex); - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs b/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs deleted file mode 100644 index ff866e4..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/HostService/MonitorLogTaskHost.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace WeiCloud.Core.HostService -{ - public class MonitorLogTaskHost : IHostedService - { - private readonly MonitorLogFlush _monitor; - public MonitorLogTaskHost(MonitorLogFlush monitor) - { - _monitor = monitor; - } - public async Task StartAsync(CancellationToken cancellationToken) - { - //using var loggerFactory = LoggerFactory.Create(builder => - //{ - // builder.SetMinimumLevel(LogLevel.Warning); - //}); - - //var logger = loggerFactory.CreateLogger(); - - //var monitorLog = new MonitorLog(logger); - //await monitorLog.Start(); - await _monitor.Start(); - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs b/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs deleted file mode 100644 index 8f71bc6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/LocalCache/LocalData.cs +++ /dev/null @@ -1,402 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.FamilyDecoration; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.DataCollection; -using WeiCloud.Utils; -using WeiCloud.Utils.RedisUtil; - -namespace WeiCloud.Core -{ - public class LocalData - { - private readonly int realDataExpireTimeMinutes = 10; - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceProvider; - private readonly IDictionaryService _dictionaryService; - public LocalData(ILogger logger, IServiceScopeFactory serviceProvider, IDictionaryService dictionaryService) - { - _logger = logger; - _serviceProvider = serviceProvider; - _dictionaryService = dictionaryService; - } - //private ConcurrentDictionary> realDataDic = new ConcurrentDictionary>(); - private ConcurrentDictionary>> realDataDic = new ConcurrentDictionary>> { }; - private async Task> InitTbRealData(long projectId, List realIds = null) - { - try - { - using var scope = _serviceProvider.CreateScope(); - var userDBContext = scope.ServiceProvider.GetRequiredService(); - - var projectInfo = userDBContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); - if (projectInfo == null || string.IsNullOrWhiteSpace(projectInfo.Dbstr)) - { - return new List { }; - } - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) - .Options; - using var contextDB = new WeiCloudDBContext(contextOptions); - var realDataQuery = contextDB.TbRealData.AsQueryable(); - if (realIds != null && realIds.Count() > 0) - { - realDataQuery = realDataQuery.Where(t => realIds.Contains(t.Id)); - } - realDataQuery = realDataQuery.Where(t => t.Projectid == projectId); - var realDatas = await realDataQuery.AsNoTracking().ToListAsync(); - if (realDatas != null && realDatas.Count() > 0) - { - var dataCaches = realDatas.Select(t => new LocalDataCache - { - CacheTime = DateTime.Now.AddMinutes(realDataExpireTimeMinutes + (t.Id % 5)), - Data = t - }).ToList(); - realDataDic.AddOrUpdate(projectId, dataCaches, (key, values) => - { - if (values == null) - { - values = new List> { }; - } - foreach (var realData in dataCaches) - { - //var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id && t.CacheTime > DateTime.Now); - var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id); - if (value == null) - { - values.Add(realData); - } - else if (value != null && value.CacheTime > DateTime.Now) - {//不为空,但已经失效 - values.Remove(value); - values.Add(realData); - } - } - return values; - }); - } - - return realDatas; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("InitTbRealData", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return new List { }; - } - - //public async Task> GetTbRealDatas(long projectId, List realdIds = null) - //{ - // List items; - // List> dataCaches = null; - // realDataDic.TryGetValue(projectId, out dataCaches); - // if (dataCaches != null) - // { - // if (realdIds != null && realdIds.Count() > 0) - // { - // items = dataCaches.Where(t => realdIds.Contains(t.Data.Id) && t.CacheTime >= DateTime.Now).Select(t => t.Data).ToList(); - // } - // else - // { - // items = dataCaches.Where(t => t.CacheTime >= DateTime.Now).Select(t => t.Data).ToList(); - // } - // if ((realdIds != null && items.Count() == realdIds.Count()) || (items.Count() == dataCaches.Count() && dataCaches.Count() > 0)) - // { - // return items; - // } - // } - // return await InitTbRealData(projectId, realdIds); - //} - public async Task> GetTbRealDatas_bak(long projectId, List realdIds = null) - { - List realvaluelist = new List { }; - if (realdIds != null && realdIds.Count() > 0) - { - realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), realdIds.Select(t => t.ToString()).ToArray(), 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); - } - else - { - var keyValueDic = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Values.ToList(); - var pageIndex = 0; - var pageSize = 500; - - while (true) - { - var _realDatas = keyValueDic.Skip(pageIndex * pageSize).Take(pageSize).ToList(); - if (_realDatas != null && _realDatas.Count() > 0) - { - realvaluelist.AddRange(_realDatas); - } - else - { - break; - } - pageIndex++; - } - - //var pageIndex = 0; - //var pageSize = 500; - - //while (true) - //{ - // var _realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Select(t => t.Value).Where(t => t != null).Skip(pageIndex * pageSize).Take(pageSize).ToList(); - // if (_realDatas != null && _realDatas.Count() > 0) - // { - // realvaluelist.AddRange(_realDatas); - // } - // else - // { - // break; - // } - // pageIndex++; - //} - //realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectId.ToString(), 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); - } - return realvaluelist ?? new List { }; - } - public async Task> GetTbRealDatas(long projectId, List realdIds = null) - { - using var serviceScope = _serviceProvider.CreateScope(); - var userCenterContext = serviceScope.ServiceProvider.GetRequiredService(); - var projectInfo = await userCenterContext.ProjectInfo.Where(t => t.Id == projectId).Select(t => new - { - t.Id, - t.Dbstr - }).FirstOrDefaultAsync(); - if (projectInfo == null || string.IsNullOrEmpty(projectInfo.Dbstr)) - { - return null; - } - try - { - var contextOptions = new DbContextOptionsBuilder() -.UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) -.Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - List realvaluelist; - if (realdIds != null && realdIds.Count() > 0) - { - //var data=await __contextDB.TbRealData.ToListAsync(); - realvaluelist = await __contextDB.TbRealData.Where(t => realdIds.Contains(t.Id) && t.Projectid == projectId).Select(t => new TbRealData - { - Id = t.Id, - Projectid = t.Projectid, - Descname = t.Descname, - Tagname = t.Tagname, - Aitype = t.Aitype, - Unit = t.Unit, - Equid = t.Equid, - Standarparamid = t.Standarparamid, - Virtualformula = t.Virtualformula, - Virtualformulaparam = t.Virtualformulaparam, - JsonContent = t.JsonContent, - PointType = t.PointType - }).ToListAsync(); - } - else - { - realvaluelist = await __contextDB.TbRealData.Where(t => t.Projectid == projectId).Select(t => new TbRealData - { - Id = t.Id, - Projectid = t.Projectid, - Descname = t.Descname, - Tagname = t.Tagname, - Aitype = t.Aitype, - Unit = t.Unit, - Equid = t.Equid, - Standarparamid = t.Standarparamid, - Virtualformula = t.Virtualformula, - Virtualformulaparam = t.Virtualformulaparam, - JsonContent = t.JsonContent, - PointType = t.PointType - }).ToListAsync(); - } - return realvaluelist ?? new List { }; - } - catch (Exception ex) - { - - throw; - } - - - } - public async Task CheckProIdIsRefresh(long projectId, List proIds, List proValueIds) - { - return true; - } - public async Task UpdateTbRealData() - { - using var scope = _serviceProvider.CreateScope(); - var configuration = scope.ServiceProvider.GetRequiredService(); - var prefix = configuration.GetConnectionString("RedisPrefix"); - prefix = prefix.Substring(0, prefix.Length - 1); - await UpdateTbRealData(0, prefix: prefix); - } - /// - /// 更新本地实时配置 - /// - /// - /// - /// - /// - private async Task UpdateTbRealData(long projectId, string prefix = "", List realIds = null) - { - try - { - using var scope = _serviceProvider.CreateScope(); - var userDBContext = scope.ServiceProvider.GetRequiredService(); - var projectQuery = userDBContext.ProjectInfo.AsNoTracking(); - if (projectId > 0) - { - projectQuery = projectQuery.Where(t => t.Id == projectId); - } - else if (!string.IsNullOrEmpty(prefix)) - { - projectQuery = projectQuery.Where(t => t.Engabb == prefix); - } - else - { - return; - } - var projectInfo = projectQuery.AsNoTracking().FirstOrDefault(); - if (projectInfo == null || string.IsNullOrWhiteSpace(projectInfo.Dbstr)) - { - return; - } - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) - .Options; - using var contextDB = new WeiCloudDBContext(contextOptions); - var realDataQuery = contextDB.TbRealData.AsQueryable(); - if (realIds != null && realIds.Count() > 0) - { - realDataQuery = realDataQuery.Where(t => realIds.Contains(t.Id)); - } - var realDatas = await realDataQuery.Where(t => t.Projectid == projectInfo.Id).AsNoTracking().ToListAsync(); - var dataCaches = realDatas.Select(t => new LocalDataCache - { - CacheTime = DateTime.Now.AddMinutes(realDataExpireTimeMinutes + (t.Id % 5)), - Data = t - }).ToList(); - realDataDic.AddOrUpdate(projectInfo.Id, dataCaches, (key, values) => - { - if (realDatas == null || realDatas.Count() == 0) - { - return new List> { }; - } - if (values == null) - { - values = new List> { }; - } - foreach (var realData in dataCaches) - { - //var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id && t.CacheTime >= DateTime.Now); - var value = values.FirstOrDefault(t => t.Data.Id == realData.Data.Id); - if (value != null && value.CacheTime > DateTime.Now) - {//不为空,但已经失效 - values.Remove(value); - values.Add(realData); - } - else if (value == null) - { - values.Add(realData); - } - } - //移除失效 - values.RemoveAll(t => t.CacheTime > DateTime.Now); - //values.RemoveAll(t => !realDatas.Select(t => t.Id).Contains(t.Data.Id) || t.CacheTime < DateTime.Now); - //values.RemoveAll(t => !realDatas.Select(t => t.Id).Contains(t.Data.Id)); - return values; - }); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("UpdateTbRealData", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - #region 组态相关 - private ConcurrentDictionary>>> ConfigurationPositionCache = new ConcurrentDictionary>>>(); - /// - /// 缓存组态数据 - /// - /// - /// - /// - public async Task>> GetConfigurationPositionCache(string key, Func>> func) - { - try - { - await ClearConfigurationPositionCache(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetConfigurationPositionCache", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - try - { - LocalDataCache>> result = null; - ConfigurationPositionCache.TryGetValue(key, out result); - if (result != null && result.CacheTime > DateTime.Now.AddSeconds(-2)) - {//缓存2秒内数据 - Console.WriteLine($"{key}缓存数据"); - return result.Data; - } - var data = func(key); - - ConfigurationPositionCache.AddOrUpdate(key, (key) => - { - return new LocalDataCache>> - { - CacheTime = DateTime.Now.AddSeconds(2), - Data = data - }; - }, (key, value) => - { - value.CacheTime = DateTime.Now.AddSeconds(2); - value.Data = data; - return value; - }); - Console.WriteLine($"{key}新数据"); - return data; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetConfigurationPositionCache", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return new ApiResult> { Code = RequestBackStatuEnum.fail.Value }; - } - private async Task ClearConfigurationPositionCache() - { - var keys = ConfigurationPositionCache.Keys; - foreach (var key in keys) - { - LocalDataCache>> value; - if (ConfigurationPositionCache.TryGetValue(key, out value) && value != null && value.CacheTime < DateTime.Now.AddSeconds(-10)) - { - ConfigurationPositionCache.TryRemove(key, out value); - } - } - } - #endregion - - public class LocalDataCache - { - public DateTime CacheTime { get; set; } - public T Data { get; set; } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs b/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs deleted file mode 100644 index b46003e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/ML/RegressionUtil.cs +++ /dev/null @@ -1,161 +0,0 @@ -using Microsoft.ML; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.LogicModels.ML; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core.ML -{ - public class RegressionUtil - { - private MLContext mlContext = new MLContext(seed: 0); - private IDataView dataView = null; - private ITransformer transModel = null; - public void Train(List trainModels) where T : class - { - var propertys = typeof(T).GetProperties(); - - var labelName = propertys.LastOrDefault().Name; - dataView = mlContext.Data.LoadFromEnumerable(trainModels); - //var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: nameof(labelName)); - var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: labelName); - List features = new List { }; - foreach (var property in propertys) - { - string name = property.Name; - - string type = (property.PropertyType).FullName; - - if ("System.Decimal" == type || "System.Double" == type || "System.Int16" == type - || "System.Int64" == type || "System.Int32" == type || "System.Single" == type) - { - //features.Add(nameof(name)); - features.Add(name); - //pipeline.Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(name))); - pipeline.Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: name)); - } - else - { - features.Add(name + "Encoded"); ; - //pipeline.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: name + "Encoded", inputColumnName: nameof(name))); - pipeline.Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: name + "Encoded", inputColumnName: name)); - } - } - pipeline.Append(mlContext.Transforms.Concatenate("Features", features.ToArray())); - pipeline.Append(mlContext.Regression.Trainers.FastTree()); - transModel = pipeline.Fit(dataView); - } - public void TrainBinary(List trainModels) - { - dataView = mlContext.Data.LoadFromEnumerable(trainModels); - - var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: nameof(BinaryTrainModel.PhyValue)) - .Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "efectphytypeEncoded", inputColumnName: nameof(BinaryTrainModel.EfectPhyType))) - .Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "efectphytype1Encoded", inputColumnName: nameof(BinaryTrainModel.EfectPhyType1))) - .Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(BinaryTrainModel.EfectPhyValue))) - .Append(mlContext.Transforms.NormalizeMeanVariance(outputColumnName: nameof(BinaryTrainModel.EfectPhyValue1))) - - .Append(mlContext.Transforms.Concatenate("Features", "efectphytypeEncoded", "efectphytype1Encoded", nameof(BinaryTrainModel.EfectPhyValue), nameof(BinaryTrainModel.EfectPhyValue1))) - .Append(mlContext.Regression.Trainers.FastTree()); - - transModel = pipeline.Fit(dataView); - } - public void Evaluate(List evaluateModels) where T : class - { - var _dataView = mlContext.Data.LoadFromEnumerable(evaluateModels); - var predictions = transModel.Transform(_dataView); - mlContext.Regression.Evaluate(predictions, "Label", "Score"); - } - public void EvaluateBinary(List evaluateModels) - { - var _dataView = mlContext.Data.LoadFromEnumerable(evaluateModels); - var predictions = transModel.Transform(_dataView); - mlContext.Regression.Evaluate(predictions, "Label", "Score"); - } - public ParamPrediction Prediction(TSrc input) where TSrc : class - { - var predictionFunction = mlContext.Model.CreatePredictionEngine(transModel); - var prediction = predictionFunction.Predict(input); - return prediction; - } - public void LoadTranModel(string url) - { - DataViewSchema modelSchema; - using (HttpClient client = new HttpClient()) - { - Stream modelFile = client.GetStreamAsync(url).Result; - transModel = mlContext.Model.Load(modelFile, out modelSchema); - } - } - public FileInfo GetModelFile() - { - string fileName = Guid.NewGuid().ToString("N") + ".zip"; - string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); - FileInfo file = null; - try - { - //mlContext.Model.Save(transModel, dataView.Schema, path); - mlContext.Model.Save(transModel, dataView.Schema, path); - file = new FileInfo(path); - } - catch (Exception ex) - { - } - finally - { - if (File.Exists(path)) - File.Delete(path); - } - return file; - } - public Stream GetModelFileStream() - { - MemoryStream memoryStream = new MemoryStream(); - try - { - mlContext.Model.Save(transModel, dataView.Schema, memoryStream); - memoryStream.Flush(); - memoryStream.Position = 0; - } - catch (Exception ex) - { - } - finally - { - } - return memoryStream; - } - public string SaveModel() - { - if (transModel == null || dataView == null) - { - return "error"; - } - string fileName = Guid.NewGuid().ToString("N") + ".zip"; - string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); - try - { - mlContext.Model.Save(transModel, dataView.Schema, path); - var file = new FileInfo(path); - var t = FileHelper.FileUpload(file); - Task.WaitAny(t); - } - catch (Exception ex) - { - throw ex; - } - finally - { - //if (File.Exists(path)) - // File.Delete(path); - } - return fileName; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs b/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs deleted file mode 100644 index 5b25290..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/ML/TrainModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.ML.Data; -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices.ComTypes; -using System.Text; - -namespace WeiCloud.Core.ML -{ - public class TrainModel - { - public Dictionary ParamDic { get; set; } - } - public class ParamPrediction - { - [ColumnName("Score")] - public float phyvalue { get; set; } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs deleted file mode 100644 index 8263a2f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Middleware/ImgResponseMiddleware.cs +++ /dev/null @@ -1,265 +0,0 @@ -using Castle.Core.Logging; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using NPOI.OpenXmlFormats; -using Org.BouncyCastle.Asn1.Ocsp; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Middleware -{ - public static class MiddlewareExtensions - { - public static IApplicationBuilder UseImgResponse( - this IApplicationBuilder builder) - { - return builder.UseMiddleware(); - } - } - public class ImgResponseMiddleware - { - private readonly RequestDelegate _next; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly List _outerNets; - private readonly List _internalNets; - public ImgResponseMiddleware(RequestDelegate next, IConfiguration config, ILogger logger) - { - _next = next; - _configuration = config; - _logger = logger; - _outerNets = _configuration["ImgConvertConfig:OuterNet"].Split(",").ToList(); - _internalNets = _configuration["ImgConvertConfig:InternalNet"].Split(",").ToList(); - } - private bool IsInternalNet(string host) - { - var result = false; - try - { - /* var addr = host.Split(".")[0]; - - if (addr == "10" || addr == "172" || addr == "192") - { - result = true; - }*/ - if (host.Contains(_configuration["ImgConvertConfig:OuterNet"])) - { - return false; - } - return true; - } - catch (Exception) - { - } - return result; - } - private Tuple GetFileHost(string host) - { - var result = false; - try - { - /* var addr = host.Split(".")[0]; - - if (addr == "10" || addr == "172" || addr == "192") - { - result = true; - }*/ - foreach (var _outerNet in _outerNets) - { - if (host.Contains(_outerNet)) - { - return new Tuple(false, _outerNet); - } - } - //if (host.Contains(_configuration["ImgConvertConfig:OuterNet"])) - //{ - // return false; - //} - var internalNet = _internalNets.First(); - foreach (var _internalNet in _internalNets) - { - if (host.Contains(_internalNet)) - { - internalNet = _internalNet; - } - } - return new Tuple(true, internalNet); - } - catch (Exception) - { - } - return new Tuple(result, string.Empty); - } - public async Task InvokeAsync(HttpContext context) - { - try - { - var method = context.Request.Method; - var isJsonRequest = false; - if (context.Request.Headers["accept"].Count > 0) - { - isJsonRequest = context.Request.Headers["accept"][0].Contains("application/json"); - } - - var scheme = "http"; - var referer = context.Request.Headers["Referer"].ToString(); - if (referer.StartsWith("https")) - { - scheme = "https"; - } - Console.WriteLine($"Referer:{referer}"); - Console.WriteLine($"Scheme:{scheme}"); - var isInternalNetInfo = GetFileHost(referer); - var isInternalNet = isInternalNetInfo.Item1; - var fileHost = isInternalNetInfo.Item2; - //if ((method.Equals("POST") || method.Equals("GET")) && !context.Request.Host.Value.StartsWith(_configuration["FileUpload:hostname"]) && isJsonRequest) - if ((method.Equals("POST") || method.Equals("GET")) && isJsonRequest) - { - var orgResponseBody = context.Response.Body; - - //替换response流 - using var newResponse = new MemoryStream(); - context.Response.Body = newResponse; - await _next.Invoke(context); - //await _next(context); - using var reader = new StreamReader(newResponse); - - newResponse.Seek(0, SeekOrigin.Begin); - - var strBody = await reader.ReadToEndAsync(); - - newResponse.Seek(0, SeekOrigin.Begin); - - if (!string.IsNullOrWhiteSpace(strBody) && (strBody.Contains("/imageserve") || strBody.Contains("live?port=1935&app="))) - { - var newStrBody = strBody; - //var newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + context.Request.HttpContext.Request.Host.Value).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + context.Request.HttpContext.Request.Host.Value); - - //if (isInternalNet) - //{//context.Request.Headers["Referer"].ToString() - // //newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:InternalNet"]).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:InternalNet"]); - - // newStrBody = strBody.Replace("http://" + _configuration["ImgConvertConfig:OuterNet"] + "/", "http://" + _configuration["ImgConvertConfig:InternalNet"] + "/").Replace("https://" + _configuration["ImgConvertConfig:OuterNet"] + "/", "https://" + _configuration["ImgConvertConfig:InternalNet"] + "/"); - //} - //else - //{ - // //newStrBody = strBody.Replace("http://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:OuterNet"]).Replace("https://" + _configuration["FileUpload:hostname"], context.Request.Scheme + "://" + _configuration["ImgConvertConfig:OuterNet"]); - // newStrBody = strBody.Replace("http://" + _configuration["ImgConvertConfig:InternalNet"]+"/", "http://" + _configuration["ImgConvertConfig:OuterNet"] + "/").Replace("https://" + _configuration["ImgConvertConfig:InternalNet"] + "/", "https://" + _configuration["ImgConvertConfig:OuterNet"] + "/"); - - //} - foreach (var _outerNet in _outerNets) - { - strBody = strBody.Replace("http://" + _outerNet + "/", scheme + "://" + fileHost + "/").Replace("https://" + _outerNet + "/", scheme + "://" + fileHost + "/"); - } - foreach (var _internalNet in _internalNets) - { - strBody = strBody.Replace("http://" + _internalNet + "/", scheme + "://" + fileHost + "/").Replace("https://" + _internalNet + "/", scheme + "://" + fileHost + "/"); - } - newStrBody = strBody; - Console.WriteLine(_configuration["FileUpload:hostname"]); - Console.WriteLine(_configuration["ImgConvertConfig:InternalNet"]); - Console.WriteLine(_configuration["ImgConvertConfig:OuterNet"]); - - - //显示修改后的数据 - //using var writer = new StreamWriter(newResponse); - - //await writer.WriteAsync(newStrBody); - //await writer.FlushAsync(); - - //newResponse.Seek(0, SeekOrigin.Begin); - - //context.Response.ContentLength = newResponse.Length; - //await newResponse.CopyToAsync(orgResponseBody); - - //await newResponse.CopyToAsync(context.Response.Body); - var buffer = Encoding.UTF8.GetBytes(newStrBody); - context.Response.Body = orgResponseBody; - context.Response.ContentLength = buffer.Length; - await context.Response.WriteAsync(newStrBody, Encoding.UTF8); - } - else - { - //context.Response.Body = orgResponseBody; - //await context.Response.WriteAsync(strBody, Encoding.UTF8); - await context.Response.Body.CopyToAsync(orgResponseBody); - } - } - else - { - await _next(context); - } - } - catch (System.Exception ex) - { - _logger.LogError($" http中间件发生错误: " + ex.ToString()); - } - context.Response.OnCompleted(() => - { - return Task.CompletedTask; - }); - } - - //public async Task InvokeAsync(HttpContext context) - //{ - // var response = context.Response.Body; - // try - // { - // if (_configuration["FileUpload:hostname"] != context.Request.HttpContext.Request.Host.Value) - // { - // //替换response流 - // using var newResponse = new MemoryStream(); - // context.Response.Body = newResponse; - - // await _next(context); - - // using var reader = new StreamReader(newResponse); - // newResponse.Position = 0; - // var strBody = await reader.ReadToEndAsync(); - - // if (!string.IsNullOrWhiteSpace(strBody) && strBody.Contains("/imageserve")) - // { - // var newStrBody = strBody.Replace(_configuration["FileUpload:hostname"], context.Request.HttpContext.Request.Host.Value); - - // //var buffer = Encoding.UTF8.GetBytes(newStr); - - // //using var ms2 = new MemoryStream(); - // //ms2.Write(buffer, 0, buffer.Length); - // //ms2.Seek(0, SeekOrigin.Begin); - // //await ms2.CopyToAsync(response); - - // using (var writer = new StreamWriter(response)) - // { - // await writer.WriteAsync(newStrBody); - // await writer.FlushAsync(); - // } - // } - // } - // else - // { - // await _next(context); - // } - // } - // catch (System.Exception ex) - // { - // _logger.LogError($" http中间件发生错误: " + ex.ToString()); - // } - // finally - // { - // context.Response.Body = response; - // } - // context.Response.OnCompleted(() => - // { - // return Task.CompletedTask; - // }); - //} - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs deleted file mode 100644 index 9dbb302..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Middleware/LogMiddleware.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Middleware -{ - public class LogMiddleware - { - private readonly ILogger _logger; - - public LogMiddleware(ILogger logger) - { - _logger = logger; - } - private readonly RequestDelegate _next; - public LogMiddleware(RequestDelegate next, ILogger logger) - { - _next = next; - _logger = logger; - } - public async Task InvokeAsync(HttpContext context) - { - try - { - if (context.Request.Method == "POST" || context.Request.Method == "PUT") - { - context.Request.EnableBuffering(); - var body = string.Empty; - using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true)) - { - body = await reader.ReadToEndAsync(); - } - context.Request.Body.Position = 0; // 重置Body流,以便后续使用 - - context.Items["RequestBody"] = body; - } - else if (context.Request.Method == "GET") - { - // 获取GET请求的参数 - var parameters = context.Request.Query; - if (parameters != null && parameters.Any()) - { - StringBuilder sbParams = new StringBuilder(); - foreach (var parameter in parameters) - { - var paramName = parameter.Key; - var paramValue = parameter.Value; - sbParams.Append($"{paramName}={paramValue}&"); - } - context.Items["Querystring"] = sbParams.ToString().TrimEnd('&'); - } - } - } - catch (Exception ex) - { - _logger.LogError("Error reading request body: {0}", ex.Message); - } - await _next(context); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs deleted file mode 100644 index 8cb3233..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketClientInstance.cs +++ /dev/null @@ -1,191 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Utils; - -namespace WeiCloud.Core.MsgSocket -{ - public class MsgWebSocketClientInstance - { - private readonly ILogger _logger; - public MsgWebSocketClientInstance(ILogger logger) - { - _logger = logger; - } - /// - /// 客户端 hubName-clientIds - /// - //private readonly ConcurrentDictionary> Clients = new ConcurrentDictionary>(); - /// - /// clientId-hubName - /// - private readonly ConcurrentDictionary ClientHub = new ConcurrentDictionary(); - /// - /// clientId-userId - /// - private readonly ConcurrentDictionary ClientUserId = new ConcurrentDictionary(); - //public List GetClientIdsByHubName(string hubName) - //{ - // List _; - // if (Clients.TryGetValue(hubName, out _)) - // { - // return _; - // } - // return null; - //} - public async Task UnSubscribe(string clientId) - { - try - { - ClientHub.TryRemove(clientId, out _); - //var userId = 0L; - ClientUserId.TryRemove(clientId,out var userId); - - //Console.WriteLine($"当前在线人数:{keys}"); - //_logger.LogInformation($"{clientId}下线,UserId:{userId}"); - //var clientIds = ClientUserId.Keys.ToList().Join(","); - //var userIds = ClientUserId.Values.ToList().Join(","); - var clientIds = ClientUserId.Where(t => t.Value == userId).Select(t => t.Key).ToList(); - _logger.LogInformation($"{clientId}下线,在线用户:UserId:{userId} 客户端ID:{clientIds.Join(",")}"); - } - catch (Exception ex) - { - _logger.LogError(ex, $"{clientId} UnSubscribe 取消连接"); - } - } - public async Task ClientIdMapUserId(string clientId, long userId) - { - ClientUserId.TryAdd(clientId, userId); - } - private string GetRequestMsg(string action, object message) - { - var requestMsg = string.Empty; - if (message != null) - { - requestMsg = $"{action}_{message}"; - } - else - { - requestMsg = action; - } - return requestMsg; - } - public async Task GetClientMapUserId(string clientId) - { - long userId = 0; - int count = 0; - while (count < 10) - { - ClientUserId.TryGetValue(clientId, out userId); - if (userId > 0) - { - break; - } - count++; - await Task.Delay(1000); - } - _logger.LogInformation($"获取用户Id:ClientId:{clientId};UserId:{userId}"); - if (userId == 0) - { - _logger.LogWarning($"获取用户Id失败:ClientId:{clientId}"); - } - return userId; - } - public async Task Subscribe(string clientId, string action, object message) - { - var result = string.Empty; - try - { - if (string.IsNullOrWhiteSpace(action)) - { - _logger.LogError("action为空"); - return result; - } - var requestMsg = GetRequestMsg(action, message); - - var orgHubName = string.Empty; - - var userId = await GetClientMapUserId(clientId); - var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); - ClientHub.TryAdd(clientId, hubName); - - _logger.LogWarning($"订阅完成:ClientId:{clientId} UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()}"); - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - } - return result; - } - /// - /// 获取客户端ID - /// - /// - /// - /// - public async Task?> GetClientIds(string action, object message) - { - List? clientIds = null; - try - { - if (string.IsNullOrWhiteSpace(action)) - { - _logger.LogError("action为空"); - return clientIds; - } - var requestMsg = string.Empty; - if (message != null) - { - requestMsg = $"{action}_{message}"; - } - else - { - requestMsg = action; - } - var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); - //Clients.TryGetValue(hubName, out clientIds); - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - } - return clientIds; - } - public async Task?> GetClientIds(long userId, string action, object message) - { - List? clientIds = null; - try - { - if (string.IsNullOrWhiteSpace(action)) - { - _logger.LogError("action为空"); - return clientIds; - } - var requestMsg = GetRequestMsg(action, message); - var hubName = MD5Helper.GetMd5String(requestMsg.ToLower()); - //Clients.TryGetValue(hubName, out clientIds); - - clientIds = ClientHub.Where(t => t.Value == hubName).Select(t => t.Key).ToList(); - - var userClientIds = ClientUserId.Where(t => t.Value == userId).Select(t => t.Key).ToList(); - clientIds = clientIds.Where(t => userClientIds.Contains(t)).ToList(); - if (clientIds != null && clientIds.Any()) - { - _logger.LogInformation($"获取客户端ID:UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()} 客户端ID:{clientIds.Join(",")}"); - } - else - { - _logger.LogInformation($"获取客户端ID:UserId:{userId} HubName:{hubName} RequestMsg:{requestMsg.ToLower()} 客户端ID:空"); - } - } - catch (Exception ex) - { - _logger.LogError(ex.Message); - } - return clientIds; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs b/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs deleted file mode 100644 index 6f99b70..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/MsgSocket/MsgWebSocketMessageHandler.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using System; -using System.Net.WebSockets; -using System.Threading.Tasks; -using WebSocketUtil; -using WeiCloud.Core.Services; -using WeiCloud.Core.Services.Message; - -namespace WeiCloud.Core.MsgSocket -{ - public class MsgWebSocketMessageHandler : WebSocketHandler - { - private readonly MsgWebSocketClientInstance _msgWebSocketClientInstance; - private readonly IUsersCoreService _usersCoreService; - private readonly IMsgCenterCoreService _msgCenterCoreService; - private readonly ILogger _logger; - public MsgWebSocketMessageHandler(WebSocketConnectionManager webSocketConnectionManager, MsgWebSocketClientInstance msgWebSocketClientInstance, IUsersCoreService usersCoreService, IMsgCenterCoreService msgCenterCoreService, ILogger logger) : base(webSocketConnectionManager) - { - _msgWebSocketClientInstance = msgWebSocketClientInstance; - _usersCoreService = usersCoreService; - _msgCenterCoreService = msgCenterCoreService; - _logger = logger; - } - public override async void OnConnected(WebSocket socket, HttpContext context, string key) - { - var token = string.Empty; - try - { - base.OnConnected(socket, context, key); - token = context.Request.Query["token"]; - var userId = 0L; - if (!string.IsNullOrEmpty(token)) - { - //var user = await _usersCoreService.GetUserInfoByJwt(token); - var user = _usersCoreService.GetUserInfoByJwtStr(token); - long.TryParse(user.Sub, out userId); - if (userId > 0) - { - //Console.WriteLine($"{userId}上线:ClientId={key}"); - await _msgWebSocketClientInstance.ClientIdMapUserId(key, userId); - } - else - { - _logger.LogWarning($"{key} {token} token验证失败"); - } - } - _logger.LogInformation($"{userId}上线:ClientId={key}"); - } - catch (Exception ex) - { - Console.WriteLine($"token验证失败{ex.Message} {ex.StackTrace} {ex.Source} {token}"); - _logger.LogError(ex, $"{token} token验证失败"); - } - } - public override async Task OnDisconnected(WebSocket socket, string connectId) - { - await _msgWebSocketClientInstance.UnSubscribe(connectId); - await base.OnDisconnected(socket, connectId); - //Console.WriteLine($"{connectId}下线"); - } - public override async Task ReceiveAsync(string action, string clientId, object message) - { - if (string.IsNullOrWhiteSpace(action)) - { - return; - } - var _userId = await _msgWebSocketClientInstance.GetClientMapUserId(clientId); - await _msgWebSocketClientInstance.Subscribe(clientId, action, message); - if (_userId > 0) - { - await _msgCenterCoreService.ResendInternalMsg(_userId);//重发未读消息 - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs deleted file mode 100644 index 5ccaa75..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/INlogMessageHelper.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Text; -using WeiCloud.Utils; - -namespace WeiCloud.Core -{ - public interface INlogMessageHelper: ITransentInject - { - string GetNlogMessage(HttpContext context, string parameter, string parmValue, string message); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs deleted file mode 100644 index e60aa33..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/LoggerHelper.cs +++ /dev/null @@ -1,187 +0,0 @@ -using NLog.Config; -using NLog; -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml.Linq; -using System.Linq; - -namespace WeiCloud.Core.NlogTools -{ - public static class LoggerHelper - { - //优先级:Trace>Debug>Info>Warn>Error>Fatal - private const string MssqlDbProvider = "Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"; - private const string MysqlDbProvider = "MySql.Data.MySqlClient.MySqlConnection, MySql.Data"; - public static Logger DbLogger = LogManager.GetLogger("logdb"); - public static Logger FileLogger = LogManager.GetLogger("logfile"); - /// - /// 确保NLog配置文件sql连接字符串正确 - /// - /// - /// - /// - public static void EnsureNLogConfig(string nLogPath, string dbType, string sqlConnectionStr) - { - var xd = XDocument.Load(nLogPath); - if (xd.Root != null && xd.Root.Elements().FirstOrDefault(a => a.Name.LocalName == "targets") is XElement targetsNode && targetsNode.Elements().FirstOrDefault(a => a.Name.LocalName == "target" && a.Attribute("name")?.Value == "log_database") is XElement targetNode) - { - if (!targetNode.Attribute("connectionString").Value.Equals(sqlConnectionStr)) //连接字符串不一致则修改 - { - targetNode.Attribute("connectionString").Value = sqlConnectionStr; - //dbProvider的变动仅限mssql和mysql - targetNode.Attribute("dbProvider").Value = dbType.ToLower() == "mysql" ? MysqlDbProvider : MssqlDbProvider; - xd.Save(nLogPath); - //编辑后重新载入配置文件(不依靠NLog自己的autoReload,有延迟) - LogManager.Configuration = new XmlLoggingConfiguration(nLogPath); - } - } - } - /// - /// 写日志到数据库 - /// - /// 日志等级 - /// 信息 - /// 异常 - public static void WriteDbLog(LogLevel logLevel, string message, Exception exception = null, string platHost = "") - { - var msg = message; - if (exception != null) - { - msg = $"{exception.StackTrace}"; - - } - var theEvent = new LogEventInfo(logLevel, DbLogger.Name, msg) - { - Exception = exception, - Properties = - { - ["LogType"] = exception != null ? exception.Source : "", - ["platHost"] = platHost - } - }; - DbLogger.Log(theEvent); - } - /// - /// 写日志到文件 - /// - /// 日志等级 - /// 信息 - /// 异常 - public static void WriteFileLog(LogLevel logLevel, string message, Exception exception = null, string platHost = "") - { - var msg = $"{message}===="; - if (exception != null) - { - msg = $"{message}======StackTrace====={exception.StackTrace}"; - } - - var theEvent = new LogEventInfo(logLevel, FileLogger.Name, msg) - { - Exception = exception, - Properties = - { - ["LogType"] = exception != null ? exception.Source : "", - ["platHost"] = platHost - } - }; - FileLogger.Log(theEvent); - } - #region 输出日志 - /// - /// 错误日志 - /// - /// - /// - /// 1、DB 2、File - /// - public static void Error(string message, Exception ex, int type = 1, string platHost = "") - { - var msg = ""; - if (ex != null) - { - message += $",Ex:{ex.Message}"; - } - - if (!string.IsNullOrEmpty(message) && ex == null) - { - msg = $"【附加信息】 : {message}
"; - } - else if (!string.IsNullOrEmpty(message) && ex != null) - { - var errorMsg = BeautyErrorMsg(ex); - msg = $"【附加信息】 : {message}
{errorMsg}"; - } - else if (string.IsNullOrEmpty(message) && ex != null) - { - msg = BeautyErrorMsg(ex); - } - - if (type == 1) - { - WriteDbLog(LogLevel.Error, msg, ex, platHost); - } - else - { - WriteFileLog(LogLevel.Error, msg, ex, platHost); - } - } - public static void Error(string message, int type = 1, Exception ex = null, string platHost = "") - { - if (type == 1) - { - WriteDbLog(LogLevel.Error, message, ex, platHost); - } - else - { - WriteFileLog(LogLevel.Error, message, ex, platHost); - } - } - public static void Debug(string message, int type = 1, string platHost = "") - { - if (type == 1) - { - WriteDbLog(LogLevel.Debug, message, platHost: platHost); - } - else - { - WriteFileLog(LogLevel.Debug, message); - } - } - public static void Info(string message, int type = 1) - { - if (type == 1) - { - WriteDbLog(LogLevel.Info, message); - } - else - { - WriteFileLog(LogLevel.Info, message); - } - } - public static void Warn(string message, int type = 1) - { - if (type == 1) - { - WriteDbLog(LogLevel.Warn, message); - } - else - { - WriteFileLog(LogLevel.Warn, message); - } - } - /// - /// 美化错误信息 - /// - /// 异常 - /// 错误信息 - private static string BeautyErrorMsg(Exception ex) - { - var errorMsg = string.Format("【异常类型】:{0}
【异常信息】:{1}
【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace }); - // errorMsg = errorMsg.Replace("\r\n", "
"); - // errorMsg = errorMsg.Replace("位置", "位置"); - return errorMsg; - } - #endregion - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs deleted file mode 100644 index 2c4e751..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/NlogTools/NlogMessageHelper.cs +++ /dev/null @@ -1,300 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; -using System; -using System.Text; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.InfoModels; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core -{ - public class NlogMessageHelper - { - private readonly HttpContext _context; - private readonly string _parameter; - private readonly string _parmValue; - private readonly string _message; - private readonly Exception _exception; - private readonly string _actionname; - - private readonly int? _equipId; - private readonly string _newParmValue; - private readonly int _logType; - private readonly int? _projectId; - private long? _userId = 0; - private string _userName = ""; - private string _machineIp = ""; - //private WeiCloudDBContext _cloudContext; - /// - /// 实例化 WebAPI Controller类的日志消息获取类 - /// - /// 当前API的上下文 - /// API返回参数名 - /// API返回参数值 - /// 提示信息 - public NlogMessageHelper(HttpContext context, string parameter, string parmValue, string message) - { - _context = context; - _parameter = parameter; - _parmValue = parmValue; - _message = message; - } - /// - /// 实例化 控制台程序或一般类的日志消息获取类 - /// - /// - /// - /// - public NlogMessageHelper(string actionname, string message) - { - _actionname = actionname; - _message = message; - } - public NlogMessageHelper(string actionname, Exception ex) - { - _actionname = actionname; - _exception = ex; - } - - public Nlog GetAPINlog() - { - long userid = 0; - string username = ""; - //通过授权验证信息获得当前用户 - if (_context.User.Claims != null) - { - foreach (var item in _context.User.Claims) - { - if (item.Type == "sub") - { - userid = long.Parse(item.Value); - } - if (item.Type == "name") - { - username = item.Value; - } - } - } - - var log = new Nlog() - { - Id = UidGenerator.Uid(), - MachineIp = _context.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + _context.Connection.RemotePort, - CreateUserId = userid, - CreateUserName = username, - CreateTime = DateTime.Now, - ActionName = _context.Request.Path, - Parameter = _parameter, - OldParmValue = _parmValue, - Message = _message, - EndDateTime = DateTime.Now - }; - - return log; - } - - public Nlog GetClassNlog() - { - var log = new Nlog() - { - Id = UidGenerator.Uid(), - MachineIp = "localhost", - CreateTime = DateTime.Now, - ActionName = _actionname, - Message = _message, - EndDateTime = DateTime.Now - }; - return log; - } - /// - /// 日志写入文件 - /// - /// - public string GetNlogMessage() - { - Nlog log; - if (_context != null) - { - log = GetAPINlog(); - //------日志添加入数据库 - //edit by wt 2020.06.18 此处写数据库日志先屏蔽掉 用全局ActionFilter进行代替 - //PostNlogs(log).Wait(); - //--------end------- - } - else - { - log = GetClassNlog(); - } - - StringBuilder messageString = new StringBuilder(); - messageString.Append(string.IsNullOrEmpty(log.MachineIp) ? "" : log.MachineIp + "|"); - messageString.Append(log.CreateUserId == 0 ? "" : log.CreateUserId.ToString() + "|"); - messageString.Append(string.IsNullOrEmpty(log.CreateUserName) ? "" : log.CreateUserName + "|"); - messageString.Append(string.IsNullOrEmpty(log.ActionName) ? "" : log.ActionName + "|"); - messageString.Append(string.IsNullOrEmpty(log.Parameter) ? "" : log.Parameter + "|"); - messageString.Append(string.IsNullOrEmpty(log.OldParmValue) ? "" : log.OldParmValue + "|"); - if (_exception != null) - { - var _msg = JsonConvert.SerializeObject(_exception); - messageString.Append(_msg + "|"); - } - else - { - messageString.Append(string.IsNullOrEmpty(log.Message) ? "" : log.Message + "|"); - } - return messageString.ToString(); - } - /// - /// 日志写入数据库 - /// - /// - /// - /*public async Task PostNlogs(Nlog log) - { - _cloudContext = new WeiCloudDBContext(); - var res = 0; - _cloudContext.Nlog.Add(log); - //数据库中更新用户状态 - res = await _cloudContext.SaveChangesAsync(); - if (res > 0) - { - return RequestBackStatuEnum.success.Value; - } - else - return RequestBackStatuEnum.fail.Value; - }*/ - /* public async Task GetLog(Nlog log) - { - int n = await PostNlogs(log); - return n; - }*/ - - - /// - /// 构造函数3 - /// - /// 当前API的上下文 - /// 设备id - /// 控制的参数名称 - /// 参数老的值 - /// 参数新的值 - /// 备注提示信息 - /// 日志类型 - public NlogMessageHelper(HttpContext context, int? projectId, int? equipId, string parameter, string oldParmValue, string newParmValue, string message, int logType) - { - _context = context; - _parameter = parameter; - _parmValue = oldParmValue; - _message = message; - _equipId = equipId; - _newParmValue = newParmValue; - _logType = logType; - _projectId = projectId; - _actionname = _context.Request.Path; - } - /// - /// 构造函数4 - /// - /// 用户id - /// 用户名称 - /// 操作名称 - /// 项目id - /// 设备id - /// 设备调用参数 - /// 老值 - /// 新的值 - /// 备注操作返回信息 - /// 日志类型 - public NlogMessageHelper(ContextModel contextModel, int? projectId, int? equipId, string parameter, string oldParmValue, string newParmValue, string message, int logType) - { - _context = null; - _parameter = parameter; - _parmValue = oldParmValue; - _message = message; - _equipId = equipId; - _newParmValue = newParmValue; - _logType = logType; - _projectId = projectId; - _actionname = contextModel.actionName; - _userId = contextModel.userId; - _userName = contextModel.userName; - _machineIp = contextModel.machineIp; - } - /// - /// 获取日志信息 配合构造函数3使用 - /// - /// 返回日志对象 - public Nlog GetAPINlogEx() - { - - //通过授权验证信息获得当前用户 - - if (_context != null) - { - if (_context.User.Claims != null) - { - foreach (var item in _context.User.Claims) - { - if (item.Type == "sub") - { - _userId = long.Parse(item.Value); - } - if (item.Type == "name") - { - _userName = item.Value; - } - } - } - _machineIp = _context.Connection.RemoteIpAddress.ToString().Replace("::ffff:", "") + ":" + _context.Connection.RemotePort; - } - - var log = new Nlog() - { - Id = UidGenerator.Uid(), - MachineIp = _machineIp, - CreateUserId = _userId.Value, - CreateUserName = _userName, - CreateTime = DateTime.Now, - ActionName = _actionname, - Parameter = _parameter, - OldParmValue = _parmValue, - Message = _message, - EndDateTime = DateTime.Now, - NewParmValue = _newParmValue, - LogType = _logType, - EquipId = _equipId, - ProjectId = _projectId - }; - return log; - } - - /// - /// 存储用户日志信息2 并输出文本信息 - /// - /// 日志文本信息 - public string GetNlogMessageEx() - { - Nlog log; - if (_context != null) - { - log = GetAPINlogEx(); - //------日志添加入数据库 - //PostNlogs(log).Wait(); - //--------end------- - } - else - { - log = GetClassNlog(); - } - StringBuilder messageString = new StringBuilder(); - messageString.Append(string.IsNullOrEmpty(log.MachineIp) ? "" : log.MachineIp + "|"); - messageString.Append(log.CreateUserId == 0 ? "" : log.CreateUserId.ToString() + "|"); - messageString.Append(string.IsNullOrEmpty(log.CreateUserName) ? "" : log.CreateUserName + "|"); - messageString.Append(string.IsNullOrEmpty(log.ActionName) ? "" : log.ActionName + "|"); - messageString.Append(string.IsNullOrEmpty(log.Parameter) ? "" : log.Parameter + "|"); - messageString.Append(string.IsNullOrEmpty(log.OldParmValue) ? "" : log.OldParmValue + "|"); - messageString.Append(string.IsNullOrEmpty(log.Message) ? "" : log.Message + "|"); - return messageString.ToString(); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs deleted file mode 100644 index da85be0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/PayTool/HttpMethods.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.PayTool -{ - /// - /// Http方法 - /// - public class HttpMethods - { - /// - /// 创建HttpClient - /// - /// - public static HttpClient CreateHttpClient(string url, IDictionary cookies = null) - { - HttpClient httpclient; - HttpClientHandler handler = new HttpClientHandler(); - var uri = new Uri(url); - if (cookies != null) - { - foreach (var key in cookies.Keys) - { - string one = key + "=" + cookies[key]; - handler.CookieContainer.SetCookies(uri, one); - } - } - //如果是发送HTTPS请求 - if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) - { - ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; - httpclient = new HttpClient(handler); - } - else - { - httpclient = new HttpClient(handler); - } - return httpclient; - } - #region 同步请求 - - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static string Post(string url, string jsonData) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new StringContent(jsonData); - postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); - Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); - return result.Result; - } - - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static string Post(string url, byte[] req) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new ByteArrayContent(req); - Task result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); - return result.Result; - } - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static string Post(string url, Dictionary pairs) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new FormUrlEncodedContent(pairs); - var result = httpClient.PostAsync(url, postData).Result.Content.ReadAsStringAsync(); - return result.Result; - - } - /// - /// get 请求 - /// - /// 请求地址 - /// - public static string Get(string url) - { - HttpClient httpClient = CreateHttpClient(url); - Task result = httpClient.GetAsync(url).Result.Content.ReadAsStringAsync(); - return result.Result; - } - - #endregion - - #region 异步请求 - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static Task PostAsync(string url, string jsonData) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new StringContent(jsonData); - postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); - var result = httpClient.PostAsync(url, postData); - return result; - } - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static Task PostAsync(string url, byte[] req) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new ByteArrayContent(req); - var result = httpClient.PostAsync(url, postData); - return result; - } - /// - /// post 请求 - /// - /// 请求地址 - /// 请求参数 - /// - public static Task PostAsync(string url, Dictionary pairs) - { - HttpClient httpClient = CreateHttpClient(url); - var postData = new FormUrlEncodedContent(pairs); - var result = httpClient.PostAsync(url, postData); - return result; - } - - /// - /// get 请求 - /// - /// 请求地址 - /// - public static Task GetAsync(string url) - { - HttpClient httpClient = CreateHttpClient(url); - var result = httpClient.GetAsync(url); - return result; - } - #endregion - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs deleted file mode 100644 index 43b6a4a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/PayTool/PayRequesEntity.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.PayTool -{ - public class PayRequesEntity - { - /// - /// 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 - /// - public string timeStamp { get; set; } - - /// - /// 随机字符串,长度为32个字符以下。 - /// - public string nonceStr { get; set; } - - /// - /// 统一下单接口返回的 prepay_id 参数值 - /// - public string package { get; set; } - - /// - /// 签名算法 - /// - public string signType { get; set; } - - /// - /// 签名 - /// - public string paySign { get; set; } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs deleted file mode 100644 index b4ca760..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/PayTool/WeChatPayHelper.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Xml.Linq; - -namespace WeiCloud.Core.PayTool -{ -// public class WeChatPayHelper -// { -// //private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); - -// public PayRequesEntity Unifiedorder(string openid, string totalfee, string orderNo) -// { -// //var PayUrl = AppSetting.Load().WechatPayStrings.FirstOrDefault().UnifiedorderURL; -// //获取统一下单参数 -// var param = GetUnifiedOrderParam(openid, orderNo, totalfee); -// //_logger.Info(() => "微信支付统一下单 发送参数为 "+param+""); -// //统一下单后拿到的xml结果 -// var payResXML = HttpMethods.Post(AppSetting.Load().WechatPayStrings.FirstOrDefault().UnifiedorderURL, param); -// //_logger.Info(() => "微信支付统一下单 返回参数为 " + payResXML + ""); -// var payRes = XDocument.Parse(payResXML); -// var root = payRes.Element("xml"); -// var res = GetPayRequestParam(root); -// //_logger.Info(() => "微信支付统一下单 参数实体为 " + JsonConvert.SerializeObject(res) + ""); -// return res; -// } - - -// /// -// /// 取统一下单的请求参数 -// /// -// /// -// /// -// private string GetUnifiedOrderParam(string openid,string orderNo, string totalfee) -// { -// string appid = AppSetting.Load().WechatStrings.FirstOrDefault().APPID; -// string secret = AppSetting.Load().WechatStrings.FirstOrDefault().SECRET; -// string mch_id = AppSetting.Load().WechatPayStrings.FirstOrDefault().Mch_ID; -// string ip = AppSetting.Load().Configurations.FirstOrDefault().IP; -// string PayResulturl = AppSetting.Load().WechatPayStrings.FirstOrDefault().PayResulturl; - -// string strcode = "益谦文化小程序-微信支付购买";////商品描述交易字段格式根据不同的应用场景按照以下格式:APP——需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。 -// byte[] buffer = Encoding.UTF8.GetBytes(strcode); -// string body = Encoding.UTF8.GetString(buffer, 0, buffer.Length); -// System.Random Random = new System.Random(); -// var dic = new Dictionary -// { -// {"appid", appid}, -// {"mch_id", mch_id}, -// {"nonce_str", GetRandomString(20)/*Random.Next().ToString()*/}, -// {"body",body}, -// {"out_trade_no",orderNo},//商户自己的订单号码 -// {"total_fee",totalfee}, -// {"spbill_create_ip",ip},//服务器的IP地址 -// {"notify_url",PayResulturl},//异步通知的地址,不能带参数 -// {"trade_type","JSAPI" }, -// {"openid",openid} -// }; -// //加入签名 -// dic.Add("sign", GetSignString(dic)); - -// var sb = new StringBuilder(); -// sb.Append(""); -// foreach (var d in dic) -// { -// sb.Append("<" + d.Key + ">" + d.Value + ""); -// } -// sb.Append(""); -// return sb.ToString(); -// } - - -// /// -// /// 获取返回给小程序的支付参数 -// /// -// /// -// /// -// /// -// /// -// private PayRequesEntity GetPayRequestParam(XElement root) -// { -// string appid = AppSetting.Load().WechatStrings.FirstOrDefault().APPID; -// //当return_code 和result_code都为SUCCESS时才有我们要的prepay_id -// if (root.Element("return_code").Value == "SUCCESS" && root.Element("result_code").Value == "SUCCESS") -// { -// var res = new Dictionary -// { -// {"appId", appid}, -// {"timeStamp", Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds).ToString()}, -// {"nonceStr", GetRandomString(20)}, -// {"package", "prepay_id=" + root.Element("prepay_id").Value}, -// {"signType", "MD5"} -// }; -// //在服务器上签名 -// res.Add("paySign", GetSignString(res)); - -// var payEntity = new PayRequesEntity -// { -// package = res["package"], -// nonceStr = res["nonceStr"], -// paySign = res["paySign"], -// signType = res["signType"], -// timeStamp = res["timeStamp"] -// }; -// return payEntity; -// } - -// return new PayRequesEntity(); -// } - - -// /// -// /// 从字符串里随机得到,规定个数的字符串. -// /// -// /// -// /// -// /// -// private static string GetRandomString(int CodeCount) -// { -// string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; -// string[] allCharArray = allChar.Split(','); -// string RandomCode = ""; -// int temp = -1; -// Random rand = new Random(); -// for (int i = 0; i < CodeCount; i++) -// { -// if (temp != -1) -// { -// rand = new Random(temp * i * ((int)DateTime.Now.Ticks)); -// } -// int t = rand.Next(allCharArray.Length - 1); -// while (temp == t) -// { -// t = rand.Next(allCharArray.Length - 1); -// } -// temp = t; -// RandomCode += allCharArray[t]; -// } - -// return RandomCode; -// } - - -// private string GetSignString(Dictionary dic) -// { -// string key = AppSetting.Load().WechatPayStrings.FirstOrDefault().WxPayKey;//商户平台 API安全里面设置的KEY 32位长度 -// dic = dic.OrderBy(d => d.Key).ToDictionary(d => d.Key, d => d.Value);//排序 -// //连接字段 -// var sign = dic.Aggregate("", (current, d) => current + (d.Key + "=" + d.Value + "&")); -// sign += "key=" + key; -// System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); -// sign = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(sign))).Replace("-", null); -// return sign; -// } - - - -// private static Object PostUnifiedOrder(string payUrl, string para) -// { -// string result = string.Empty; -// try -// { -// HttpClient client = new HttpClient(); -// HttpContent httpContent = new StringContent(para); -// httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); -// httpContent.Headers.ContentType.CharSet = "utf-8"; -// HttpResponseMessage hrm = client.PostAsync(payUrl, httpContent).Result; -// return hrm; -// } -// catch (Exception e) -// { -// result = e.Message; -// } -// return result; -// } -//} -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs deleted file mode 100644 index fecb9b2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Report/ReportEnum.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.Report -{ - public class ReportEnum - { - - } - public class ReportGroupCalculateEnum - { - /// - /// 组内可能多个值 - /// - public const short Common = 0; - /// - /// 组内求平均 - /// - public const short Average = 1; - } - public class ReportSourceTypeEnum - { - /// - /// 实时值 - /// - public const short RealTime = 1; - /// - /// 状态值(目前是根据EquipId获取设备状态值) - /// - public const short Status = 2; - } - //public enum QueryTimeTypeEnum - //{ - // Custom = 0, - // Hour = 1, - // Day = 2, - // Month = 3, - // Year = 4 - //} - public enum ReportEnergyConsumeTypeEnum - { - /// - /// 电 - /// - ElectricPower = 1, - /// - /// 气 - /// - Gas = 2, - /// - /// 水 - /// - Water = 3, - /// - /// 热 - /// - Heat = 4, - /// - /// 碳 - /// - Carbon = 5, - /// - /// 电、气 天燃气立方米*10=能耗单位统一kWh - /// - ElectricPower_Gas = 12 - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs deleted file mode 100644 index b75835a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/CronExpressionHelper.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core -{ - public class CronExpressionHelper - { - /// - /// 获取Cron表达式 - /// - /// 界面表达式 - /// - public static string GetCronExpression(string crondesc) - { - if (string.IsNullOrEmpty(crondesc)) - { - return ""; - } - string cron = ""; - try - { - string[] atr = crondesc.Trim().Split("|"); - switch (atr[0]) - { - //传递字符串 - //标记 月 日 周 天 时 分 秒 - //0 1 2 3 4 5 6 7 - - //使用字符串 - // 秒 分 时 日 月 年 - // 7 6 5 2 1 * - case "1": //每年的x月x日x时x分x秒执行 - cron = $"{atr[7]} {atr[6]} {atr[5]} {atr[2]} {atr[1]} ?"; - break; - case "2"://每季度的倒数x日x时x分x秒执行 - cron = $"{atr[7]} {atr[6]} {atr[5]} L-{Convert.ToInt32(atr[2]) - 1} 3,6,9,12 ?"; - break; - case "3"://每月的x日x时x分x秒执行 - cron = $"{atr[7]} {atr[6]} {atr[5]} {atr[2]} * ?"; - break; - case "4"://每月的倒数x日x时x分x秒执行 - cron = $"{atr[7]} {atr[6]} {atr[5]} L-{Convert.ToInt32(atr[2]) - 1} * ?"; - break; - case "5"://每周的周xx时x分x秒执行 - int a = Convert.ToInt32(atr[3]) % 7 + 1; - cron = $"{atr[7]} {atr[6]} {atr[5]} ? * {a.ToString()}"; - break; - case "6"://每隔x天的x时x分x秒执行 - cron = $"{atr[7]} {atr[6]} {atr[5]} /{atr[4]} * ?"; - break; - case "7"://每隔x时执行 - cron = $"0 0 /{atr[5]} * * ?"; - break; - case "8"://每隔x分执行 - cron = $"0 /{atr[6]} * * * ?"; - break; - case "9"://每隔x秒执行 - cron = $"/{atr[7]} * * * * ?"; - break; - default: - cron = ""; - break; - } - } - catch - { - cron = ""; - } - return cron; - } - - /// - /// 获取Cron表达式的描述 频率描述 - /// - /// - /// - public static string GetCronExpressionDescInfo(string crondesc) - { - if (string.IsNullOrEmpty(crondesc)) - { - return ""; - } - string cron = ""; - try - { - string[] atr = crondesc.Trim().Split("|"); - switch (atr[0]) - { - //传递字符串 - //标记 月 日 周 天 时 分 秒 - //0 1 2 3 4 5 6 7 - - //使用字符串 - // 秒 分 时 日 月 年 - // 7 6 5 2 1 * - - case "1": //每年的x月x日x时x分x秒执行 - cron = $"每年的{atr[1]}月{atr[2]}日{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; - break; - case "2"://每季度的倒数x日x时x分x秒执行 - cron = $"每季度的倒数第{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; - break; - case "3"://每月的x日x时x分x秒执行 - cron = $"每月{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; - break; - case "4"://每月的倒数x日x时x分x秒执行 - cron = $"每月的倒数第{atr[2]}日的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; - break; - case "5"://每周的周xx时x分x秒执行 - cron = $"每周{atr[3]}的{atr[5]}时{atr[6]}分{atr[7]}秒执行一次"; - break; - case "6"://每隔x天的x时x分x秒执行 - cron = $"每隔{atr[4]}天执行一次,执行时间点:{atr[5]}时{atr[6]}分{atr[7]}秒"; - break; - case "7"://每隔x时执行 - cron = $"每隔{atr[5]}小时执行一次"; - break; - case "8"://每隔x分执行 - cron = $"每隔{atr[6]}分钟执行一次"; - break; - case "9"://每隔x秒执行 - cron = $"每隔{atr[7]}秒执行一次"; - break; - default: - cron = ""; - break; - } - } - catch - { - cron = ""; - } - return cron; - } - - /// - /// 获取时间单位 - /// - /// - /// - public static string GetUnitTypeName(int? timeunit) - { - string unit = ""; - switch (timeunit) - { - case 1: - unit = "秒"; - break; - case 2: - unit = "分"; - break; - case 3: - unit = "时"; - break; - case 4: - unit = "天"; - break; - case 5: - unit = "月"; - break; - default: - unit = ""; - break; - } - return unit; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs deleted file mode 100644 index 1ce1306..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/ExecuterRepository.cs +++ /dev/null @@ -1,99 +0,0 @@ -using NRules.Fluent; -using NRules.RuleModel; -using NRules.RuleModel.Builders; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; - -namespace WeiCloud.Core.RulesEngine -{ - public class ExecuterRepository : IRuleRepository, IExecuterRepository - { - private readonly RuleRepository _internalRuleRepository; - - private IRuleSet _ruleSet; - - private List _assemblys; - - public ExecuterRepository() - { - _internalRuleRepository = new RuleRepository(); - _ruleSet = new RuleSet("default"); - _assemblys = new List(); - } - - public IEnumerable GetRuleSets() - { - //合并 - var sets = new List(); - sets.Add(_ruleSet); - sets.AddRange(_internalRuleRepository.GetRuleSets()); - return sets; - } - - /// - /// 清空规则 edit by wt - /// - public void ClearRules() - { - _ruleSet = new RuleSet("default"); - _assemblys = new List(); - } - - public void AddRule(RuleDefinition definition) - { - var builder = new RuleBuilder(); - builder.Name(definition.Name); - foreach (var condition in definition.Conditions) - { - ParsePattern(builder, condition); - } - foreach (var action in definition.Actions) - { - var param = action.Parameters.FirstOrDefault(); - var obj = GetObject(param.Type); - builder.RightHandSide().Action(ParseAction(obj, action, param.Name)); - } - _ruleSet.Add(new[] { builder.Build() }); - } - - - public void AddAssembly(IEnumerable assemblys) - { - _assemblys.AddRange(assemblys); - } - - public void AddAssembly(Assembly assembly) - { - _assemblys.Add(assembly); - } - - internal void LoadAssemblys() - { - _internalRuleRepository.Load(x => x.From(_assemblys)); - } - - - PatternBuilder ParsePattern(RuleBuilder builder, LambdaExpression condition) - { - var parameter = condition.Parameters.FirstOrDefault(); - var type = parameter.Type; - var customerPattern = builder.LeftHandSide().Pattern(type, parameter.Name); - customerPattern.Condition(condition); - return customerPattern; - } - - - LambdaExpression ParseAction(TEntity entity, LambdaExpression action, String param) where TEntity : class, new() - { - return NRulesHelper.AddContext(action as Expression>); - } - - static dynamic GetObject(Type type) - { - return System.Activator.CreateInstance(type); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs deleted file mode 100644 index 93872a9..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterContainer.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace WeiCloud.Core.RulesEngine -{ - public interface IExecuterContainer - { - IExecuterSession CreateSession(IExecuterRepository executerRepository); - - IExecuterSession CreateSession(IExecuterRepository executerRepository, Action initializationAction); - - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs deleted file mode 100644 index ea9d5f2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterRepository.cs +++ /dev/null @@ -1,31 +0,0 @@ -using NRules.RuleModel; -using System.Collections.Generic; -using System.Reflection; - -namespace WeiCloud.Core.RulesEngine -{ - public interface IExecuterRepository - { - /// - /// 加载运行时的规则 - /// - /// - void AddRule(RuleDefinition definition); - /// - /// 加载预设的规则 - /// - /// - void AddAssembly(IEnumerable assemblys); - /// - /// 加载预设的规则 - /// - /// - void AddAssembly(Assembly assembly); - - IEnumerable GetRuleSets(); - /// - /// 清除规则 - /// - void ClearRules(); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs deleted file mode 100644 index b792b08..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/IExecuterSession.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Collections.Generic; - -namespace WeiCloud.Core.RulesEngine -{ - /// - /// 执行器的会话 - /// - public interface IExecuterSession - { - /// - /// 插入需要处理的对象 - /// - /// - void Insert(object fact); - - /// - /// 插入需要处理的对象 - /// - /// - void InsertAll(IEnumerable facts); - - /// - /// 执行,返回命中的规则数目 - /// - /// - int Fire(); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs deleted file mode 100644 index d894468..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NRulesHelper.cs +++ /dev/null @@ -1,33 +0,0 @@ -using NRules.RuleModel; -using System; -using System.Linq; -using System.Linq.Expressions; - -namespace WeiCloud.Core.RulesEngine -{ - internal class NRulesHelper - { - internal static Expression> AddContext(Expression action) - { - var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) }; - var result = Expression.Lambda>(Expression.Invoke(action, action.Parameters), convertedParameters); - return result; - } - - internal static Expression> AddContext(Expression> action) - { - var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) } - .Concat(action.Parameters).ToArray(); - var result = Expression.Lambda>(action.Body, convertedParameters); - return result; - } - - internal static Expression> AddContext(Expression> action) - { - var convertedParameters = new[] { Expression.Parameter(typeof(IContext)) } - .Concat(action.Parameters).ToArray(); - var result = Expression.Lambda>(action.Body, convertedParameters); - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs deleted file mode 100644 index 245995f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterContainer.cs +++ /dev/null @@ -1,26 +0,0 @@ -using NRules; -using System; - -namespace WeiCloud.Core.RulesEngine -{ - public class NulesExecuterContainer : IExecuterContainer - { - public IExecuterSession CreateSession(IExecuterRepository executerRepository) - { - return CreateSession(executerRepository, null); - } - - public IExecuterSession CreateSession(IExecuterRepository executerRepository, Action initializationAction) - { - var repository = executerRepository as ExecuterRepository; - repository.LoadAssemblys(); - ISessionFactory factory = repository.Compile(); - var session = new NulesExecuterSession(factory.CreateSession()); - if (initializationAction != null) - { - initializationAction(session); - } - return session; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs deleted file mode 100644 index e8939e2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/NulesExecuterSession.cs +++ /dev/null @@ -1,30 +0,0 @@ -using NRules; -using System.Collections.Generic; - -namespace WeiCloud.Core.RulesEngine -{ - public class NulesExecuterSession : IExecuterSession - { - private readonly ISession _session; - - public NulesExecuterSession(ISession session) - { - _session = session; - } - - public void Insert(object fact) - { - _session.Insert(fact); - } - - public void InsertAll(IEnumerable facts) - { - _session.Insert(facts); - } - - public int Fire() - { - return _session.Fire(); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs deleted file mode 100644 index c61758d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RuleDefinition.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; - -namespace WeiCloud.Core.RulesEngine -{ - public class RuleDefinition - { - /// - /// 规则的名称 - /// - public String Name { get; set; } - /// - /// 约束条件 - /// - public List Conditions { get; set; } - /// - /// 执行行动 - /// - public List Actions { get; set; } - - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs deleted file mode 100644 index 6a37e3d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Arithmetic.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - public enum Arithmetic - { - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs deleted file mode 100644 index 1d67aa7..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/Energy.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - public class Energy - { - /// - /// 项目 - /// - public long? ProjectId { get; set; } - /// - /// 机房 - /// - public long? ConstId { get; set; } - - /// - /// 设备组id - /// - public long? EquGroupId { get; set; } - - /// - /// 设备类型 - /// - public long? EquType { get; set; } - - /// - /// 表达式 - /// - private string ParamDesc { get; set; } - - //初始化操作 - public Energy() - { - //初始化变量 - ParamDesc = ""; - } - - - } - - - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs deleted file mode 100644 index 040b6d6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/EnergyTypeEnum.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - public static class EquipmentEnum - { - public const string AmmeterTypeCode = "eq128016"; //电表TypeCode - public const string WatterTypeCode = "eq128017"; //水表TypeCode - public const string GasmeterTypeCode = "eq128018";//燃气表TypeCode - public const string HeatTypeCode = "eq128019";//热表TypeCode - - public const string DirectFiredCode = "eq001039";//直燃机TypeCode - - public const string HotAndColdPump = "eq002003";//冷热泵TypeCode - - public const string CoolingPump = "eq002005";//冷热泵TypeCode - } - - /// - /// 总支不平衡 - /// - public static class EnergyTypeEnum - { - public const string TotalMeterTypeCode = "eg0006"; - public const string BranchMeterTypeCode = "eg0007"; - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs deleted file mode 100644 index bcbdded..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/IEntity.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - public interface IEntity - { - TKey Id { get; set; } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs deleted file mode 100644 index a13c86e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleConditions.cs +++ /dev/null @@ -1,54 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - /// - /// 约束条件 - /// - public class RuleConditions - { - /// - ///主键id - /// - public long? Id { get; set; } - /// - /// 所属规则 - /// - public long? RuleId { get; set; } - /// - /// 参数1 - /// - public string Param1 { get; set; } - /// - /// 四册运算符号 - /// - public string Arithmetic { get; set; } - /// - /// 参数2 - /// - public string Param2 { get; set; } - /// - /// 比较符号 - /// - public string Compare { get; set; } - /// - /// 比较参数 - /// - public string CParam1 { get; set; } - /// - /// 比较运算符号 - /// - public string CArithmetic1 { get; set; } - /// - /// 比较参数 - /// - public string CParam2 { get; set; } - /// - /// 比较运算符号 - /// - public string CArithmetic2 { get; set; } - /// - /// 比较常量 - /// - public float? Constant { get; set; } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs deleted file mode 100644 index 49ffccb..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleInfos.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - /// - /// 规则定义 - /// - public class RuleInfos - { - /// - /// 主键id - /// - public long? Id { get; set; } - public long? ProjectId { get; set; } - public long? ConstId { get; set; } - /// - /// 规则名称 - /// - public string RuleName { get; set; } - /// - /// 设备所属组号 - /// - public long EquGroup { get; set; } - - /// - /// 规则适用项目 - /// - public string[] WithProjects { get; set; } - /// - /// 规则类型 - /// - public RuleTypes RuleType { get; set; } - /// - /// 数据源开始时间 - /// - public DateTime? DataStarTime { get; set; } - /// - /// 数据源截止时间 - /// - public DateTime? DataEndTime { get; set; } - /// - /// 规则自动执行间隔 - /// - public int? Interval { get; set; } - /// - /// 间隔单位 - /// - public int? TimeUnit { get; set; } - /// - /// 执行间隔秒 - /// - public int? Intervals { get; set; } - /// - /// 规则约束条件是否互斥,互斥相当于 or ,否则相当于 and - /// - public bool IsSingle { get; set; } - /// - /// 规则是否启用 - /// - public bool IsUsing { get; set; } - /// - /// 规则描述 - /// - public string RuleDesc { get; set; } - /// - /// 公式表达式 - /// - public string Formula { get; set; } - /// - /// 定时调度Cron - /// - public string Cron { get; set; } - /// - /// 定时调度描述 - /// - public string Crondesc { get; set; } - /// - /// 约束条件 - /// - public List RuleConditionList { get; set; } - - /// - /// 规则参数条件 - /// - public List RuleConditionParamList { get; set; } - - /// - /// 实际执行开始时间 数据的开始时间 - /// - public DateTime? ActualStartTime { get; set; } - /// - /// 实际执行结束时间 数据的结束时间 - /// - public DateTime? ActualEndTime { get; set; } - /// - /// 设备类型 - /// - - public long? EquType { get; set; } - /// - /// 实时参数表达式 - /// - public List RealParamGicExList { get; set; } - /// - /// 实时参数公式 - /// - public List RealFormulaGics { get; set; } - /// - /// 实时参数采集公式解析的设备信息 - /// - public List Equids { get; set; } - /// - /// 设备类型ids - /// - public List EquPTypes { get; set; } - - /// - /// 公式的最终表达式子 用于报警描述 - /// - public string ParamDesc { get; set; } - - /// - /// 能耗分项id - /// - public long? Subentryid { get; set; } - - /// - /// 时间间隔 cron的时间周期 - /// - public int Timeperiod { get; set; } = 0; - } - - /// - /// 实时参数公式 - /// - public class RealFormulaGic - { - public long Id { get; set; } - public string EquName { get; set; } - public string Formula { get; set; } - - public string Paramname { get; set; } - public long? Rid { get; set; } - } - - /// - /// 规则的时间区间 - /// - public class RuleTimeSection - { - /// - /// 返回结果 - /// - public bool result { get; set; } - /// - /// 开始时间 - /// - public DateTime? startTime { get; set; } - /// - /// 结束时间 - /// - public DateTime? endTime { get; set; } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs b/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs deleted file mode 100644 index f6a21c1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/RulesEngine/RulesModels/RuleTypes.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace WeiCloud.Core.RulesEngine.RulesModels -{ - public class RuleTypes - { - public long? Id { get; set; } - public string TypeName { get; set; } - - public long? ParentId { get; set; } - - public string EqType { get; set; } - - public string ParamIds { get; set; } - public long? Fautype { get; set; } - - public long? Fauclass { get; set; } - - public string Energytypes { get; set; } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs b/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs deleted file mode 100644 index 320e2da..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Schedule/ScheduleItemConvert.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Newtonsoft.Json; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.InfoModels; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core.Schedule -{ - public static class ScheduleItemConvert - { - public static TaskMessageHubModel TaskMessageToJobSchedulerConfig(this JobSchedulerConfigItem input) - { - TaskMessageHubModel jobConfigItem = new TaskMessageHubModel - { - JobName = input.JobName, - JobGroup = input.JobGroup, - TriggerName = input.TriggerName, - TriggerGroup = input.TriggerGroup, - IsEnable = input.IsEnable, - Id = input.Id - }; - - jobConfigItem.JobDataMapKey = input.JobDataMapKey; - jobConfigItem.Concurrent = input.Concurrent; - - jobConfigItem.StartAt = input.StartAt; - jobConfigItem.EndAt = input.EndAt; - jobConfigItem.SimpleScheduleIn = input.SimpleScheduleIn; - jobConfigItem.SimpleScheduleCount = input.SimpleScheduleCount; - jobConfigItem.CronExpression = input.CronExpression; - jobConfigItem.IntervalTime = input.IntervalTime; - jobConfigItem.Priority = input.Priority; - jobConfigItem.ServiceName = input.ServiceName; - jobConfigItem.IntervalUnit = input.IntervalUnit; - jobConfigItem.TaskName = input.TaskName; - jobConfigItem.AssemblyItem = input.AssemblyItem; - jobConfigItem.IsDelete = input.IsDeleted; - return jobConfigItem; - } - public static JobSchedulerConfig TaskMessageToJobSchedulerConfig(this TaskMessageHubModel input, JobSchedulerConfig jobConfigItem) - { - if (jobConfigItem == null) - { - jobConfigItem = new JobSchedulerConfig - { - JobName = input.JobName, - JobGroup = input.JobGroup, - TriggerName = input.TriggerName, - TriggerGroup = input.TriggerGroup, - Id = UidGenerator.Uid() - }; - } - else - { - input.JobName = jobConfigItem.JobName; - input.JobGroup = jobConfigItem.JobGroup; - input.TriggerName = jobConfigItem.TriggerName; - input.TriggerGroup = jobConfigItem.TriggerGroup; - input.IsEnable = jobConfigItem.IsEnable != null && (bool)jobConfigItem.IsEnable == true ? (byte)1 : (byte)0; - } - - jobConfigItem.JobDataMapKey = input.JobDataMapKey; - jobConfigItem.Concurrent = input.Concurrent == 1; - - jobConfigItem.StartAt = input.StartAt; - jobConfigItem.EndAt = input.EndAt; - jobConfigItem.SimpleScheduleIn = input.SimpleScheduleIn; - jobConfigItem.SimpleScheduleCount = input.SimpleScheduleCount; - jobConfigItem.CronExpression = input.CronExpression; - jobConfigItem.IntervalTime = input.IntervalTime; - jobConfigItem.Priority = input.Priority; - jobConfigItem.ServiceName = input.ServiceName; - jobConfigItem.IsEnable = input.IsEnable == 1; - jobConfigItem.IntervalUnit = input.IntervalUnit; - jobConfigItem.TaskName = input.TaskName; - if (input.AssemblyItem != null) - jobConfigItem.AssemblyItem = JsonConvert.SerializeObject(input.AssemblyItem); - else - jobConfigItem.AssemblyItem = string.Empty; - return jobConfigItem; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs deleted file mode 100644 index 6eb9420..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/CarbonEmissionService.cs +++ /dev/null @@ -1,135 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services.CarbonEmission -{ - /// - /// 碳排放计算公式 - /// - public class CarbonEmissionService : ICarbonEmissionService - { - private readonly WeiCloudDBUserCenterContext _weiCloudDBUser; - public CarbonEmissionService(WeiCloudDBUserCenterContext weiCloudDBUser) - { - _weiCloudDBUser = weiCloudDBUser; - } - /* - 1、电碳排放tCO2=碳排放因子×用电量(kWh)/1000;各区域电网碳排放因子见右表 - 2、天然气碳排放tCO2=天然气用量(万m3)×低位热值×44/12×单位热值含碳量×碳氧化率 - 低位热值=389.3(GJ/万Nm3) - 单位热值含碳量=0.0153(tC/GJ) - 碳氧化率=99% - 3、外购热力碳排放tCO2=热力碳排放因子0.11×用热量GJ - 4、总碳排放量=电碳排放+天然气碳排放+外购热力碳排放 - */ - /// - /// 碳排放计算公式 - /// - /// - /// - /// - /// - public async Task GetValue(double ammeterDWSum, double gasDWSum, long projectId) - { - var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); - var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new - { - t.Paraname, - t.Realvalue - }).ToListAsync(); - - double carbonEmissionFactor = 0; - if (sysConfigs.Count() == 1) - { - carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); - } - else if (sysConfigs.Count() == 2) - { - carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); - } - var sumCO2 = ammeterDWSum * carbonEmissionFactor / 1000 + (gasDWSum / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; - return sumCO2; - } - /// - /// 碳排放计算公式 - /// - /// - /// - /// - /// - /// - public async Task GetValue(double ammeterDWSum, double gasDWSum, string cityCode, List sysConfigs) - { - double carbonEmissionFactor = 0; - if (sysConfigs.Count() == 1) - { - carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); - } - else if (sysConfigs.Count() == 2) - { - carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == cityCode).Realvalue); - } - var sumCO2 = ammeterDWSum * carbonEmissionFactor / 1000 + (gasDWSum / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; - return sumCO2; - } - /// - /// 碳排放系数 电 - /// - /// - /// - public async Task GetValue_Elect(long projectId) - { - var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); - var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new - { - t.Paraname, - t.Realvalue - }).ToListAsync(); - double carbonEmissionFactor = 0; - if (sysConfigs.Count() == 1) - { - carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); - } - else if (sysConfigs.Count() == 2) - { - carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); - } - var sumCO2 = carbonEmissionFactor / 1000 ; - return sumCO2; - } - /// - /// 碳排放系数 气 - /// - /// - /// - public async Task GetValue_Gas(long projectId) - { - var projectInfo = _weiCloudDBUser.ProjectInfo.FirstOrDefault(t => t.Id == projectId); - var sysConfigs = await _weiCloudDBUser.SysConfig.Where(t => t.ConfigType == SysBaseCodeMeta.CarbonEmissionFactor && (t.Paraname == projectInfo.ProvoiceCode.GetValueOrDefault().ToString() || t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString())).Select(t => new - { - t.Paraname, - t.Realvalue - }).ToListAsync(); - - double carbonEmissionFactor = 0; - if (sysConfigs.Count() == 1) - { - carbonEmissionFactor = double.Parse(sysConfigs[0].Realvalue); - } - else if (sysConfigs.Count() == 2) - { - carbonEmissionFactor = double.Parse(sysConfigs.FirstOrDefault(t => t.Paraname == projectInfo.CityCode.GetValueOrDefault().ToString()).Realvalue); - } - var sumCO2 =(1 / 10000) * 389.3 * 44 / 12 * 0.0153 * 0.99; - return sumCO2; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs deleted file mode 100644 index 18efa30..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/CarbonEmission/ICarbonEmissionService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services.CarbonEmission -{ - public interface ICarbonEmissionService - { - Task GetValue(double ammeterDWSum, double gasDWSum, long projectId); - Task GetValue(double ammeterDWSum, double gasDWSum, string cityCode, List sysConfigs); - Task GetValue_Elect(long projectId); - Task GetValue_Gas(long projectId); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs deleted file mode 100644 index 2defde9..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ConstrInfoGainCoreService.cs +++ /dev/null @@ -1,213 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Core.BaseCore; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.DataQuality; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class ConstrInfoGainCoreService : Grain, IConstrInfoGainCoreService - { - private readonly WeiCloudDBContext _context; - private readonly WeiCloudDBUserCenterContext _userContext; - private readonly IListService _listService; - private readonly IDictionaryService _dictionaryService; - private readonly ILogger _logger; - public ConstrInfoGainCoreService(WeiCloudDBContext context, WeiCloudDBUserCenterContext userContext, IListService listService, IDictionaryService dictionaryService, ILogger logger) - { - _context = context; - _userContext = userContext; - _listService = listService; - _dictionaryService = dictionaryService; - _logger = logger; - } - /// - /// 批量redis获取建筑物 - /// - /// 建筑物集合 - public async Task> GetAllConstructionInfoRedis() - { - //ConstructionInfo construction = new ConstructionInfo(); - //var result = _dictionaryService.GetValue(construction.GetType().Name); - //var list = result.Values.ToList(); - //return await Task.FromResult(list); - return await _context.ConstructionInfo.TagWith("SubDB").AsNoTracking().ToListAsync(); - } - - public async Task GetConstModelById(long id) - { - //ConstructionInfo constInfo = new ConstructionInfo(); - //constInfo = _dictionaryService.GetValue(constInfo.GetType().Name)[id.ToString()]; - //return await Task.FromResult(constInfo); - return _context.ConstructionInfo.TagWith("SubDB").FirstOrDefault(t => t.Id == id); - } - public async Task> GetConstByKeys(string[] keys) - { - //List consts = new List(); - //ConstructionInfo c = new ConstructionInfo(); - //consts = _dictionaryService.GetValue(c.GetType().Name, keys).Select(d => d.Value).ToList(); - //if (consts != null) - //{ - // consts = consts.Where(d => d != null && d.Id > 0).ToList(); - //} - var ids = keys.Select(t => long.Parse(t)).ToList(); - return _context.ConstructionInfo.Where(t => ids.Contains(t.Id)).TagWith("SubDB").AsNoTracking().ToList(); - } - private List GetConstTreeByParentId(long parentId, List constList) - { - List conSmpleList = new List(); - conSmpleList = (from c in constList - where c.Parentid == parentId - orderby c.Constinfo - select new ConstructionInfoTreeNew - { - Id = c.Id, - Label = c.Constinfo, - Constcode = c.Constcode, - Parentid = c.Parentid, - ConstType = c.Consttype, - Children = GetConstTreeByParentId(c.Id, constList) - }).ToList(); - return conSmpleList; - } - /// - /// 查询建筑物树结构 - /// - /// - /// - /// - /// - public async Task> GetConstTreeByProjectId(long projectId, int isUsing, int? level) - { - try - { - //1.根据用户的建筑物权限 ConstantIds - var currentUser = CurrentContext.GetContext(); - //2.根据项目id 以及1中的建筑物ids 从 redis中获取要过滤的建筑物信息 - //var data = _dictionaryService.GetValue("ConstructionInfo").Values.Where(op => op.Projectid == projectId && op.Isusing == 1); - var query = _context.ConstructionInfo.Where(op => op.Projectid == projectId && op.Isusing == 1); - - if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) - { - query = query.Where(op => currentUser.ConstIds.Contains(op.Id)); - } - - if (isUsing >= 0) - { - query = query.Where(o => o.Isusing == isUsing); - } - if (level == 1) - { - query = query.Where(o => o.Parentid == 0); - } - //if (show >=0) - //{ - // data = data.Where(t => t.Isshow == show); - //} - //3.对建筑物信息 进行排序展现 - var data1 = await query.OrderBy(o => o.Constinfo).AsNoTracking().ToListAsync(); - //4.递归组成树根据parentid=0找到一级列表 - var conSmpleList = (from c in data1 - where c.Parentid == 0 - orderby c.Constinfo - select new ConstructionInfoTreeNew - { - Id = c.Id, - Label = c.Constinfo, - Constcode = c.Constcode, - Parentid = c.Parentid, - ConstType = c.Consttype, - Children = GetConstTreeByParentId(c.Id, data1) - }).ToList(); - return await Task.FromResult(conSmpleList); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetConstTreeByProjectIdAsync", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return await Task.FromResult(new List()); - } - /// - /// 查询建筑物树结构 - /// - /// - /// - public async Task> GetConstEquipsTreeByProjectId(long projectId) - { - try - { - //1.根据用户的建筑物权限 ConstantIds - var currentUser = CurrentContext.GetContext(); - //2.根据项目id 以及1中的建筑物ids 从 redis中获取要过滤的建筑物信息 - //var data = _dictionaryService.GetValue("ConstructionInfo").Values.Where(op => op.Projectid == projectId && op.Isusing == 1); - var query = _context.ConstructionInfo.Where(op => op.Projectid == projectId && op.Isusing == 1); - - if (currentUser.RoleCode != SysBaseCodeMeta.AdminCode) - { - query = query.Where(op => currentUser.ConstIds.Contains(op.Id)); - } - - //3.对建筑物信息 进行排序展现 - var data1 = await query.OrderBy(o => o.Constinfo).AsNoTracking().ToListAsync(); - - var equipInfos = await _context.EquipmentInfo.Where(t => t.Projectid == projectId && t.State == 1).AsNoTracking().ToListAsync(); - - - //4.递归组成树根据parentid=0找到一级列表 - var conSmpleList = (from c in data1 - where c.Parentid == 0 - orderby c.Constinfo - select new ConstInfoEquipTreeNewModel - { - Id = c.Id, - Label = c.Constinfo, - ConstCode = c.Constcode, - ParentId = c.Parentid, - ConstType = c.Consttype, - Equips = equipInfos.Where(t => t.Constid == c.Id).Select(t => new ConstInfoEquipEquipModel - { - Id = t.Id, - EquipName = t.Eqname - }).ToList(), - Children = GetConstTreeByParentId(c.Id, data1, equipInfos) - }).ToList(); - return await Task.FromResult(conSmpleList); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetConstTreeByProjectIdAsync", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return await Task.FromResult(new List()); - } - private List GetConstTreeByParentId(long parentId, List constList, List equipInfos) - { - List conSmpleList = new List(); - conSmpleList = (from c in constList - where c.Parentid == parentId - orderby c.Constinfo - select new ConstInfoEquipTreeNewModel - { - Id = c.Id, - Label = c.Constinfo, - ConstCode = c.Constcode, - ParentId = c.Parentid, - ConstType = c.Consttype, - Equips = equipInfos.Where(t => t.Constid == c.Id).Select(t => new ConstInfoEquipEquipModel - { - Id = t.Id, - EquipName = t.Eqname - }).ToList(), - Children = GetConstTreeByParentId(c.Id, constList, equipInfos) - }).ToList(); - return conSmpleList; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs deleted file mode 100644 index 09e97ed..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/IProjectParamMethodRuleCoreService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DataQuality; - -namespace WeiCloud.Core.Services.DataStream -{ - public interface IProjectParamMethodRuleCoreService - { - Task>> GetBindNewCodeNumsV02(Dictionary paramConfigIdDic, List paramConfigs = null, List realMapParamConfigs = null); - Task GetNewCodeNum(long qualityMethodId); - Task GetNewParamGroupCodeNum(long qualityTypeId); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs deleted file mode 100644 index 05464ea..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ISubscribePointCoreService.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.DataStreamModels; - -namespace WeiCloud.Core.Services.DataStream -{ - public interface ISubscribePointCoreService - { - Task> SubscribePoint(long projectId, List pointIds, string clientId = "", bool isValueChanged = false); - /// - /// 订阅主题 项目所有点位 - /// - /// - /// - /// - /// - Task> SubscribePointAll(long projectId, string clientId = "", bool isValueChanged = false); - Task> SubscribePointHeartbeat(string clientId = ""); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs deleted file mode 100644 index 97c64af..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ITimeSeqService.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.DataStream -{ - public interface ITimeSeqService - { - Task> QueryEquipRealDataDoc(DateTime queryTime, long projectId, List equipIds); - Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds); - Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, long realDataId, bool isRepaired = false); - Task> QueryRealDataItemByRealIds(DateTime queryTime, List realDataIds); - Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, List realDataIds, bool isMore = false); - Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1); - //Task>> RecoverHistoryData(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs deleted file mode 100644 index 14533b1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/ProjectParamMethodRuleCoreService.cs +++ /dev/null @@ -1,202 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DataQuality; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Services.DataStream -{ - public class ProjectParamMethodRuleCoreService : IProjectParamMethodRuleCoreService - { - private readonly ILogger _logger; - private readonly WeiCloundDBDataQualityContext _weiCloudDataQualityDBContext; - public ProjectParamMethodRuleCoreService(ILogger logger, WeiCloundDBDataQualityContext weiCloudDataQualityDBContext) - { - _logger = logger; - _weiCloudDataQualityDBContext = weiCloudDataQualityDBContext; - } - /// - /// 生成新code - /// - /// - /// - public async Task GetNewCodeNum(long qualityMethodId) - { - long num = 1; - long i = 1; - try - { - var existingCodes = await _weiCloudDataQualityDBContext.ParamConfig.Where(t => t.QualityMethodId == qualityMethodId && t.IsDeleted == false).AsNoTracking().Select(t => t.Code).ToListAsync(); - - if (existingCodes.Count() > 0) - { - var codeNums = new List { }; - foreach (var existingCode in existingCodes) - { - try - { - codeNums.Add(int.Parse(existingCode.Split("-").Last())); - } - catch (Exception) - { - } - } - codeNums = codeNums.OrderBy(t => t).ToList(); - while (true) - { - if (!codeNums.Any(t => t == i)) - { - break; - } - ++i; - } - } - num = i; - } - catch (Exception ex) - { - Random rd = new Random(); - num = rd.Next(10000, 99999); - _logger.LogError(new LoggerWarp(actionName: "GetNewCodeNum", ex: ex).GetMessage()); - } - return num; - } - /// - /// 绑定时生成新code - /// - /// key方法规则Id、参数Code个数 - /// - /// - /// - public async Task>> GetBindNewCodeNumsV02(Dictionary paramConfigIdDic, List paramConfigs = null, List realMapParamConfigs = null) - { - var paramConfigIds = paramConfigIdDic.Select(t => t.Key).ToList(); - if (paramConfigs == null || paramConfigs.Count() == 0) - { - paramConfigs = await _weiCloudDataQualityDBContext.ParamConfig.AsNoTracking().Where(t => paramConfigIds.Contains(t.Id)).Select(t => new ParamConfig - { - Code = t.Code, - Id = t.Id - }).ToListAsync(); - } - else - { - paramConfigs = paramConfigs.Where(t => paramConfigIds.Contains(t.Id)).ToList(); - } - - if (realMapParamConfigs == null || realMapParamConfigs.Count() == 0) - { - realMapParamConfigs = await _weiCloudDataQualityDBContext.ParamConfig.Where(t => paramConfigIds.Contains(t.ReferId) && t.IsDeleted == false).AsNoTracking().ToListAsync(); - } - else - { - realMapParamConfigs = realMapParamConfigs.Where(t => paramConfigIds.Contains(t.ReferId)).ToList(); - } - - Dictionary> resultItems = new Dictionary> { }; - - foreach (var paramConfigDicItem in paramConfigIdDic) - { - var paramConfig = paramConfigs.FirstOrDefault(t => t.Id == paramConfigDicItem.Key); - var nums = new List { }; - - - #region 计算 - var existingCodes = realMapParamConfigs.Where(t => t.ReferId == paramConfig.Id).Select(t => t.Code).ToList(); - - long i = 1; - - var codeNums = new List { }; - if (existingCodes.Count() > 0) - { - foreach (var existingCode in existingCodes) - { - try - { - codeNums.Add(int.Parse(existingCode.Split("-").Last())); - } - catch (Exception) - { - } - } - codeNums = codeNums.OrderBy(t => t).ToList(); - } - while (nums.Count() <= paramConfigDicItem.Value) - { - try - { - if (!codeNums.Any(t => t == i) && !nums.Any(t => t == i)) - { - nums.Add(i); - } - ++i; - } - catch (Exception ex) - { - } - } - #endregion - var numStrs = new List { }; - foreach (var num in nums) - { - numStrs.Add($"{paramConfig.Code}-{num}"); - } - resultItems.Add(paramConfig.Id, numStrs); - } - - return resultItems; - } - - - /// - /// 生成新code - /// - /// - /// - public async Task GetNewParamGroupCodeNum(long qualityTypeId) - { - long num = 1; - long i = 1; - try - { - var existingCodes = await _weiCloudDataQualityDBContext.ParamGroup.Where(t => t.GroupTypeId == qualityTypeId && t.IsDeleted == false).AsNoTracking().Select(t => t.Code).ToListAsync(); - - if (existingCodes.Count() > 0) - { - var codeNums = new List { }; - foreach (var existingCode in existingCodes) - { - try - { - codeNums.Add(int.Parse(existingCode.Split("-").Last())); - } - catch (Exception) - { - } - } - codeNums = codeNums.OrderBy(t => t).ToList(); - while (true) - { - if (!codeNums.Any(t => t == i)) - { - break; - } - ++i; - } - } - num = i; - } - catch (Exception ex) - { - Random rd = new Random(); - num = rd.Next(10000, 99999); - _logger.LogError(new LoggerWarp(actionName: "GetNewCodeNum", ex: ex).GetMessage()); - } - return num; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs deleted file mode 100644 index 8cbef3f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/SubscribePointCoreService.cs +++ /dev/null @@ -1,175 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; -using System.Net.Http.Headers; -using WeiCloud.Entity.LogicModels.DataStreamModels; -using NPOI.Util; - -namespace WeiCloud.Core.Services.DataStream -{ - public class SubscribePointCoreService : ISubscribePointCoreService - { - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly IHttpClientFactory _httpClientFactory; - private readonly IServiceScopeFactory _serviceScopeFactory; - public SubscribePointCoreService(IHttpClientFactory httpClientFactory, IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration) - { - _logger = logger; - _configuration = configuration; - _httpClientFactory = httpClientFactory; - _serviceScopeFactory = serviceScopeFactory; - } - /// - /// 订阅主题 - /// - /// - /// 点位 - /// - /// 值变化时推送 - /// - public async Task> SubscribePoint(long projectId, List pointIds, string clientId = "", bool isValueChanged = false) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - string dbRealDataResultStr = string.Empty; - try - { - if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "SubscribeMQTT:ApiUrl为空!"; - return result; - } - var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePoint"; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromSeconds(15); - if (string.IsNullOrEmpty(clientId)) - { - clientId = _configuration["SubscribeMQTT:TopicName"]; - } - var body = JsonConvert.SerializeObject(new - { - ProjectId = projectId, - PointIds = pointIds, - ClientId = clientId, - IsValueChanged = isValueChanged - }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - var httpResponse = await client.PostAsync(apiUrl, byteContent); - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - Console.WriteLine($"点位订阅:{dbRealDataResultStr}"); - result = JsonConvert.DeserializeObject>(dbRealDataResultStr); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("点位订阅:{0} {1}", dbRealDataResultStr, pointIds.Join(","))).GetNlogMessage()); - } - return result; - } - - - /// - /// 订阅主题 项目所有点位 - /// - /// - /// - /// - /// - public async Task> SubscribePointAll(long projectId, string clientId = "", bool isValueChanged = false) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - string dbRealDataResultStr = string.Empty; - try - { - if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "SubscribeMQTT:ApiUrl为空!"; - return result; - } - var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePointAll"; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromSeconds(15); - if (string.IsNullOrEmpty(clientId)) - { - clientId = _configuration["SubscribeMQTT:TopicName"]; - } - var body = JsonConvert.SerializeObject(new - { - ProjectId = projectId, - ClientId = clientId, - IsValueChanged = isValueChanged - }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - var httpResponse = await client.PostAsync(apiUrl, byteContent); - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - Console.WriteLine($"点位订阅:{dbRealDataResultStr}"); - result = JsonConvert.DeserializeObject>(dbRealDataResultStr); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePointAll", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); - } - return result; - } - - /// - /// 定时心跳 - /// - /// - /// - public async Task> SubscribePointHeartbeat(string clientId = "") - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - string dbRealDataResultStr = string.Empty; - try - { - if (string.IsNullOrEmpty(_configuration["SubscribeMQTT:ApiUrl"])) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "SubscribeMQTT:ApiUrl为空!"; - return result; - } - if (string.IsNullOrEmpty(clientId)) - { - clientId = _configuration["SubscribeMQTT:TopicName"]; - } - var apiUrl = _configuration["SubscribeMQTT:ApiUrl"] + "/api/Point/SubscribePointHeartbeat?clientId=" + clientId; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromSeconds(5); - var httpResponse = await client.GetAsync(apiUrl); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - } - result = JsonConvert.DeserializeObject>(dbRealDataResultStr); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("抛出了异常信息: {0}", ex.Message)).GetNlogMessage()); - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName + "-SubscribePoint", string.Format("点位订阅:{0}", dbRealDataResultStr)).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs deleted file mode 100644 index 7c1c1c6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/DataStream/TimeSeqService.cs +++ /dev/null @@ -1,607 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using MongoDB.Bson; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Newtonsoft.Json; -using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; -using WeiCloud.Entity.Models; -using WeiCloud.Utils.Mongo; - -namespace WeiCloud.Core.Services.DataStream -{ - public class TimeSeqService : ITimeSeqService - { - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly IHttpClientFactory _httpClientFactory; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IOptions> _changeTime; - public TimeSeqService(IHttpClientFactory httpClientFactory, IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration, IOptions> changeTime) - { - _logger = logger; - _configuration = configuration; - _httpClientFactory = httpClientFactory; - _serviceScopeFactory = serviceScopeFactory; - _changeTime = changeTime; - } - /// - /// 根据时间查询实时数据 - /// - /// - /// - /// - /// - /// - public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, long realDataId, bool isRepaired = false) - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - string dbRealDataResultStr = string.Empty; - try - { - var timeDBApiQueryUrl = _configuration["TimeDBApiQueryUrl"]; - //var timeDBApiUrl = _configuration["TimeDBApiUrl"]; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromMinutes(5); - var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, Id = realDataId, IsRepaired = isRepaired }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/data/QueryRealDataItem", byteContent); - var httpResponse = await client.PostAsync(timeDBApiQueryUrl, byteContent); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - } - result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};{1}", ex.Message, realDataId.ToString())).GetNlogMessage()); - } - return result; - } - - /// - /// 根据参数Id查询当前时刻值 - /// - /// - /// - /// - public async Task> QueryRealDataItemByRealIds(DateTime queryTime, List realDataIds) - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - string dbRealDataResultStr = string.Empty; - try - { - var timeDBApiQueryUrl = _configuration["TimeDBApiQueryByTimeRealIdsUrl"]; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromMinutes(3); - var body = JsonConvert.SerializeObject(new { time = queryTime, RealIds = realDataIds }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/data/QueryRealDataItem", byteContent); - var httpResponse = await client.PostAsync(timeDBApiQueryUrl, byteContent); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - } - result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - if (result != null && result.Data != null) - { - return result.Data; - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItemByRealIds", string.Format("抛出了异常信息: {0};{1}", ex.Message, realDataIds.ToString())).GetNlogMessage()); - } - return new List { }; - } - - public async Task> QueryEquipRealDataDoc(DateTime queryTime, long projectId, List equipIds) - { - var result = new List { }; - try - { - var startTime = queryTime.AddMinutes(-6); - //var startTime = queryTime.AddHours(-1); - var endTime = queryTime.AddMinutes(6); - using var scope = _serviceScopeFactory.CreateScope(); - var userCenterContext = scope.ServiceProvider.GetRequiredService(); - var projectInfo = userCenterContext.ProjectInfo.FirstOrDefault(t => t.Id == projectId); - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) - .Options; - using var _contextDB = new WeiCloudDBContext(contextOptions); - - var equipInfos = await _contextDB.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().Select(t => new - { - t.Id, - t.Eqtype - }).ToListAsync(); - var equipTypeIds = equipInfos.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - - var equipTypes = await userCenterContext.EquipmentType.Where(t => equipTypeIds.Contains(t.Id)).Select(t => new { t.Id, t.Tablename }).AsNoTracking().ToListAsync(); - var mongoUtil = scope.ServiceProvider.GetRequiredService(); - var db = mongoUtil.GetClient().GetDatabase("RealDataDB"); - - foreach (var equipType in equipTypes) - { - var collection = db.GetCollection(equipType.Tablename); - var _equipInfos = equipInfos.Where(t => t.Eqtype == equipType.Id); - if (_equipInfos.Count() == 0) - { - continue; - } - - var filter = Builders.Filter; - //filter.Gt("CreateTime", queryTime); - //filter.In("EquiId", _equipInfos.Select(t => t.Id).ToArray()); - var _equipIds = _equipInfos.Select(t => t.Id).ToArray(); - //_equipIds = new long[] { 495360044170798 }; - //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).ToListAsync(); - var sort = Builders.Sort; - var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")).ToListAsync(); - //var docs = collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")); - - foreach (var doc in docs) - { - var equipIdDoc = doc.GetValue("EquipId"); - try - { - long equipId = equipIdDoc.ToLong(); - //if (!long.TryParse(equipIdDoc.AsString, out equipId)) - //{ - // continue; - //} - //if (!result.Any(t => t.EquipId == equipIdDoc.AsInt64)) - if (!result.Any(t => t.EquipId == equipId)) - { - try - { - var createTimeDoc = doc.GetValue("CreateTime"); - var updateTimeDoc = doc.GetValue("UpdateTime"); - var docParams = doc.Where(t => t.Name != "_id" - && t.Name != "CreateTime" - && t.Name != "EquipId" - && t.Name != "CreateTime" - && t.Name != "UpdateTime").ToList(); - var item = new EquipParamRealDataModel - { - EquipId = equipId, - CreateTime = createTimeDoc.ToLocalTime(), - UpdateTime = updateTimeDoc.ToLocalTime(), - Params = new Dictionary { } - //Params = doc.Where(t => t.Name != "_id" && t.Name != "CreateTime" && t.Name != "EquipId" && t.Name != "CreateTime" && t.Name != "UpdateTime").ToDictionary(t => t.Name, t => t.Value.AsNullableDouble) - }; - foreach (var docParam in docParams) - { - if (docParam.Value.IsDouble) - { - item.Params[docParam.Name] = docParam.Value.ToDouble(); - } - else if (docParam.Value.IsInt32) - { - item.Params[docParam.Name] = docParam.Value.AsInt32; - } - else if (docParam.Value.IsInt64) - { - item.Params[docParam.Name] = docParam.Value.AsInt64; - } - else if (docParam.Value.IsDecimal128) - { - item.Params[docParam.Name] = (double)docParam.Value.ToDecimal(); - } - } - - result.Add(item); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData-Doc1", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData-Doc2", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData", string.Format("抛出了异常信息: {0};{1}", ex.Message, equipIds.Join(","))).GetNlogMessage()); - } - return result; - } - - public async Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds) - { - var result = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var userCenterContext = scope.ServiceProvider.GetRequiredService(); - var projectInfo = userCenterContext.ProjectInfo.FirstOrDefault(t => t.Id == projectId); - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))) - .Options; - using var _contextDB = new WeiCloudDBContext(contextOptions); - - var equipInfos = await _contextDB.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().Select(t => new - { - t.Id, - t.Eqtype - }).ToListAsync(); - var equipTypeIds = equipInfos.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - - var equipTypes = await userCenterContext.EquipmentType.Where(t => equipTypeIds.Contains(t.Id)).Select(t => new { t.Id, t.Tablename }).AsNoTracking().ToListAsync(); - var mongoUtil = scope.ServiceProvider.GetRequiredService(); - var db = mongoUtil.GetClient().GetDatabase("RealDataDB"); - - foreach (var equipType in equipTypes) - { - var collection = db.GetCollection(equipType.Tablename); - var _equipInfos = equipInfos.Where(t => t.Eqtype == equipType.Id); - if (_equipInfos.Count() == 0) - { - continue; - } - - var filter = Builders.Filter; - //filter.Gt("CreateTime", queryTime); - //filter.In("EquiId", _equipInfos.Select(t => t.Id).ToArray()); - var _equipIds = _equipInfos.Select(t => t.Id).ToArray(); - //_equipIds = new long[] { 495360044170798 }; - //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).ToListAsync(); - var sort = Builders.Sort; - //var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Descending("CreateTime")).ToListAsync(); - var docs = await collection.Find(filter.Gt("CreateTime", startTime) & filter.Lt("CreateTime", endTime) & filter.In("EquipId", _equipIds)).Sort(sort.Ascending("CreateTime")).ToListAsync(); - - foreach (var doc in docs) - { - var equipIdDoc = doc.GetValue("EquipId"); - - var item = result.FirstOrDefault(t => t.EquipId == equipIdDoc.AsInt64); - if (item == null) - { - item = new EquipIntervalParamRealDataModel { EquipId = equipIdDoc.AsInt64, Items = new List { } }; - result.Add(item); - } - var itemDic = doc.Where(t => t.Name != "_id" && t.Name != "CreateTime" && t.Name != "EquipId" && t.Name != "CreateTime" && t.Name != "UpdateTime").ToDictionary(t => t.Name, t => t.Value.AsNullableDouble); - var createTimeDoc = doc.GetValue("CreateTime"); - var updateTimeDoc = doc.GetValue("UpdateTime"); - item.Items.Add(new EquipRangeParamRealDataItemModel - { - EquipId = equipIdDoc.AsInt64, - CreateTime = createTimeDoc.ToLocalTime(), - UpdateTime = updateTimeDoc.ToLocalTime(), - Params = itemDic - }); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryEquipRealData", string.Format("抛出了异常信息: {0};{1}", ex.Message, equipIds.Join(","))).GetNlogMessage()); - } - return result; - } - public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, List realDataIds, bool isMore = false) - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - string dbRealDataResultStr = string.Empty; - try - { - var timeDBApiUrl = _configuration["TimeDBApiUrl"]; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromMinutes(3); - var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds, IsMore = isMore }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - } - result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - /// - /// 获取区间值,缺值默认 - /// - /// - /// - /// - /// - /// - /// - /// - public async Task>> QueryRealDataItem(DateTime startTime, DateTime endTime, short intervalUnit, int interval, List realDataIds, short complementType = 1) - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - string dbRealDataResultStr = string.Empty; - try - { - var times = new List { }; - var _startTime = startTime; - while (_startTime < endTime) - { - times.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddSeconds(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddMinutes(interval); - } - } - var timeDBApiUrl = _configuration["TimeDBApiUrl"]; - ApiResult> resultDataStream = new ApiResult>(); - //要替换日期的历史数据 2023-12-15 - var test = _changeTime.Value; - - //var ds = _configuration["SpecialHistoricalCurveDate1:SearchDate"]; - - //var dse = _configuration["SpecialHistoricalCurveDate1:ActualityDate"]; - var specialHistoricalCon = _configuration.GetSection("SpecialHistoricalCurveDate").Get(); - //var changeTimesP = JsonConvert.DeserializeObject >(_configuration["SpecialHistoricalCurveDate"]); - var changeTimes = new List(); - if (specialHistoricalCon != null && specialHistoricalCon.Length > 0) - { - foreach (var e in specialHistoricalCon) - { - changeTimes.Add(new SpecialHistoricalCurveDate { SearchDate = e.SearchDate, ActualityDate = e.ActualityDate }); - } - } - List dates = new List(); - List dateTimeNew = new List();//重组后的时间段 - if (changeTimes != null && changeTimes.Count > 0) - { - var dateStart = startTime.Date; - var dateEnd = endTime.Date; - bool isNeedChange = false;//是否需要替换某个日期的历史数据 - //dates.Add(dateStart); - var t = dateStart; - while (t <= dateEnd) - { - dates.Add(t); - t = t.AddDays(1); - } - foreach (var d in changeTimes) - { - DateTime sDate = Convert.ToDateTime(d.SearchDate); - DateTime aDate = Convert.ToDateTime(d.ActualityDate); - if (sDate >= dateStart && sDate <= dateEnd) - { - isNeedChange = true; - dates.Add(aDate.Date); - dates.Remove(sDate.Date); - } - } - if (!isNeedChange)//没有要替换日期的数据 - { - resultDataStream = await GetRealHistory(realDataIds, timeDBApiUrl, startTime, endTime); - } - else//有要替换日期的数据 - { - dates = dates.Distinct().OrderBy(d => d).ToList(); - int j = 0; - for (int i = 0; i < dates.Count; i++) - { - - if (i == 0) - { continue; } - if (i != 0 && dates[i] == dates[i - 1].AddDays(1)) - { - if (i == dates.Count - 1) - { - DateItem tie = new DateItem(); - tie.Start = dates[j]; - tie.End = dates[i].AddHours(23).AddMinutes(59).AddSeconds(59); - dateTimeNew.Add(tie); - } - continue; - } - DateItem tiem = new DateItem(); - tiem.Start = dates[j]; - tiem.End = dates[i - 1].AddHours(23).AddMinutes(59).AddSeconds(59); - dateTimeNew.Add(tiem); - j = i; - if (i == dates.Count - 1) - { - DateItem tim = new DateItem(); - tim.Start = dates[i]; - tim.End = dates[i].AddHours(23).AddMinutes(59).AddSeconds(59); - dateTimeNew.Add(tim); - } - } - if (dateTimeNew == null || dateTimeNew.Count == 0)//说明都连续没有断 - { - DateItem tiem = new DateItem(); - tiem.Start = dates.First(); - tiem.End = dates.Last(); - dateTimeNew.Add(tiem); - } - dateTimeNew.FirstOrDefault().Start = dateTimeNew.FirstOrDefault().Start.AddHours(startTime.Hour).AddMinutes(startTime.Minute).AddSeconds(startTime.Second); - dateTimeNew.LastOrDefault().End = dateTimeNew.LastOrDefault().End.Date.AddHours(endTime.Hour).AddMinutes(endTime.Minute).AddSeconds(endTime.Second); - List list = new List();//不同时间段的数据集合 - List list1 = new List();//不同时间段的数据集合 - foreach (var s in dateTimeNew) - { - //var client = _httpClientFactory.CreateClient(); - //client.Timeout = TimeSpan.FromMinutes(3); - //var body = JsonConvert.SerializeObject(new { StartTime = s.Start, EndTime = s.End != DateTime.MinValue ? s.End : DateTime.Now, RealIds = realDataIds }); - //var buffer = Encoding.UTF8.GetBytes(body); - //var byteContent = new ByteArrayContent(buffer); - //byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); - //if (httpResponse.StatusCode == HttpStatusCode.OK) - //{ - // dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - //} - //var resultDataStream1 = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - var resultDataStream1 = await GetRealHistory(realDataIds, timeDBApiUrl, s.Start, s.End); - var data = resultDataStream1.Data; - if (data == null || data.Count == 0) - { continue; } - var tt = s.Start.Date; - while (tt <= s.End.Date) - { - foreach (var g in changeTimes) - { - DateTime sDate = Convert.ToDateTime(g.SearchDate).Date; - DateTime aDate = Convert.ToDateTime(g.ActualityDate).Date; - if (tt != aDate)//找到要替换的数据 - { - continue; - } - foreach (var l in data) - { - if (l.Items == null || l.Items.Count == 0) - { continue; } - var cData = l.Items.Where(d => d.Time.Date == aDate).ToList(); - if (cData == null || cData.Count == 0) - { continue; } - var ccdata = cData.Select(d => new EquipParamHistoryItemModel { Value = d.Value, Time = sDate.AddHours(d.Time.Hour).AddMinutes(d.Time.Minute).AddSeconds(d.Time.Second) }).ToList(); - l.Items = l.Items.Where(d => d.Time.Date != aDate).ToList(); - l.Items = l.Items.Union(ccdata).ToList(); - } - } - tt = tt.AddDays(1); - } - list = list.Union(data).ToList(); - } - if (list != null && list.Count > 0) - { - var saData = list.Select(d => d.Id).Distinct().ToList(); - foreach (var s in saData) - { - EquipParamHistoryModel nn = new EquipParamHistoryModel(); - List ll = new List(); - nn.Id = s; - var llItem = list.Where(d => d.Id == s).ToList(); - foreach (var te in llItem) - { - ll = ll.Union(te.Items).ToList(); - } - nn.Items = ll.Distinct().ToList(); - list1.Add(nn); - } - } - resultDataStream.Data = list1; - } - } - else//原来逻辑 - { - //var client = _httpClientFactory.CreateClient(); - //client.Timeout = TimeSpan.FromMinutes(3); - //var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime =endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds }); - //var buffer = Encoding.UTF8.GetBytes(body); - //var byteContent = new ByteArrayContent(buffer); - //byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - //var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); - //if (httpResponse.StatusCode == HttpStatusCode.OK) - //{ - // dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - //} - //resultDataStream = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - resultDataStream = await GetRealHistory(realDataIds, timeDBApiUrl, startTime, endTime); - } - if (resultDataStream != null && resultDataStream.Data.Count() > 0) - { - foreach (var point in resultDataStream.Data) - { - if (point.Items == null || point.Items.Count() == 0) - { - continue; - } - var items = new List { }; - foreach (var time in times) - { - var sTime = time.AddMinutes(-1); - var pointItem = point.Items.LastOrDefault(t => t.Time > sTime && t.Time <= time);//取最近值 - - EquipParamHistoryItemModel _pointItem = new EquipParamHistoryItemModel { Time = time }; - if (pointItem != null) - { - _pointItem.Value = pointItem.Value; - } - else - { - pointItem = point.Items.FirstOrDefault(t => t.Time > time && t.Time <= time.AddMinutes(1));//取后面个值 - if (pointItem != null) - { - _pointItem.Value = pointItem.Value; - } - } - if (_pointItem != null) - { - if (_pointItem.Value != null) - { - _pointItem.Value = Math.Round(_pointItem.Value.GetValueOrDefault(), 2); - } - items.Add(_pointItem); - } - } - result.Data.Add(new EquipParamHistoryModel - { - Id = point.Id, - Items = items - }); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "-QueryRealDataItem", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - private async Task>> GetRealHistory(List realDataIds, string timeDBApiUrl, DateTime startTime, DateTime endTime) - { - string dbRealDataResultStr = string.Empty; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromMinutes(3); - var body = JsonConvert.SerializeObject(new { StartTime = startTime, EndTime = endTime != DateTime.MinValue ? endTime : DateTime.Now, RealIds = realDataIds }); - var buffer = Encoding.UTF8.GetBytes(body); - var byteContent = new ByteArrayContent(buffer); - byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - var httpResponse = await client.PostAsync(timeDBApiUrl + "/api/datav03/QueryRealDataItemByRealIds", byteContent); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - dbRealDataResultStr = await httpResponse.Content.ReadAsStringAsync(); - } - var result = JsonConvert.DeserializeObject>>(dbRealDataResultStr); - return result; - } - - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs deleted file mode 100644 index e997c27..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EnergySaveDwService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.Context.AirDB; - -namespace WeiCloud.Core.Services -{ - public class EnergySaveDwCoreService : IEnergySaveDwCoreService - { - private readonly WeiCloudAirDBContext _context; - private readonly ILogger _logger; - - public EnergySaveDwCoreService(WeiCloudAirDBContext context, ILogger logger) - { - _context = context; - _logger = logger; - } - - public async Task GetProEneSaveDWNow(long? project, DateTime dateTime) - { - DateTime now = DateTimeTools.GetSysDateTimeNow(); - DateTime yearfristday = DateTimeTools.GetYearFirstDay(); - try - { - var data = await _context.TbEnergySaveDw.Where(m => m.Parm002 == project).ToListAsync(); - //parm002 :项目id parm003:存储时间 - var result = (from m in data - where m.Parm002 == project && m.Parm003 >= yearfristday && m.Parm003 <= now - group m by m.Parm004 into g - select new - { - //003累计节能 - sum = (g.Max(a => a.ProParm003) - g.Min(a => a.ProParm003)) - }).Sum(a => a.sum); - return result.ToDouble(); - - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProEneSaveDWNow ", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - return await Task.FromResult(-1); - } - - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs deleted file mode 100644 index 66e4f56..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipInfoCoreService.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; - -namespace WeiCloud.Core.Services -{ - public class EquipInfoCoreService : IEquipInfoCoreService - { - private readonly WeiCloudDBContext _context; - private readonly ILogger _logger; - public EquipInfoCoreService(WeiCloudDBContext context, ILogger logger) - { - _context = context; - _logger = logger; - } - /// - /// 查询设备信息 - /// - /// - /// - public async Task> GetEquipmentInfos(long projectId) - { - var equipmentInfos = await _context.EquipmentInfo.Where(t => t.Projectid == projectId && t.State == 1).AsNoTracking().ToListAsync(); - return equipmentInfos; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs deleted file mode 100644 index 558056e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/EquipPartCoreService.cs +++ /dev/null @@ -1,207 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common.EquipPart; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.EquipPart; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core.Services.EquipPart -{ - public class EquipPartCoreService : IEquipPartCoreService - { - private readonly ILogger _logger; - private readonly WeiCloudDBContext _dbContext; - private readonly WeiCloudDBUserCenterContext _dbUserCenterContext; - public EquipPartCoreService(ILogger logger, WeiCloudDBContext dbContext, WeiCloudDBUserCenterContext dbUserCenterContext) - { - _logger = logger; - _dbContext = dbContext; - _dbUserCenterContext = dbUserCenterContext; - } - /// - /// 消息通知,更新审批状态(对工作流) - /// - /// - /// - public async Task> ApproveItem(ApproveItemModel input) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = true }; - try - { - if (input.Status != (short)EquipPartApproveState.Applied - && input.Status != (short)EquipPartApproveState.Approved - && input.Status != (short)EquipPartApproveState.Refuse - && input.Status != (short)EquipPartApproveState.Completed) - {//其他不用处理 - _logger.LogWarning(new NlogMessageHelper("ApproveItem", "").GetNlogMessage().ToString()); - return result; - } - if (input.OrderId <= 0 || input.ApproverUserId <= 0) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "OrderId必填"; - return result; - } - var equipPartApply = _dbContext.EtEquipPartApply.FirstOrDefault(t => t.Id == input.ApplyId && t.OrderId == input.OrderId); - if (equipPartApply == null) - { - result.Code = RequestBackStatuEnum.notexist.Value; - result.Msg = "申请单不存在"; - return result; - } - var approverUser = _dbUserCenterContext.Users.FirstOrDefault(t => t.Id == input.ApproverUserId); - - using var dbContextTrans = _dbContext.Database.BeginTransaction(); - try - { - var lastEtEquipPartApplyState = _dbContext.EtEquipPartApplyState.OrderByDescending(t => t.CreateTime).AsNoTracking().FirstOrDefault(t => t.EquipPartApplyId == equipPartApply.Id); - if (lastEtEquipPartApplyState != null) - { - if (lastEtEquipPartApplyState.Status == (short)EquipPartApproveState.Completed - || lastEtEquipPartApplyState.Status == (short)EquipPartApproveState.Refuse) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "申请单已经审批完成!不需要处理"; - return result; - } - } - var approverName = ""; - if (input.Status != (short)EquipPartApproveState.Applied) - { - approverName = approverUser == null ? "" : approverUser?.Userfullname; - } - _dbContext.EtEquipPartApplyState.Add(new EtEquipPartApplyState - { - Id = UidGenerator.Uid(), - EquipPartApplyId = equipPartApply.Id, - Status = input.Status, - ApproverId = input.ApproverUserId, - ApproverName = approverName, - CreateTime = DateTime.Now - }); - if (input.Status == (short)EquipPartApproveState.Completed || input.Status == (short)EquipPartApproveState.Refuse) - {//已完成或者拒绝 - var equipPartApplyDetails = await _dbContext.EtEquipPartApplyDetail.Where(t => t.EquipPartApplyId == equipPartApply.Id).ToListAsync(); - var warehouseIds = equipPartApplyDetails.Select(t => t.WarehouseId).Distinct().ToList(); - var equipPartIds = equipPartApplyDetails.Select(t => t.EquipPartId).Distinct().ToList(); - - var equipPartStocks = _dbContext.EtEquipPartStock.Where(t => warehouseIds.Contains(t.WarehouseId) && equipPartIds.Contains(t.EquipPartId) && t.IsDeleted == false).ToList(); - _logger.LogWarning(new NlogMessageHelper("ApproveItem原始", message: $"{JsonConvert.SerializeObject(equipPartStocks)}").GetNlogMessage().ToString()); - - if (equipPartApply.Type == (short)EquipPartApplyEnum.In && input.Status == (short)EquipPartApproveState.Completed) - {//入库,通过,加库存 - foreach (var equipPartApplyDetail in equipPartApplyDetails) - { - var equipPartStock = equipPartStocks.FirstOrDefault(t => t.WarehouseId == equipPartApplyDetail.WarehouseId && t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); - if (equipPartStock == null) - { - equipPartStock = new EtEquipPartStock - { - Id = UidGenerator.Uid(), - WarehouseId = equipPartApplyDetail.WarehouseId, - EquipPartId = equipPartApplyDetail.EquipPartId, - Brand = equipPartApplyDetail.Brand, - Batch = equipPartApplyDetail.Batch, - BrandModel = equipPartApplyDetail.BrandModel, - CreateTime = DateTime.Now, - Creator = equipPartApply.ApplyUserId - }; - _dbContext.EtEquipPartStock.Add(equipPartStock); - } - else - { - _dbContext.Entry(equipPartStock).State = EntityState.Modified; - _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; - } - _logger.LogWarning(new NlogMessageHelper("ApproveItem入库", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); - equipPartStock.Quantity += equipPartApplyDetail.Quantity; - equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; - equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; - } - } - else if (equipPartApply.Type == (short)EquipPartApplyEnum.Out && input.Status == (short)EquipPartApproveState.Refuse) - {//出库,拒绝,归还库存 - foreach (var equipPartApplyDetail in equipPartApplyDetails) - { - var equipPartStock = equipPartStocks.FirstOrDefault(t => t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); - if (equipPartStock == null) - { - continue; - } - else - { - _dbContext.Entry(equipPartStock).State = EntityState.Modified; - _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; - } - _logger.LogWarning(new NlogMessageHelper("ApproveItem出库", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); - equipPartStock.Quantity += equipPartApplyDetail.Quantity; - equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; - equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; - } - } - else if (equipPartApply.Type == (short)EquipPartApplyEnum.LentOut) - {//外借,拒绝或者完成,结果都是归还数量 - foreach (var equipPartApplyDetail in equipPartApplyDetails) - { - var equipPartStock = equipPartStocks.FirstOrDefault(t => t.WarehouseId == equipPartApplyDetail.WarehouseId && t.EquipPartId == equipPartApplyDetail.EquipPartId - && t.Batch == equipPartApplyDetail.Batch && t.Brand == equipPartApplyDetail.Brand && t.BrandModel == equipPartApplyDetail.BrandModel); - if (equipPartStock == null) - { - continue; - } - - _dbContext.Entry(equipPartStock).State = EntityState.Modified; - _dbContext.Entry(equipPartStock).Property(t => t.Quantity).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UnitPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.TotalPrice).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.Updater).IsModified = true; - _dbContext.Entry(equipPartStock).Property(t => t.UpdateTime).IsModified = true; - - _logger.LogWarning(new NlogMessageHelper("ApproveItem外借", message: $"原有数量:{equipPartStock.Quantity}:归还数量:{equipPartApplyDetail.Quantity}---{JsonConvert.SerializeObject(equipPartStock)}").GetNlogMessage().ToString()); - equipPartStock.Quantity = equipPartStock.Quantity + equipPartApplyDetail.Quantity; - _logger.LogWarning(new NlogMessageHelper("ApproveItem外借", message: $"现有有数量:{equipPartStock.Quantity}").GetNlogMessage().ToString()); - equipPartStock.UnitPrice = equipPartApplyDetail.UnitPrice; - equipPartStock.TotalPrice = equipPartApplyDetail.TotalPrice; - } - } - } - _dbContext.SaveChanges(); - dbContextTrans.Commit(); - } - catch (Exception ex) - { - dbContextTrans.Rollback(); - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper("ApproveItem", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper("ApproveItem", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - finally - { - _logger.LogWarning(new NlogMessageHelper("ApproveItem", message: JsonConvert.SerializeObject(input)).GetNlogMessage().ToString()); - } - return result; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs deleted file mode 100644 index bba7530..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipPart/IEquipPartCoreService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.EquipPart; - -namespace WeiCloud.Core.Services.EquipPart -{ - public interface IEquipPartCoreService - { - Task> ApproveItem(ApproveItemModel input); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs deleted file mode 100644 index ce92b9a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/EquipStatisticsService.cs +++ /dev/null @@ -1,1961 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using NewLife.Log; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Core.Calculation; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.SystemDiagnosis; -using WeiCloud.Utils; - -namespace WeiCloud.Core.EquipStatistics -{ - public class EquipStatisticsService : IEquipStatisticsService - { - private readonly ILogger _logger; - private readonly IDictionaryService _dictionaryService; - private readonly WeiCloudDBUserCenterContext _userCenterContext; - public EquipStatisticsService(ILogger logger, IDictionaryService dictionaryService, WeiCloudDBUserCenterContext userCenterContext) - { - _logger = logger; - _dictionaryService = dictionaryService; - _userCenterContext = userCenterContext; - } - /// - /// 能效计算 - /// - /// - /// 有效设备 - /// 全部设备 - /// - /// - /// - /// - /// - public async Task> GetEquipEfficiencyV04(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) - { - var result = new List { }; - try - { - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - //var time1 = timeList[i].AddMinutes(-3); - var time1 = timeList[i]; - //var time2 = timeList[i + 1]; - var time2 = time1.AddSeconds(10); - - - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - var _ammeterHistorys = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - //AmParm027 = t.Max(m => m.AmParm027) - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) - { - //ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); - ammeterConsum = _ammeterHistorys.Sum(t => t.Value); - } - - //瞬时流量 - //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new - var _gasMeterHistorys = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - //AmParm027 = t.Max(m => m.AmParm027) - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) - { - //gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); - gasMeterConsum = _gasMeterHistorys.Sum(t => t.Value); - } - - //var _heatMeterHistorys11 = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).ToList(); - //瞬时热流量 - /* - * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 - */ - //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new - var _heatMeterHistorys = heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - //AmParm027 = t.Max(m => m.AmParm027) - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) - { - //heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); - heatMeterConsum = _heatMeterHistorys.Sum(t => t.Value); - } - - double r = 0; - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - - public async Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) - { - var result = new List { }; - try - { - var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); - - ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - - var mainEquipmentTypes = equipmentTypes.Where(t => t.Typecode == EquipTypeEnum.DirectFiredUnitCode - || t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode - || t.Typecode == EquipTypeEnum.FCCCode - || t.Typecode == EquipTypeEnum.CoolingTower).ToList(); - - var mainEquipmentTypeIds = mainEquipmentTypes.Select(t => t.Id).Distinct().ToList(); - - var mainEquipmentInfos = equipmentInfos.Where(t => t.Eqtype != null && mainEquipmentTypeIds.Contains((long)t.Eqtype)).ToList(); - var mainEquipmentInfoIds = mainEquipmentInfos.Select(t => t.Id).Distinct().ToList(); - - - var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - - bool isSys = false; - if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) - && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) - { - isSys = true; - } - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - //var time1 = timeList[i].AddMinutes(-3); - var time1 = timeList[i]; - //var time2 = timeList[i + 1]; - var time2 = time1.AddSeconds(10); - - if (!isSys && equipmentRunningTimesHistorysCloseds != null && equipmentRunningTimesHistorysCloseds.Count() > 0) - { - var _equipmentRunningTimesHistorysCloseds = equipmentRunningTimesHistorysCloseds.Where(t => mainEquipmentInfoIds.Contains(t.EquipId) && ((time1 >= t.StartTime && time1 <= t.EndTime) || (time2 >= t.StartTime && time2 < t.EndTime))).ToList(); - foreach (var _equipmentRunningTimesHistorysClosed in _equipmentRunningTimesHistorysCloseds) - { - ammeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - gasMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - heatMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - waterMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - } - } - - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.AmParm027 == null || (t.AmParm027 >= 0 && t.AmParm027 <= 50))).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //AmParm027 = t.Max(m => m.AmParm027) - //AmParm027 = t.LastOrDefault()?.AmParm027 - AmParm027 = t.FirstOrDefault()?.AmParm027 - }).ToList(); - if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) - { - //ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); - ammeterConsum = _ammeterHistorys.Average(t => t.AmParm027 ?? 0); - } - - //瞬时流量 - //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new - var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.GmParm001 == null || t.GmParm001 >= 0)).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //Parm002 = t.Max(m => m.Parm002) - //GmParm001 = t.LastOrDefault()?.GmParm001 - GmParm001 = t.FirstOrDefault()?.GmParm001 - }).ToList(); - if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) - { - //gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); - gasMeterConsum = _gasMeterHistorys.Average(t => t.GmParm001 ?? 0); - } - - //var _heatMeterHistorys11 = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).ToList(); - //瞬时热流量 - /* - * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 - */ - //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm001 >= time1 && t.Parm001 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new - var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && (t.HmParm001 == null || (t.HmParm001 >= 0 && t.HmParm001 <= 3000))).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //HmParm001 = t.Max(m => m.HmParm001) - //HmParm001 = t.LastOrDefault()?.HmParm001 - HmParm001 = t.FirstOrDefault()?.HmParm001 - }).ToList(); - if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) - { - //heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); - heatMeterConsum = _heatMeterHistorys.Average(t => t.HmParm001 ?? 0); - } - - double r = 0; - if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) - && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) - { - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) - { - r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) - { - r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); - } - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - public async Task> GetEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys) - { - var result = new List { }; - try - { - var timeList = new List { }; - var _startTime = startTime; - while (_startTime <= endTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - else if (intervalUnit == 4) - { - _startTime = _startTime.AddMonths((int)interval); - } - else - { - break; - } - } - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - var time1 = timeList[i]; - var time2 = timeList[i + 1]; - - - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - if (ammeterHistorys.Count() > 0) - { - ammeterConsum = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - }).Average(t => t.Value); - //ammeterConsum = ammeterHistorys.Last().Value.GetValueOrDefault() - ammeterHistorys.First().Value.GetValueOrDefault(); - } - if (gasMeterHistorys.Count() > 0) - { - //gasMeterConsum = gasMeterHistorys.Last().Value.GetValueOrDefault() - gasMeterHistorys.First().Value.GetValueOrDefault(); - gasMeterConsum = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - }).Average(t => t.Value); - } - - if (heatMeterHistorys.Count() > 0) - { - //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); - heatMeterConsum += heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - }).Average(t => t.Value); - } - //if (coolMeterHistorys.Count() > 0) - //{ - // //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); - // heatMeterConsum += coolMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2 && t.Value > 0).GroupBy(t => t.Id).Select(t => new - // { - // Id = t.Key, - // Value = t.Last().Value.GetValueOrDefault() - // }).Average(t => t.Value); - //} - - - double r = 0; - if (label == "系统") - { - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (label == "主机") - { - r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (label == "泵" || label == "塔") - { - r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); - } - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - public async Task> GetEnergyEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List coolMeterHistorys) - { - var result = new List { }; - try - { - var timeList = new List { }; - var _startTime = startTime; - while (_startTime <= endTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - else if (intervalUnit == 4) - { - _startTime = _startTime.AddMonths((int)interval); - } - else - { - break; - } - } - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - var time1 = timeList[i]; - var time2 = timeList[i + 1]; - - - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - if (ammeterHistorys.Count() > 0) - { - ammeterConsum = ammeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() - }).Sum(t => t.Value); - //ammeterConsum = ammeterHistorys.Last().Value.GetValueOrDefault() - ammeterHistorys.First().Value.GetValueOrDefault(); - } - if (gasMeterHistorys.Count() > 0) - { - //gasMeterConsum = gasMeterHistorys.Last().Value.GetValueOrDefault() - gasMeterHistorys.First().Value.GetValueOrDefault(); - gasMeterConsum = gasMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() - }).Sum(t => t.Value); - } - - if (heatMeterHistorys.Count() > 0) - { - //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); - heatMeterConsum += heatMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() - }).Sum(t => t.Value); - } - if (coolMeterHistorys.Count() > 0) - { - //heatMeterConsum += heatMeterHistorys.Last().Value.GetValueOrDefault() - heatMeterHistorys.First().Value.GetValueOrDefault(); - heatMeterConsum += coolMeterHistorys.Where(t => t.CreateTime >= time1 && t.CreateTime < time2).GroupBy(t => t.Id).Select(t => new - { - Id = t.Key, - Value = t.Last().Value.GetValueOrDefault() - t.First().Value.GetValueOrDefault() - }).Sum(t => t.Value); - } - - - double r = 0; - if (label == "系统") - { - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (label == "主机") - { - r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (label == "泵" || label == "塔") - { - r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); - } - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - - /// - /// 根据累计值计算能效 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> GetEquipEfficiencyByCumulative(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null) - { - var result = new List { }; - try - { - var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); - - ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - - var mainEquipmentTypes = equipmentTypes.Where(t => t.Typecode == EquipTypeEnum.DirectFiredUnitCode - || t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode - || t.Typecode == EquipTypeEnum.FCCCode - || t.Typecode == EquipTypeEnum.CoolingTower).ToList(); - - var mainEquipmentTypeIds = mainEquipmentTypes.Select(t => t.Id).Distinct().ToList(); - - var mainEquipmentInfos = equipmentInfos.Where(t => t.Eqtype != null && mainEquipmentTypeIds.Contains((long)t.Eqtype)).ToList(); - var mainEquipmentInfoIds = mainEquipmentInfos.Select(t => t.Id).Distinct().ToList(); - - - var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - var time1 = timeList[i].AddMinutes(-3); - var time2 = timeList[i + 1]; - - if (equipmentRunningTimesHistorysCloseds != null && equipmentRunningTimesHistorysCloseds.Count() > 0) - { - var _equipmentRunningTimesHistorysCloseds = equipmentRunningTimesHistorysCloseds.Where(t => mainEquipmentInfoIds.Contains(t.EquipId) && ((time1 >= t.StartTime && time1 <= t.EndTime) || (time2 >= t.StartTime && time2 <= t.EndTime))).ToList(); - foreach (var _equipmentRunningTimesHistorysClosed in _equipmentRunningTimesHistorysCloseds) - { - ammeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - gasMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - heatMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - waterMeterHistorys.RemoveAll(t => equipIds.Contains((long)t.Parm002) && t.Parm003 >= _equipmentRunningTimesHistorysClosed.StartTime && t.Parm003 <= _equipmentRunningTimesHistorysClosed.EndTime); - } - } - - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0 && t.AmParm027 <= 50).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - MinAmParm029 = t.Min(m => m.AmParm029 ?? 0), - MaxAmParm029 = t.Max(m => m.AmParm029 ?? 0) - }).ToList(); - if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) - { - ammeterConsum = (double)_ammeterHistorys.Sum(t => t.MaxAmParm029 - t.MinAmParm029); - } - - //瞬时流量 - var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - MaxGmParm001 = t.Max(m => m.GmParm001 ?? 0), - MinGmParm001 = t.Min(m => m.GmParm001 ?? 0) - }).ToList(); - if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) - { - gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.MaxGmParm001 - t.MinGmParm001); - } - - - //瞬时热流量 - /* - * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 - */ - var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - MaxHmParm001 = t.Max(m => m.HmParm002 ?? 0), - MinHmParm001 = t.Min(m => m.HmParm002 ?? 0) - }).ToList(); - if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) - { - heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.MaxHmParm001 - t.MinHmParm001); - } - - double r = 0; - if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) - && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) - { - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) - { - r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) - { - r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); - } - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - - /// - /// 能效计算 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// 间隔单位1-分,2-时,3-日,4-月 - /// - public async Task> GetEquipEfficiency(DateTime startTime, DateTime endTime, List equipmentInfos, List equipmentInfoAlls - , List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys - , List heatMeterHistorys, double interval, int intervalUnit) - { - var result = new List { }; - try - { - var equipIds = equipmentInfos.Select(t => t.Id).Distinct().ToList(); - - ammeterHistorys = ammeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - waterMeterHistorys = waterMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - gasMeterHistorys = gasMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - heatMeterHistorys = heatMeterHistorys.Where(t => equipIds.Contains((long)t.Parm002)).OrderBy(t => t.Parm003).ToList(); - - - var equipTypeIds = equipmentInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var timeList = new List { }; - var _startTime = startTime; - while (_startTime <= endTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - else if (intervalUnit == 4) - { - _startTime = _startTime.AddMonths((int)interval); - } - else - { - break; - } - } - for (var i = 0; i < timeList.Count(); i++) - { - if (i + 1 >= timeList.Count()) - { - break; - } - if (timeList[i] >= DateTime.Now) - { - break; - } - var time1 = timeList[i].AddMinutes(-3); - var time2 = timeList[i + 1]; - double ammeterConsum = 0; - double gasMeterConsum = 0; - double heatMeterConsum = 0; - - //总功率(瞬时) - /* - * (2)水泵、冷却塔、主机电表总功率突变为0(运行状态为开启时),总功率取上个时刻值;总功率突变超过50kW,取上个时刻值。 - */ - - - //var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0 && t.AmParm027 <= 50).GroupBy(t => new - var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.AmParm027 != null && t.AmParm027 > 0).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //AmParm027 = t.Max(m => m.AmParm027) - AmParm027 = t.LastOrDefault()?.AmParm027 - }).ToList(); - if (_ammeterHistorys != null && _ammeterHistorys.Count() > 0) - { - ammeterConsum = (double)_ammeterHistorys.Sum(t => t.AmParm027); - } - - //瞬时流量 - var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.GmParm001 != null && t.GmParm001 > 0).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //Parm002 = t.Max(m => m.Parm002) - GmParm001 = t.LastOrDefault()?.GmParm001 - }).ToList(); - if (_gasMeterHistorys != null && _gasMeterHistorys.Count() > 0) - { - gasMeterConsum = (double)_gasMeterHistorys.Sum(t => t.GmParm001); - } - - - //瞬时热流量 - /* - * (1)热量表瞬时流量突降为0(水泵运行状态只要有一个为开启时),热量取上个时刻值;热量表瞬时热流量超过3000kW,取上个时刻值。 - */ - var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && equipIds.Contains((long)t.Parm002) && t.Parm003 >= time1 && t.Parm003 < time2 && t.HmParm001 != null && t.HmParm001 > 0 && t.HmParm001 <= 3000).GroupBy(t => new - { - EquipId = t.Parm002 ?? 0 - }).Select(t => new - { - EquipId = t.Key.EquipId, - //HmParm001 = t.Max(m => m.HmParm001) - HmParm001 = t.LastOrDefault()?.HmParm001 - }).ToList(); - if (_heatMeterHistorys != null && _heatMeterHistorys.Count() > 0) - { - heatMeterConsum = (double)_heatMeterHistorys.Sum(t => t.HmParm001); - } - - double r = 0; - if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode) - && equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode))) - { - r = EngeryCalculation.SysEnergyEfficiency(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && t.Typecode == EquipTypeEnum.DirectFiredUnitCode)) - { - r = EngeryCalculation.DirectFireEngeryCalcu(heatMeterConsum, gasMeterConsum, ammeterConsum); - } - else if (equipmentTypes.Any(t => equipTypeIds.Contains(t.Id) && (t.Typecode == EquipTypeEnum.ColdWarmWaterCirculatingCode || t.Typecode == EquipTypeEnum.FCCCode || t.Typecode == EquipTypeEnum.CoolingTower))) - { - r = EngeryCalculation.CoolHotPumpEngeryCalu(heatMeterConsum, ammeterConsum); - } - if (r > 5000) - {//自个决定>5000的不要了 - continue; - } - result.Add(new RealDataModelItem { Time = timeList[i], Value = Math.Round(r, 2) }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - - /// - /// 能效计算 - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> GetEquipEfficiency(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); - var equipmentGroupShipAlls = new List { }; - var equipmentGroupShips = new List { }; - var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); - var isSys = 0; - if (groupParent.Order == 0) - {//默认是系统,查询所有设备 - isSys = 1; - //var allEqGroupIds = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).AsNoTracking().Select(t => t.Id).ToListAsync(); - //equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - } - else - { - isSys = 0; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - } - equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); - var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); - - #region 正常设备 - //var equipIdsNormal = await CheckEquipsState(equipIds); - //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); - //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - #endregion - - - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var endTime = startTime.AddDays(1); - - var timeList = new List { };//时间间隔 - var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); - while (_startTime <= endTime && _startTime <= nowTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - } - if (timeList.Count() == 1) - { - timeList.Add(nowTime); - } - //电气热冷 - List energyCodes = new List { "EP", "LJ", "HE", "CO" }; - - var epIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "EP").Select(t => t.Id).ToList(); - var ljIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "LJ").Select(t => t.Id).ToList(); - var heIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && (t.ParamCode == "HE" || t.ParamCode == "CO")).Select(t => t.Id).ToList(); - - var ammeterHistorys = await _context.DsPointHistory.Where(t => epIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - - var gasMeterHistorys = await _context.DsPointHistory.Where(t => ljIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - var heatMeterHistorys = await _context.DsPointHistory.Where(t => heIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - - //var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); - //var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); - //var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); - //var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); - - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - var minDate = timeList.Min(t => t); - var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - List equipmentRunningTimesHistorysClosed = null; - if (equipmentRunningTimesHistorys.Count() > 0) - { - equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - { - EquipId = t.Parm003, - StartTime = t.Starttime, - EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - }).ToList(); - } - - - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipEfficiencyDiagnosisItemModel - { - Id = equipGroup.Id, - Name = equipGroup.Eqgroupname, - EnergyEfficiencys = new List { } - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (isSys == 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); - _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - var efficiencys = await GetEquipEfficiencyV04(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); - if (efficiencys != null && efficiencys.Count() > 0) - { - foreach (var efficiency in efficiencys) - { - var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; - - item.EnergyEfficiencys.Add(_energyEfficiencyItem); - } - } - #region 计算能耗 - var _ammeterHistoryValues = ammeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) - { - //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); - item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); - } - - var _heatMeterHistoryValues = heatMeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) - { - //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); - item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value ?? 0 }).ToList(); - } - - - var _gasMeterHistoryValues = gasMeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) - { - //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); - item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); - } - #endregion - if (item.EnergyEfficiencys != null && equipGroup.Eqgroupname.Contains("直燃机")) - { - //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 - item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); - } - items.Add(item); - } - return items; - } - - /// - /// 能效计算 - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> GetEquipEfficiencyV2(List groupIds, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var groupParent = await _context.EpgProDataSetGroupItem.FirstOrDefaultAsync(t => groupIds.Contains(t.Id)); - // var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); - var equipmentGroupShipAlls = new List { }; - var equipmentGroupShips = new List { }; - var equipGroups = await _context.EpgProDataSetGroupItem.Where(t => groupIds.Contains(t.ParentId)).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); - var isSys = 0; - if (groupParent.Order == 0) - {//默认是系统,查询所有设备 - isSys = 1; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EpgProDataSetGroupItemMapEquip.Where(t => equipGroupIds.Contains(t.ProDataSetGroupItemId)).AsNoTracking().ToListAsync(); - } - else - { - isSys = 0; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EpgProDataSetGroupItemMapEquip.Where(t => equipGroupIds.Contains(t.ProDataSetGroupItemId)).AsNoTracking().ToListAsync(); - } - equipIds = equipmentGroupShipAlls.Select(t => t.EquipId).Distinct().ToList(); - var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var endTime = startTime.AddDays(1); - - var timeList = new List { };//时间间隔 - var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); - while (_startTime <= endTime && _startTime <= nowTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - } - if (timeList.Count() == 1) - { - timeList.Add(nowTime); - } - //电气热冷 - List energyCodes = new List { "EP", "LJ", "HE", "CO" }; - - var epIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "EP").Select(t => t.Id).ToList(); - var ljIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && t.ParamCode == "LJ").Select(t => t.Id).ToList(); - var heIds = _context.PtThing.Where(t => equipIds.Contains(t.ParentId) && (t.ParamCode == "HE" || t.ParamCode == "CO")).Select(t => t.Id).ToList(); - - var ammeterHistorys = await _context.DsPointHistory.Where(t => epIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - - var gasMeterHistorys = await _context.DsPointHistory.Where(t => ljIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - var heatMeterHistorys = await _context.DsPointHistory.Where(t => heIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).AsNoTracking().ToListAsync(); - - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - var minDate = timeList.Min(t => t); - var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - List equipmentRunningTimesHistorysClosed = null; - if (equipmentRunningTimesHistorys.Count() > 0) - { - equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - { - EquipId = t.Parm003, - StartTime = t.Starttime, - EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - }).ToList(); - } - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipEfficiencyDiagnosisItemModel - { - Id = equipGroup.Id, - Name = equipGroup.Name, - EnergyEfficiencys = new List { } - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (isSys == 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.ProDataSetGroupItemId == equipGroup.Id).ToList(); - _equipIds = _equipmentGroupShips.Select(t => t.EquipId).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.EquipId).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - var efficiencys = await GetEquipEfficiencyV04(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); - if (efficiencys != null && efficiencys.Count() > 0) - { - foreach (var efficiency in efficiencys) - { - var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; - - item.EnergyEfficiencys.Add(_energyEfficiencyItem); - } - } - #region 计算能耗 - var _ammeterHistoryValues = ammeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) - { - item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); - } - - var _heatMeterHistoryValues = heatMeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) - { - item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value ?? 0 }).ToList(); - } - - - var _gasMeterHistoryValues = gasMeterHistorys.GroupBy(t => t.Id).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.Value ?? 0) - t.Min(m => m.Value ?? 0) - }).ToList(); - if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) - { - item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId, Consume = t.Value }).ToList(); - } - #endregion - if (item.EnergyEfficiencys != null && equipGroup.Name.Contains("直燃机")) - { - //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 - item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); - } - items.Add(item); - } - return items; - } - - public async Task> GetEquipEfficiency_bak(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var groupParent = _context.EquipmentGroup.FirstOrDefault(t => t.Id == equipId); - var equipmentGroupShipAlls = new List { }; - var equipmentGroupShips = new List { }; - var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).AsNoTracking().ToListAsync(); - var isSys = 0; - if (groupParent.Order == 0) - {//默认是系统,查询所有设备 - isSys = 1; - //var allEqGroupIds = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).AsNoTracking().Select(t => t.Id).ToListAsync(); - //equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - } - else - { - isSys = 0; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().ToListAsync(); - } - equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); - var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - var equipTypeAlls = await _userCenterContext.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); - - #region 正常设备 - //var equipIdsNormal = await CheckEquipsState(equipIds); - //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); - //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - #endregion - - - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var endTime = startTime.AddDays(1); - - var timeList = new List { };//时间间隔 - var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); - while (_startTime <= endTime && _startTime <= nowTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - else if (intervalUnit == 3) - { - _startTime = _startTime.AddDays(interval); - } - } - if (timeList.Count() == 1) - { - timeList.Add(nowTime); - } - - - var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - - var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); - var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); - var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); - var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); - - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - var minDate = timeList.Min(t => t); - var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - List equipmentRunningTimesHistorysClosed = null; - if (equipmentRunningTimesHistorys.Count() > 0) - { - equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - { - EquipId = t.Parm003, - StartTime = t.Starttime, - EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - }).ToList(); - } - - - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipEfficiencyDiagnosisItemModel - { - Id = equipGroup.Id, - Name = equipGroup.Eqgroupname, - EnergyEfficiencys = new List { } - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (isSys == 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); - _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - var efficiencys = await GetEquipEfficiency(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, waterMeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); - if (efficiencys != null && efficiencys.Count() > 0) - { - foreach (var efficiency in efficiencys) - { - var _energyEfficiencyItem = new RealDataModelItem { Time = efficiency.Time, Value = Math.Round(efficiency.Value, 2) }; - - item.EnergyEfficiencys.Add(_energyEfficiencyItem); - } - } - #region 计算能耗 - var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.AmParm029 != null && t.AmParm029 > 0).ToList(); - var _ammeterHistoryValues = _ammeterHistorys.GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) - }).ToList(); - if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) - { - //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); - item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.HmParm002 != null && t.HmParm002 > 0).ToList(); - var _heatMeterHistoryValues = _heatMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) - }).ToList(); - if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) - { - //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); - item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - var _waterMeterHistorys = waterMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.WmParm003 != null && t.WmParm003 > 0).ToList(); - var _waterMeterHistoryValues = _waterMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) - }).ToList(); - if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) - { - //item.TotalWaterValue = _waterMeterHistoryValues.Sum(t => t.Value); - item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && _equipIds.Contains((long)t.Parm002) && t.GmParm002 != null && t.GmParm002 > 0).ToList(); - var _gasMeterHistoryValues = _gasMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) - }).ToList(); - if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) - { - //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); - item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - #endregion - if (item.EnergyEfficiencys != null && equipGroup.Eqgroupname.Contains("直燃机")) - { - //删除掉超过1.5的数值,由于异常值,直燃机偶尔会返回关闭状态 - item.EnergyEfficiencys = item.EnergyEfficiencys.Where(t => t.Value < 1.5).ToList(); - } - items.Add(item); - } - return items; - } - /// - /// 目前支持一天 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public async Task> GetEquipConsume(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var groupParent = equipmentGroups.FirstOrDefault(t => t.Id == groupId); - var equipmentGroupShipAlls = new List { }; - - var equipGroups = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).ToList(); - var isSys = 0; - if (groupParent.Order == 0) - {//默认是系统,查询所有设备 - isSys = 1; - //var allEqGroupIds = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).Select(t => t.Id).ToList(); - //equipmentGroupShipAlls = equipmentGroupShips.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).ToList(); - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); - } - else - { - isSys = 0; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); - } - equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); - var equipInfoAlls = equipmentInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - var equipTypeAlls = equipmentTypeAlls.Where(t => t.Isusing == 1).ToList(); - - #region 正常设备 - //var equipIdsNormal = await CheckEquipsState(equipIds); - //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); - //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - #endregion - - - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var startTime1 = startTime.AddHours(1); - var endTime = startTime.AddDays(1).AddHours(-1); - var endTime1 = startTime.AddDays(1); - if (date.ToString("yyyy-MM-dd") == nowTime.ToString("yyyy-MM-dd")) - { - endTime = nowTime.AddHours(-1); - endTime1 = nowTime; - } - - var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - - //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - - //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); - //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); - //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); - //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm001 >= startTime && t.Parm001 < startTime1) || (t.Parm001 >= endTime1 && t.Parm001 < endTime))); - - //var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); - //var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); - //var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); - //var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); - - - var ammeterHistoryValues = await ammeterHistoryQuery.Where(t => t.AmParm029 != null && t.AmParm029 > 0).GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) - }).AsNoTracking().ToListAsync(); - var waterMeterHistoryValues = await waterMeterHistoryQuery.Where(t => t.WmParm003 != null && t.WmParm003 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) - }).AsNoTracking().ToListAsync(); - var gasMeterHistoryValues = await gasMeterHistoryQuery.Where(t => t.GmParm002 != null && t.GmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) - }).AsNoTracking().ToListAsync(); - var heatMeterHistoryValues = await heatMeterHistoryQuery.Where(t => t.HmParm002 != null && t.HmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - { - EquipId = t.Key, - Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) - }).AsNoTracking().ToListAsync(); - - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - //var minDate = timeList.Min(t => t); - //var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - //var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - //List equipmentRunningTimesHistorysClosed = null; - //if (equipmentRunningTimesHistorys.Count() > 0) - //{ - // equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - // { - // EquipId = t.Parm003, - // StartTime = t.Starttime, - // EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - // }).ToList(); - //} - - - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipConsumeDiagnosisItemModel - { - Id = equipGroup.Id, - Name = equipGroup.Eqgroupname - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (isSys == 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); - _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - #region 计算能耗 - //var _ammeterHistorys = ammeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.AmParm029 != null && t.AmParm029 > 0).ToList(); - //var _ammeterHistoryValues = _ammeterHistorys.GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) - //}).ToList(); - var _ammeterHistoryValues = ammeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) - { - //item.TotalAmmeterValue = _ammeterHistoryValues.Sum(t => t.Value); - item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - //var _heatMeterHistorys = heatMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.HmParm002 != null && t.HmParm002 > 0).ToList(); - //var _heatMeterHistoryValues = _heatMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) - //}).ToList(); - var _heatMeterHistoryValues = heatMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) - { - //item.TotalHeatValue = _heatMeterHistoryValues.Sum(t => t.Value); - item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - //var _waterMeterHistorys = waterMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.WmParm003 != null && t.WmParm003 > 0).ToList(); - //var _waterMeterHistoryValues = _waterMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) - //}).ToList(); - var _waterMeterHistoryValues = waterMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) - { - //item.TotalWaterValue = _waterMeterHistoryValues.Sum(t => t.Value); - item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - //var _gasMeterHistorys = gasMeterHistorys.Where(t => t.Parm002 != null && t.Parm002 > 0 && _equipIds.Contains((long)t.Parm002) && t.GmParm002 != null && t.GmParm002 > 0).ToList(); - //var _gasMeterHistoryValues = _gasMeterHistorys.GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) - //}).ToList(); - var _gasMeterHistoryValues = gasMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) - { - //item.TotalGasValue = _gasMeterHistoryValues.Sum(t => t.Value); - item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - } - #endregion - items.Add(item); - } - return items; - } - - public async Task> GetEquipConsume_V02(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var groupParent = equipmentGroups.FirstOrDefault(t => t.Id == groupId); - var equipmentGroupShipAlls = new List { }; - - var equipGroups = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Parentid == groupParent.Id).OrderBy(t => t.Order).ToList(); - var isSys = 0; - if (groupParent.Order == 0) - {//默认是系统,查询所有设备 - isSys = 1; - //var allEqGroupIds = equipmentGroups.Where(t => t.Grouptype == EqGroupTypeEnum.GroupType_SysDiagnosis && t.Projectid == groupParent.Projectid).Select(t => t.Id).ToList(); - //equipmentGroupShipAlls = equipmentGroupShips.Where(t => allEqGroupIds.Contains(t.Eqgroupid)).ToList(); - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); - } - else - { - isSys = 0; - var equipGroupIds = equipGroups.Select(t => t.Id).Distinct().ToList(); - equipmentGroupShipAlls = equipmentGroupShips.Where(t => equipGroupIds.Contains(t.Eqgroupid)).ToList(); - } - equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); - var equipInfoAlls = equipmentInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - var equipTypeAlls = equipmentTypeAlls.Where(t => t.Isusing == 1).ToList(); - - #region 正常设备 - //var equipIdsNormal = await CheckEquipsState(equipIds); - //equipmentGroupShips = equipmentGroupShipAlls.Where(t => equipIdsNormal.Contains(t.Eqid)).ToList(); - //equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - #endregion - - - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var startTime1 = startTime.AddHours(1); - var endTime = startTime.AddDays(1).AddHours(-1); - var endTime1 = startTime.AddDays(1); - if (date.ToString("yyyy-MM-dd") == nowTime.ToString("yyyy-MM-dd")) - { - endTime = nowTime.AddHours(-1); - endTime1 = nowTime; - } - - //var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - //var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - //var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - //var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && ((t.Parm003 >= startTime && t.Parm003 < startTime1) || (((endTime >= startTime && t.Parm003 > endTime) || (endTime < startTime && t.Parm003 >= startTime)) && t.Parm003 <= endTime1))); - - //var ammeterHistoryValues = await ammeterHistoryQuery.Where(t => t.AmParm029 != null && t.AmParm029 > 0).GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.AmParm029 ?? 0) - t.Min(m => m.AmParm029 ?? 0) - //}).AsNoTracking().ToListAsync(); - //var waterMeterHistoryValues = await waterMeterHistoryQuery.Where(t => t.WmParm003 != null && t.WmParm003 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.WmParm003 ?? 0) - t.Min(m => m.WmParm003 ?? 0) - //}).AsNoTracking().ToListAsync(); - //var gasMeterHistoryValues = await gasMeterHistoryQuery.Where(t => t.GmParm002 != null && t.GmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.GmParm002 ?? 0) - t.Min(m => m.GmParm002 ?? 0) - //}).AsNoTracking().ToListAsync(); - //var heatMeterHistoryValues = await heatMeterHistoryQuery.Where(t => t.HmParm002 != null && t.HmParm002 > 0).AsNoTracking().GroupBy(t => t.Parm002).Select(t => new - //{ - // EquipId = t.Key, - // Value = t.Max(m => m.HmParm002 ?? 0) - t.Min(m => m.HmParm002 ?? 0) - //}).AsNoTracking().ToListAsync(); - - #endregion - - #region DW - var timeIds = await _airDBContext.Times.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime1).AsNoTracking().Select(t => t.Id).ToListAsync(); - var ammeterDws = await _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new - { - Parm002 = t.Parm002 ?? 0, - AmParm003 = t.AmParm003 ?? 0 - }).AsNoTracking().ToListAsync(); - var waterMeterDws = await _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new - { - Parm002 = t.Parm002 ?? 0, - WmParm002 = t.WmParm002 ?? 0 - }).AsNoTracking().ToListAsync(); - var gasMeterDws = await _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new - { - Parm002 = t.Parm002 ?? 0, - GmParm002 = t.GmParm002 ?? 0 - }).AsNoTracking().ToListAsync(); - var heatMeterDws = await _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new - { - Parm002 = t.Parm002 ?? 0, - HmParm001 = t.HmParm001 ?? 0 - }).AsNoTracking().ToListAsync(); - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - //var minDate = timeList.Min(t => t); - //var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - //var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - //List equipmentRunningTimesHistorysClosed = null; - //if (equipmentRunningTimesHistorys.Count() > 0) - //{ - // equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - // { - // EquipId = t.Parm003, - // StartTime = t.Starttime, - // EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - // }).ToList(); - //} - - - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipConsumeDiagnosisItemModel - { - Id = equipGroup.Id, - Name = equipGroup.Eqgroupname - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (isSys == 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); - _equipIds = _equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - #region 计算能耗 - - var _ammeterDws = ammeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new - { - Parm002 = t.Key, - AmParm003 = t.Sum(s => s.AmParm003) - }).ToList(); - if (_ammeterDws != null && _ammeterDws.Count() > 0) - { - item.AmmeterEquipConsumes = _ammeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.AmParm003 }).ToList(); - } - - //var _ammeterHistoryValues = ammeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - //if (_ammeterHistoryValues != null && _ammeterHistoryValues.Count() > 0) - //{ - // item.AmmeterEquipConsumes = _ammeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - //} - - var _heatMeterDws = heatMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new - { - Parm002 = t.Key, - HmParm001 = t.Sum(s => s.HmParm001) - }).ToList(); - if (_heatMeterDws != null && _heatMeterDws.Count() > 0) - { - item.HeatEquipConsumes = _heatMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.HmParm001 }).ToList(); - } - - //var _heatMeterHistoryValues = heatMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - //if (_heatMeterHistoryValues != null && _heatMeterHistoryValues.Count() > 0) - //{ - // item.HeatEquipConsumes = _heatMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - //} - - var _waterMeterDws = waterMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new - { - Parm002 = t.Key, - WmParm002 = t.Sum(s => s.WmParm002) - }).ToList(); - if (_waterMeterDws != null && _waterMeterDws.Count() > 0) - { - item.WaterEquipConsumes = _waterMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.WmParm002 }).ToList(); - } - - //var _waterMeterHistoryValues = waterMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - //if (_waterMeterHistoryValues != null && _waterMeterHistoryValues.Count() > 0) - //{ - // item.WaterEquipConsumes = _waterMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - //} - - var _gasMeterDws = gasMeterDws.Where(t => _equipIds.Contains(t.Parm002)).GroupBy(t => t.Parm002).Select(t => new - { - Parm002 = t.Key, - GmParm002 = t.Sum(s => s.GmParm002) - }).ToList(); - if (_gasMeterDws != null && _gasMeterDws.Count() > 0) - { - item.GasEquipConsumes = _gasMeterDws.Select(t => new EquipConsumeModel { EquipId = t.Parm002, Consume = t.GmParm002 }).ToList(); - } - - //var _gasMeterHistoryValues = gasMeterHistoryValues.Where(t => t.EquipId != null && _equipIds.Contains((long)t.EquipId)).ToList(); - //if (_gasMeterHistoryValues != null && _gasMeterHistoryValues.Count() > 0) - //{ - // item.GasEquipConsumes = _gasMeterHistoryValues.Select(t => new EquipConsumeModel { EquipId = t.EquipId ?? 0, Consume = t.Value }).ToList(); - //} - #endregion - items.Add(item); - } - return items; - } - - /// - /// - /// - /// - /// - /// 1-分钟,2-小时 - /// - /// - /// - /// - public async Task> GetEquipEfficiencyAndConsum(long projectId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext) - { - var items = new List { }; - - var equipIds = new List { }; - - var equipmentGroupShips = new List { }; - var equipGroups = await _context.EquipmentGroup.Where(t => t.Grouptype == EqGroupTypeEnum.EnergyEfficiencyConsumZone && t.Projectid == projectId).OrderBy(t => t.Order).AsNoTracking().TagWith("SubDB").ToListAsync(); - var equipGroupIds = equipGroups.Select(t => t.Id).ToList(); - - var equipmentGroupShipAlls = await _context.EquipmentGroupShip.Where(t => equipGroupIds.Contains(t.Eqgroupid)).AsNoTracking().TagWith("SubDB").ToListAsync(); - - equipIds = equipmentGroupShipAlls.Select(t => t.Eqid).Distinct().ToList(); - var equipInfoAlls = await _context.EquipmentInfo.Where(t => equipIds.Contains(t.Id)).AsNoTracking().TagWith("SubDB").ToListAsync(); - //var equipTypeAlls = await _context.EquipmentType.Where(t => t.Isusing == 1).AsNoTracking().ToListAsync(); - var equipTypeAlls = _dictionaryService.GetValue(typeof(EquipmentType).Name).Values.Where(t => t.Isusing == 1).ToList(); - - - - var equipInfos = equipInfoAlls.Where(t => equipIds.Contains(t.Id)).ToList(); - - //防止无法判断组的设备类型 - var equipTypeIds = equipInfoAlls.Select(t => t.Eqtype ?? 0).Distinct().ToList(); - var equipmentTypes = equipTypeAlls.Where(t => equipTypeIds.Contains(t.Id)).ToList(); - #region 历史表查询 - - var nowTime = DateTime.Now; - var startTime = DateTime.Parse(date.ToString("yyyy-MM-dd"));//目前只支持到当天 - var endTime = startTime.AddDays(1); - - var timeList = new List { };//时间间隔 - var _startTime = DateTime.Parse(date.ToString("yyyy-MM-dd")); - while (_startTime <= endTime && _startTime <= nowTime) - { - timeList.Add(_startTime); - if (intervalUnit == 1) - { - _startTime = _startTime.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _startTime = _startTime.AddHours(interval); - } - } - if (timeList.Count() == 1) - { - timeList.Add(nowTime); - } - - - var ammeterHistoryQuery = _airDBContext.TbAmmeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var waterMeterHistoryQuery = _airDBContext.TbWaterMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var gasMeterHistoryQuery = _airDBContext.TbGasMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - var heatMeterHistoryQuery = _airDBContext.TbHeatMeterHistory.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && t.Parm003 >= startTime && t.Parm003 < endTime); - - var ammeterHistorys = await ammeterHistoryQuery.AsNoTracking().ToListAsync(); - var waterMeterHistorys = await waterMeterHistoryQuery.AsNoTracking().ToListAsync(); - var gasMeterHistorys = await gasMeterHistoryQuery.AsNoTracking().ToListAsync(); - var heatMeterHistorys = await heatMeterHistoryQuery.AsNoTracking().ToListAsync(); - - #endregion - - #region 设备历史状态 - equipmentGroupShips = equipmentGroupShipAlls; - var minDate = timeList.Min(t => t); - var maxDate = timeList.Max(t => t); - //设备历史状态,关机状态 - var equipmentRunningTimesHistorys = await _airDBContext.TbEquipmentRunningTimesHistory.Where(t => equipIds.Contains(t.Parm003) && t.Eqstatus == 0 && t.Runningtimes != null && t.Runningtimes > 10 && (t.Parm004 >= minDate && t.Parm004 <= maxDate)).AsNoTracking().ToListAsync(); - - List equipmentRunningTimesHistorysClosed = null; - if (equipmentRunningTimesHistorys.Count() > 0) - { - equipmentRunningTimesHistorysClosed = equipmentRunningTimesHistorys.Where(t => t.Runningtimes != null).Select(t => new EquipmentRunningTimesHistorysClosed - { - EquipId = t.Parm003, - StartTime = t.Starttime, - EndTime = t.Starttime.AddMinutes((double)t.Runningtimes) - }).ToList(); - } - - - #endregion - - foreach (var equipGroup in equipGroups) - { - var item = new EquipEfficiencyAndConsumModel - { - Id = equipGroup.Id, - Name = equipGroup.Eqgroupname, - EnergyEfficiencys = new List { } - }; - var _equipInfoAlls = new List { }; - var _equipIds = new List { }; - if (equipGroups.IndexOf(equipGroup) > 0) - { - var _equipmentGroupShips = equipmentGroupShips.Where(t => t.Eqgroupid == equipGroup.Id).ToList(); - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList(); - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - else - {//系统,所有设备 - _equipIds = equipmentGroupShips.Select(t => t.Eqid).Distinct().ToList();//所有设备 - _equipInfoAlls = equipInfoAlls.Where(t => _equipIds.Contains(t.Id)).ToList(); - } - var _equipInfos = equipInfos.Where(t => _equipIds.Contains(t.Id)).ToList(); - - var efficiencys = await GetEquipEfficiency(timeList, _equipInfos, _equipInfoAlls, equipmentTypes, ammeterHistorys, waterMeterHistorys, gasMeterHistorys, heatMeterHistorys, equipmentRunningTimesHistorysClosed); - if (efficiencys != null && efficiencys.Count() > 0) - { - foreach (var efficiency in efficiencys) - { - item.EnergyEfficiencys.Add(new EquipEfficiencyAndConsumItemModel { Time = efficiency.Time, Efficiency = Math.Round(efficiency.Value, 2) }); - } - } - items.Add(item); - } - return items; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs deleted file mode 100644 index 706aca7..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/EquipReport/IEquipStatisticsService.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.SystemDiagnosis; - -namespace WeiCloud.Core.EquipStatistics -{ - public interface IEquipStatisticsService - { - Task> GetEnergyEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List coolMeterHistorys); - Task> GetEquipEfficiencyV03(double interval, int intervalUnit, DateTime startTime, DateTime endTime, string label, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys); - //Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); - - Task> GetEquipEfficiencyByCumulative(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); - Task> GetEquipEfficiency(long equipId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); - - Task> GetEquipEfficiencyV2(List groupIds, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); - Task> GetEquipEfficiencyAndConsum(long projectId, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); - - Task> GetEquipConsume(long equipId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); - Task> GetEquipConsume_V02(long groupId, List equipmentGroups, List equipmentGroupShips, List equipmentInfoAlls, List equipmentTypeAlls, DateTime date, int interval, short intervalUnit, WeiCloudDBContext _context, WeiCloudAirDBContext _airDBContext); - Task> GetEquipEfficiencyV04(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); - Task> GetEquipEfficiency(List timeList, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, List equipmentRunningTimesHistorysCloseds = null); - Task> GetEquipEfficiency(DateTime startTime, DateTime endTime, List equipmentInfos, List equipmentInfoAlls, List equipmentTypes, List ammeterHistorys, List waterMeterHistorys, List gasMeterHistorys, List heatMeterHistorys, double interval, int intervalUnit); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs deleted file mode 100644 index 2770ec1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IConstrInfoGainCoreService.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.LogicModels; - -namespace WeiCloud.Core.Services -{ - public interface IConstrInfoGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task> GetAllConstructionInfoRedis(); - Task GetConstModelById(long id); - Task> GetConstByKeys(string[] keys); - Task> GetConstTreeByProjectId(long projectId, int isUsing, int? level); - Task> GetConstEquipsTreeByProjectId(long projectId); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs deleted file mode 100644 index 70a3613..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IEnergySaveDwCoreService.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Services -{ - public interface IEnergySaveDwCoreService - { - /// - /// 项目到目前为止的节能量 - /// - /// - /// - /// - Task GetProEneSaveDWNow(long? project, DateTime dateTime); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs deleted file mode 100644 index 2438453..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IEquipInfoCoreService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; - -namespace WeiCloud.Core.Services -{ - public interface IEquipInfoCoreService - { - Task> GetEquipmentInfos(long projectId); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs deleted file mode 100644 index ec0f66b..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/INlogCoreService.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Services -{ - public interface INlogCoreService - { - Task PostNlogsParam(string actionName, int? type, string oldValue, string newValue, string message, long operatorId = 0, string operatorName = ""); - - Task> UpdateOrAndNlogs(List nlogs); - Task> UpdateOrAndNlogs(CmdNlogBoNew item); - Task> UpdateOrAndNlog(CmdNlogBoNew item); - Task> GetIPHomePlaces(List ips); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs deleted file mode 100644 index 9552529..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IPermissionsGainCoreService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public interface IPermissionsGainCoreService - { - Task> GetAllPermissionsRedis(); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs deleted file mode 100644 index 8d1c3db..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectDWCoreService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Services -{ - public interface IProjectDWCoreService - { - Task GetCurrentEnergyYear(long? projectid, DateTime dateTime); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs deleted file mode 100644 index 4ece86d..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IProjectInfoGainCoreService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; - -namespace WeiCloud.Core.Services -{ - public interface IProjectInfoGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task> GetAllEquipRedis(); - Task GetEquipModel(long equipId); - Task> GetEquipListByKeys(string[] keys); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs deleted file mode 100644 index fbd4032..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IPublicFunctionService.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.InfoModels; -using WeiCloud.Entity.LogicModels.SysModule; - -namespace WeiCloud.Core.Services -{ - public interface IPublicFunctionService: WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task>> GetProjectListByRole(CurrentUser user); - Task> GetWeatherByProId(long proiectId); - Task>> Get7DaysWeatherByProId(long proiectId); - Task> GetWeatherByProIdNow(long proiectId); - Task>> GetEngeryType(); - Task>> GetAirQuantityType(); - Task>> GetTimeSpanData(); - Task> GetProjectBaseInfo(long projectid); - Task>> GetProjectMenuSysModule(string roleCode, long projectId, long parentId, long? modelType = 0); - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs deleted file mode 100644 index 7210223..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IRealDataAnalyzeCoreService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Services -{ - public interface IRealDataAnalyzeCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task>> GetEquCommStatusAsync(List equids); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs deleted file mode 100644 index 117bd83..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IStandarParamsCoreService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public interface IStandarParamsCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task GetStandarParam(int id); - Task> GetStandarParam(); - Task> GetStandarParamByAllKes(string[] keys); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs deleted file mode 100644 index ab684aa..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ISteamHeatCalculateService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace WeiCloud.Core.Services -{ - public interface ISteamHeatCalculateService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task CalculateSteamHeat(double steamFlow, double steamOutTemperature, double waterInTemperature); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs deleted file mode 100644 index 3b07d06..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserGroupsGainCoreService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.ProConfiguration.Service -{ - public interface IUserGroupsGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task PushUserGroupsToRedis(UserGroups userGroups); - Task deleteUserGroupsInfo(string[] keys); - Task GetUserGroupsModelById(long id); - Task> GetAllUserGroupsRedis(); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs deleted file mode 100644 index 3626e51..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPermissionsCoreService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public interface IUserProjectPermissionsCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task GetCurrentUserPermission(string userId); - Task> GetAllGroupPressRedis(); - Task GetCurrentUserPermission(string userRoleId, string userGroupId); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs deleted file mode 100644 index 72fcc4f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IUserProjectPressRedisTreeService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; - -namespace WeiCloud.Core.Services -{ - public interface IUserProjectPressRedisTreeCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task GetProIdAndConstPressTreeByUserId(long userId); - Task GetUserRolePress(); - Task GetUserRolePress(long? userId, string code); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs deleted file mode 100644 index 216c102..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersCoreService.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.Users; - -namespace WeiCloud.Core.Services -{ - public interface IUsersCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task GetUsersById(long id); - Task GetUsersByName(string name); - Task GetAdmin(); - Task GetUsersByIdV02(long id); - Task> GetChildDeptUsers(List userGroups, long deptId); - Task GetUserInfoByJwt(string token); - Task> GetUserIdsByProjectId(long projectId); - Task ChangeUserPassword(long userId, string newPwd); - UserInfoJwtViewModel GetUserInfoByJwtStr(string token); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs deleted file mode 100644 index 2f15fbf..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IUsersGainCoreService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public interface IUsersGainCoreService : WeiCloud.Core.BaseCore.IGrainWithIntegerKey - { - Task GetUserModelById(long id); - Task PushUserToRedis(Users users); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs deleted file mode 100644 index 7e4a2c5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/IWorkflowService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.DataModels; - -namespace WeiCloud.Core.Services -{ - public interface IWorkflowService - { - Task SaveWorkflowAsync(WorkOrderAggregateDto dto); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs deleted file mode 100644 index 666b2b5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IIotService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.IotDS; - -namespace WeiCloud.Core.Services.Iot -{ - public interface IIotService - { - Task>> GetIoTDeviceControl(GetIoTDeviceControlModel input); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs deleted file mode 100644 index e5377e0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Iot/IotService.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.IotDS; - -namespace WeiCloud.Core.Services.Iot -{ - public class IotService : IIotService - { - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - public IotService(IServiceScopeFactory serviceScopeFactory, ILogger logger, WeiCloudDBContext weiCloudDBContext, WeiCloudDBUserCenterContext weiCloudDBUserCenterContext) - { - _serviceScopeFactory = serviceScopeFactory; - _logger = logger ?? throw new ArgumentNullException(nameof(_logger)); - } - /// - /// 查看参数下控记录 - /// - /// - public async Task>> GetIoTDeviceControl(GetIoTDeviceControlModel input) - { - var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var currentContext = scope.ServiceProvider.GetRequiredService().GetContext(); - if (currentContext == null || string.IsNullOrEmpty(currentContext.Token)) - { - result.Code = RequestBackStatuEnum.unauthorized.Value; - return result; - } - var configuration = scope.ServiceProvider.GetRequiredService(); - var httpClientFactory = scope.ServiceProvider.GetRequiredService(); - var message = JsonConvert.SerializeObject(input); - using (HttpContent httpContent = new StringContent(message)) - { - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - var url = $"{configuration["Iot:BaseUrl"]}api/IotDeviceProperty/GetIoTDeviceControl"; - using (var httpClient = new HttpClient()) - { - httpClient.DefaultRequestHeaders.Add("Authorization", currentContext.Token); - httpClient.DefaultRequestHeaders.Add("Accept", "application/json;charset=UTF-8"); - HttpResponseMessage responseMessage = await httpClient.PostAsync(url, httpContent); - if (responseMessage.IsSuccessStatusCode) - { - var responseStr = await responseMessage.Content.ReadAsStringAsync(); - result = JsonConvert.DeserializeObject>>(responseStr); - } - } - } - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {0};", "GetIotDevices", ex.Message)).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs deleted file mode 100644 index ef12d47..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/IJobManagerCoreService.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.JobTask; - -namespace WeiCloud.Core.Services.Job -{ - public interface IJobManagerCoreService - { - Task GetJob(string jobName, bool isDeleted = false); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs deleted file mode 100644 index c5fbb80..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Job/JobManagerCoreService.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.JobTask; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; - -namespace WeiCloud.Core.Services.Job -{ - public class JobManagerCoreService : IJobManagerCoreService - { - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - public JobManagerCoreService(IServiceScopeFactory serviceScopeFactory, ILogger logger, IConfiguration configuration) - { - _serviceScopeFactory = serviceScopeFactory; - _logger = logger; - _configuration = configuration; - } - /// - /// 获取任务 - /// - /// - /// - /// - public async Task GetJob(string jobName, bool isDeleted = false) - { - JobTaskModel result = null; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var _httpClientFactory = scope.ServiceProvider.GetRequiredService(); - var apiUrl = $"{_configuration["JobTaskApiUrl"]}{"/api/Job/QueryJob"}?jobName={jobName}&isDeleted={isDeleted}"; - var client = _httpClientFactory.CreateClient(); - client.Timeout = TimeSpan.FromSeconds(3); - var httpResponse = await client.GetAsync(apiUrl); - var responseBody = string.Empty; - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - responseBody = await httpResponse.Content.ReadAsStringAsync(); - } - result = JsonConvert.DeserializeObject(responseBody); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(System.Reflection.MethodBase.GetCurrentMethod().Name, string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs deleted file mode 100644 index 431663f..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMessageService.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Core.EventBus; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Services.Message -{ - public interface IMessageService - { - Task> SendMsg(ProduceMsgModel faultMsg); - Task> UserOnlineSendOffline(long userId); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs deleted file mode 100644 index d5f4b33..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/IMsgCenterCoreService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Core.EventBus; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.MsgCenter; - -namespace WeiCloud.Core.Services.Message -{ - public interface IMsgCenterCoreService - { - Task> ResendInternalMsg(long userId); - Task> SendMsg(MsgTempateEventDto input); - Task> TenantSendMsg(InternalTenantSendMsgDto input); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs deleted file mode 100644 index 4f06427..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MessageService.cs +++ /dev/null @@ -1,459 +0,0 @@ -using DotNetCore.CAP; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Msg.Core.UniPush; -using Newtonsoft.Json; -using StackExchange.Redis; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Core.AliYunSms; -using WeiCloud.Core.EventBus; -using WeiCloud.Core.MsgSocket; -using WeiCloud.Core.Services.Tenement; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core.Services.Message -{ - public class MessageService : IMessageService - { - private readonly ILogger _logger; - private readonly UniPushInstance _uniPushInstance; - private readonly WeiCloudDBUserCenterContext _userDBContext; - private readonly ISmsHelperService _smsHelperService; - private readonly ICapPublisher _capPublisher; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly IConfiguration _configuration; - public MessageService(ICapPublisher capPublisher, UniPushInstance uniPushInstance, WeiCloudDBUserCenterContext userDBContext, ILogger logger, ISmsHelperService smsHelperService, IServiceScopeFactory serviceScopeFactory,IConfiguration configuration) - { - _uniPushInstance = uniPushInstance; - _userDBContext = userDBContext; - _logger = logger; - _smsHelperService = smsHelperService; - _capPublisher = capPublisher; - _serviceScopeFactory = serviceScopeFactory; - _configuration = configuration; - } - /// - /// 发送消息 - /// - /// - /// - public async Task> SendMsg(ProduceMsgModel faultMsg) - { - var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = true }; - try - { - if (faultMsg == null) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Data = false; - return result; - } - if (faultMsg.UserIds == null || faultMsg.UserIds.Count() == 0) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Data = false; - return result; - } - if (faultMsg.SendTypes == null || faultMsg.SendTypes.Count() == 0) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Data = false; - return result; - } - var users = await _userDBContext.Users.Where(t => faultMsg.UserIds.Contains(t.Id)).Select(t => new - { - t.Id, - t.Userfullname, - t.Phone - }).AsNoTracking().ToListAsync(); - - long sendMsgId = UidGenerator.Uid(); - var payLoad = JsonConvert.SerializeObject(new - { - projectId = faultMsg.ProjectId, - id = faultMsg.Id, - type = 1, - MsgType = faultMsg.MsgType, - MainId = faultMsg.MainId, - msg = sendMsgId - }); - _userDBContext.SendMsgs.Add(new SendMsgs - { - Id = sendMsgId, - Title = faultMsg.Title, - Content = faultMsg.Content, - Payload = payLoad, - ProduceContent = JsonConvert.SerializeObject(faultMsg), - CreateTime = DateTime.Now - }); - List? userMapClients = null; - if (faultMsg.SendTypes.Contains((int)SendTypeMeta.AppMsg)) - { - userMapClients = await _userDBContext.UserMapClient.Where(t => faultMsg.UserIds.Contains(t.UserId)).Select(t => new UserMapClient - { - UserId = t.UserId, - ClientId = t.ClientId, - ServerId = t.ServerId, - ClientType = t.ClientType - }).ToListAsync(); - } - - foreach (var userId in faultMsg.UserIds) - { - try - { - if (faultMsg.SendTypes.Contains((int)SendTypeMeta.AppMsg))//app端 - { - UniPushResModel pushResult = null; - var _userMapClients = userMapClients.Where(t => t.UserId == userId && !string.IsNullOrEmpty(t.ClientId) && t.ClientType == (short)SendTypeMeta.AppMsg).ToList(); - var userMapClient = _userMapClients.FirstOrDefault(t => !string.IsNullOrEmpty(t.ServerId)); - if (userMapClient != null && !string.IsNullOrEmpty(userMapClient.ServerId) && !string.IsNullOrEmpty(userMapClient.ClientId)) - { - var instance = _uniPushInstance.Instance(userMapClient.ServerId); - if (instance != null) - { - pushResult = await instance.Push(new MsgPushEntity - { - ClientIds = _userMapClients.Select(t => t.ClientId).ToList(), - Body = faultMsg.Content, - Title = faultMsg.Title, - PlayLoad = payLoad, - ClickType = 5, - }); - } - } - _userDBContext.SendUserMsg.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = userId, - MsgId = sendMsgId, - IsSend = (pushResult != null && pushResult.Code == 200), - SendType = (short)SendTypeMeta.AppMsg, - IsRead = 0, - MsgType = faultMsg.MsgType, - EmergencyType = faultMsg.EmergencyType, - MainId = faultMsg.MainId, - ProjectId = faultMsg.ProjectId, - CreateTime = DateTime.Now - }); - } - if (faultMsg.SendTypes.Contains((int)SendTypeMeta.PcMsg)) //PC端 - { - //后续再写 - /*var pcClienIds = userMapClientInfos.Where(ui => ui.ClientType == (short)SendTypeMeta.PcMsg).Select(ui => ui.ClientId).Distinct().ToList(); - foreach (var pcClienId in pcClienIds) - { - try - { - *//* await _msgHub.Clients.Client(pcClienId).SendAsync("ReceiveFaultMsg", new MsgPushModel - { - MsgId = sendMsgId, - Title = faultMsg.Title, - Body = !string.IsNullOrEmpty(faultMsg.Content) && faultMsg.Content.Length > 20 ? faultMsg.Content.Substring(0, 20) : faultMsg.Content, - ClientId = pcClienId, - Type = 1, - PlayLoad = faultMsg.Extend - });*//* - } - catch (Exception ex) - { - _logger.LogError(ex, "ActionName:" + this.GetType().FullName); - Console.WriteLine(ex.Message); - } - }*/ - - bool isSend = false; - using (var scope = _serviceScopeFactory.CreateScope()) - { - var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); - var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); - var keys = await msgWebSocketClientInstance.GetClientIds(userId, faultMsg.SubscribeAction, faultMsg.SubscribeFilter); - //Console.WriteLine($"发送:{userId}" + JsonConvert.SerializeObject(keys)); - - if (keys != null && keys.Any()) - { - _logger.LogWarning($"{userId}发送消息,客户端Keys:{JsonConvert.SerializeObject(keys)} {faultMsg.Content}"); - foreach (var key in keys) - { - await myWebSocketHandler.SendMessageAsync(key, faultMsg.Content); - } - isSend = true; - } - } - _userDBContext.SendUserMsg.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = userId, - MsgId = sendMsgId, - IsSend = isSend, - SendType = (short)SendTypeMeta.PcMsg, - IsRead = 0, - MsgType = faultMsg.MsgType, - EmergencyType = faultMsg.EmergencyType, - MainId = faultMsg.MainId, - CreateTime = DateTime.Now, - ProjectId = faultMsg.ProjectId - }); - } - if (faultMsg.SendTypes.Contains((int)SendTypeMeta.SMSMsg)) - { - - var title = faultMsg.Title; - if (faultMsg.Title.Length > 20) - { - title = faultMsg.Title.Substring(0, 20); - } - if (!string.IsNullOrEmpty(title)) - { - title = title.Replace(".", "_");//替换特殊字符 - } - - var content = faultMsg.Content; - if (content.Length > 20) - { - content = content.Substring(0, 20); - } - if (!string.IsNullOrEmpty(content)) - { - content = content.Replace(".", "_");//替换特殊字符 - } - var equname = faultMsg.ProjectShortName + "_" + faultMsg.EquName; - - if (equname.Length > 20) - { - equname = equname.Substring(0, 20); - } - if (!string.IsNullOrEmpty(equname)) - { - equname = equname.Replace(".", "_");//替换特殊字符 - } - - //短信发送 - var user = users.Where(x => x.Id == userId).FirstOrDefault(); - if (user != null) - { - if (!string.IsNullOrEmpty(user.Phone)) - { - bool isSend = false; - //发送短信 - string msg = ""; - switch (faultMsg.MsgType) - { - case 0: - msg = "{\"Code\":\"" + content + "\"}"; - break; - case 1://工单 您有新的工单待处理,状态:${status},工单摘要:${remark},请及时处理。 - - msg = "{\"status\":\"" + title + "\",\"remark\":\"" + content + "\"}"; - break; - case 2://知识库 - msg = "{\"Code\":\"" + content + "\"}"; - break; - case 3://报警 您有新的报警,设备名称:${eqname},报警摘要:${remark},请及时处理。 - /* var equname = await _dbContext.QueryFirstAsync("SELECT `eqname` FROM `EquipmentInfo` WHERE `id` =" + faultMsg.EquId); - var projectShortName = await _dbContext.QueryFirstAsync("SELECT `shortname` FROM `ProjectInfo` WHERE `id` =" + faultMsg.ProjectId); - equname = projectShortName + "_" + projectShortName;*/ - - - if (string.IsNullOrEmpty(equname)) - { - equname = "暂无"; - } - //var contet1 = faultMsg.Content; - //if (faultMsg.Content.Length > 20) - //{ - // contet1 = faultMsg.Content.Substring(0, 20); - //} - - msg = "{\"eqname\":\"" + equname + "\",\"remark\":\"" + content + "\"}"; - break; - case 4: //计划管理 - //msg = "{\"Code\":\"" + faultMsg.Content + "\"}"; - break; - case 5: //智能诊断 - //var equname1 = faultMsg.ProjectShortName; - - //if (equname1.Length > 20) - //{ - // equname1 = equname1.Substring(0, 20); - //} - //var contet2 = faultMsg.Content; - //if (faultMsg.Content.Length > 20) - //{ - // contet2 = faultMsg.Content.Substring(0, 20); - //} - - msg = "{\"eqname\":\"" + equname + "\",\"remark\":\"" + content + "\"}"; - break; - default: - break; - } - _logger.LogWarning($"短信下发 {msg}"); - if (!string.IsNullOrEmpty(msg)) - { - //SmsResposeModel smsResposeModel = _smsHelperService.SendSms(user.Phone, msg, faultMsg.MsgType); - - //if (smsResposeModel.Code == "OK") - //{ - // isSend = true; - //} - //else if (smsResposeModel.Code == "MonthLimitControl" || smsResposeModel.Code == "DayLimitControl") - //{ - - // _logger.LogError($"短信下发失败 {smsResposeModel.Message} {smsResposeModel.Code}"); - //} - //else - //{ - // _logger.LogError($"短信下发失败 {smsResposeModel.Message} {smsResposeModel.Code}"); - //} - //if (faultMsg.MsgType == 3) - //{ - // //下发电话通知 - // //尊敬的客户,项目{pname},设备{eqname}产生{warning}报警 - // // var callmsg = "{\"pname\":\"" + faultMsg.ProjectShortName + "\",\"eqname\":\"" + faultMsg.EquName + "\",\"warning\":\"" + faultMsg.Content + "\"}"; - // // _callHelperService.SendFaultCall(user.Phone, callmsg); - //} - await SendFaultMsg(user.Phone, equname, content); - } - _userDBContext.SendUserMsg.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = userId, - MsgId = sendMsgId, - IsSend = isSend, - SendType = (short)SendTypeMeta.SMSMsg, - IsRead = 0, - MsgType = faultMsg.MsgType, - EmergencyType = faultMsg.EmergencyType, - MainId = faultMsg.MainId, - CreateTime = DateTime.Now, - ProjectId = faultMsg.ProjectId - }); - } - } - } - } - catch (Exception ex) - { - _logger.LogError($"{this.GetType().FullName}-->>{userId}SendMsg抛出异常:{ex.Message} {ex.Source} {ex.StackTrace}"); - } - } - await _userDBContext.SaveChangesAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"SendMsg抛出异常:{ex.Message} {ex.Source} {ex.StackTrace} {ex.InnerException}").GetNlogMessage().ToString()); - } - return result; - } - private async Task SendFaultMsg(string phone, string equip, string content) - { - try - { - var accessKey = _configuration["EmpTenantEMS:PrepaidAccessKey"]; - var accessSecret = _configuration["EmpTenantEMS:PrepaidAccessSecret"]; - var url = _configuration["EmpTenantEMS:Url"]; - var msgTemplateId = _configuration["EmpTenantEMS:MsgTemplateId"]; - using var scope = _serviceScopeFactory.CreateScope(); - var tenantEMSService = scope.ServiceProvider.GetRequiredService(); - await tenantEMSService.SendHttpRequest(new Entity.LogicModels.Tenant.TenantSendMsgDto - { - MsgTemplateId = msgTemplateId, - PhoneNums = new List { phone }, - Fields = new Dictionary - { - { "eqname", equip }, - { "remark", content } - } - }, accessKey, accessSecret, url); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("SendFaultMsg", ex).GetNlogMessage()); - } - } - /// - /// 用户上线发送离线消息 - /// - /// - /// - public async Task> UserOnlineSendOffline(long userId) - { - var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = true }; - try - { - var invalidTime = DateTime.Now.AddDays(-5); - var sendUserMsgs = await _userDBContext.SendUserMsg.Where(t => t.UserId == userId && t.SendType == (short)SendTypeMeta.AppMsg && t.IsSend == false && t.CreateTime >= invalidTime).OrderBy(t => t.CreateTime).ToListAsync(); - if (sendUserMsgs.Count() == 0) - { - return result; - } - var msgIds = sendUserMsgs.Select(t => t.MsgId).ToList(); - var sendMsgs = await _userDBContext.SendMsgs.Where(t => msgIds.Contains(t.Id)).Select(t => new - { - t.Id, - t.Title, - t.Content, - t.Payload - }).ToListAsync(); - if (sendMsgs.Count() == 0) - { - return result; - } - var userMapClients = await _userDBContext.UserMapClient.Where(t => t.UserId == userId).Select(t => new - { - t.UserId, - t.ClientId, - t.ServerId, - t.ClientType - }).ToListAsync(); - var userIds = new List { userId }; - foreach (var sendMsg in sendMsgs) - { - var clientIds = userMapClients.Where(t => t.UserId == userId && !string.IsNullOrEmpty(t.ClientId) && t.ClientType == (short)SendTypeMeta.AppMsg).Select(t => t.ClientId).ToList(); - - if (clientIds.Count() > 0) - { - var instance = _uniPushInstance.Instance(userMapClients.FirstOrDefault().ServerId); - if (instance != null) - { - var pushResult = await instance.Push(new MsgPushEntity - { - ClientIds = clientIds, - Body = sendMsg.Content, - Title = sendMsg.Title, - PlayLoad = sendMsg.Payload, - ClickType = 5 - }); - if (pushResult != null && pushResult.Code == 200) - { - var sendUserMsg = sendUserMsgs.FirstOrDefault(t => t.MsgId == sendMsg.Id); - if (sendUserMsg != null) - { - _userDBContext.Entry(sendUserMsg).State = EntityState.Modified; - _userDBContext.Entry(sendUserMsg).Property(o => o.IsSend).IsModified = false; - _userDBContext.Entry(sendUserMsg).Property(o => o.UpdateTime).IsModified = false; - sendUserMsg.IsSend = true; - sendUserMsg.UpdateTime = DateTime.Now; - } - } - } - } - } - await _userDBContext.SaveChangesAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs deleted file mode 100644 index 6b5d97a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/MsgCenterCoreService.cs +++ /dev/null @@ -1,476 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Core.AliYunSms; -using WeiCloud.Core.Common; -using WeiCloud.Core.EnumTools; -using WeiCloud.Core.EventBus; -using WeiCloud.Core.Filters; -using WeiCloud.Core.MsgSocket; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.MsgCenter; -using WeiCloud.Entity.LogicModels.Tenant; -using WeiCloud.Utils.Common; - -namespace WeiCloud.Core.Services.Message -{ - public class MsgCenterCoreService : IMsgCenterCoreService - { - private readonly ILogger _logger; - private readonly WeiCloudDBUserCenterContext _userCenterContext; - private readonly IServiceScopeFactory _serviceScopeFactory; - - private readonly ITenantAccessContextProvider _contextProvider; - public MsgCenterCoreService(ILogger logger, WeiCloudDBUserCenterContext userCenterContext, IServiceScopeFactory serviceScopeFactory, ITenantAccessContextProvider contextProvider) - { - _logger = logger; - _userCenterContext = userCenterContext; - _serviceScopeFactory = serviceScopeFactory; - _contextProvider = contextProvider; - } - /// - /// 发送消息 - /// - /// - /// - public async Task> SendMsg(MsgTempateEventDto input) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - if (input.UserIds == null || !input.UserIds.Any()) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, "用户ID不能为空").GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "用户ID不能为空"; - return result; - } - - - var users = await _userCenterContext.Users.Where(t => input.UserIds.Contains(t.Id)).Select(t => new - { - t.Phone, - t.Id - }).Distinct().ToListAsync(); - - var msgTemplate = _userCenterContext.MsgTemplate.Where(t => t.Id == input.MsgTempateId).AsNoTracking().Select(t => new - { - t.Id, - t.Name, - t.MsgClassId, - t.TemplateType, - t.TemplateContent, - t.IsEnableVoice, - t.VoiceContent, - t.MsgProviderId, - t.Code - }).FirstOrDefault(); - if (msgTemplate == null) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{input.MsgTempateId}消息模板不存在").GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "消息模板不存在"; - return result; - } - - var msgTemplateContent = await GetMsgContentByField(msgTemplate.TemplateContent, input.Fields, msgTemplate.TemplateType, msgTemplate.MsgClassId); - - var sendMsg = new SendMsgs - { - Id = UidGenerator.Uid(), - Title = input.Title, - Content = msgTemplateContent, - Payload = JsonConvert.SerializeObject(input), - CreateTime = DateTime.Now, - MsgTemplateId = msgTemplate.Id - }; - var sendUserMsgs = new List { }; - - - if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.SMS) - { - var phoneNums = users.Where(t => !string.IsNullOrWhiteSpace(t.Phone)).Select(t => t.Phone).Distinct().ToList(); - var msgProvider = _userCenterContext.MsgProvider.Where(t => t.Id == msgTemplate.MsgProviderId && t.ServiceApply == (short)MsgServiceApplyEnum.SMS).AsNoTracking().FirstOrDefault(); - if (msgProvider == null) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "短信服务商不存在"; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{msgTemplate.MsgProviderId}短信服务商不存在").GetNlogMessage().ToString()); - return result; - } - var msgProviderConfig = JsonConvert.DeserializeObject(msgProvider.Extend); - await SendEMS(phoneNums, msgTemplateContent, msgTemplate.MsgClassId, msgProviderConfig); - foreach (var user in users) - { - sendUserMsgs.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = user.Id, - MsgId = sendMsg.Id, - IsSend = true, - SendType = (short)SendTypeMeta.SMSMsg, - IsRead = 0, - CreateTime = DateTime.Now - }); - } - } - else if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.Internal) - { - var pushMethod = $"{msgTemplate.Code}_method"; - var userIds = users.Select(t => t.Id).ToList(); - var resultSendInternalMsg = await SendInternalMsg(sendMsg.Id, userIds, pushMethod, msgTemplateContent, input.Extend, input.Title); - if (resultSendInternalMsg.Code == RequestBackStatuEnum.success.Value && resultSendInternalMsg.Data != null && resultSendInternalMsg.Data.Any()) - { - sendUserMsgs.AddRange(resultSendInternalMsg.Data); - } - } - _userCenterContext.SendMsgs.Add(sendMsg); - _userCenterContext.SendUserMsg.AddRange(sendUserMsgs); - await _userCenterContext.SaveChangesAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"SendMsg:{JsonConvert.SerializeObject(input)}").GetNlogMessage().ToString()); - } - return result; - } - /// - /// 发送消息 - /// - /// - /// - public async Task> TenantSendMsg(InternalTenantSendMsgDto input) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - var msgTemplate = _userCenterContext.MsgTemplate.Where(t => t.Id == input.MsgTemplateId).AsNoTracking().Select(t => new - { - t.Id, - t.Name, - t.MsgClassId, - t.TemplateType, - t.TemplateContent, - t.IsEnableVoice, - t.VoiceContent, - t.MsgProviderId, - t.Code - }).FirstOrDefault(); - if (msgTemplate == null) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{input.MsgTemplateId}消息模板不存在").GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "消息模板不存在"; - return result; - } - - var msgTemplateContent = await GetMsgContentByField(msgTemplate.TemplateContent, input.Fields, msgTemplate.TemplateType, msgTemplate.MsgClassId); - var tenantAccess = _contextProvider.Current; - var sendMsg = new SendMsgs - { - Id = UidGenerator.Uid(), - Title = input.Title, - Content = msgTemplateContent, - Payload = JsonConvert.SerializeObject(input), - CreateTime = DateTime.Now, - MsgTemplateId = msgTemplate.Id - }; - if (string.IsNullOrEmpty(sendMsg.Title)) - {//如果标题为空,则使用模板名称作为标题 - sendMsg.Title = msgTemplate.Name; - } - if (tenantAccess != null) - { - sendMsg.TenantId = tenantAccess.Id; - } - var sendUserMsgs = new List { }; - - if (msgTemplate.TemplateType == (short)MsgTemplateTypeEnum.SMS) - { - if (input.PhoneNums == null || !input.PhoneNums.Any()) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "手机号码不能为空"; - return result; - } - var msgProvider = _userCenterContext.MsgProvider.Where(t => t.Id == msgTemplate.MsgProviderId && t.ServiceApply == (short)MsgServiceApplyEnum.SMS).AsNoTracking().FirstOrDefault(); - if (msgProvider == null) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "短信服务商不存在"; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, $"{msgTemplate.MsgProviderId}短信服务商不存在").GetNlogMessage().ToString()); - return result; - } - var msgProviderConfig = JsonConvert.DeserializeObject(msgProvider.Extend); - await SendEMS(input.PhoneNums, msgTemplateContent, msgTemplate.MsgClassId, msgProviderConfig); - foreach (var phone in input.PhoneNums) - { - sendUserMsgs.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = 0, - Phone = phone, - MsgId = sendMsg.Id, - IsSend = true, - SendType = (short)SendTypeMeta.SMSMsg, - IsRead = 0, - CreateTime = DateTime.Now - }); - } - } - _userCenterContext.SendMsgs.Add(sendMsg); - _userCenterContext.SendUserMsg.AddRange(sendUserMsgs); - await _userCenterContext.SaveChangesAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"SendMsg:{JsonConvert.SerializeObject(input)}").GetNlogMessage().ToString()); - } - return result; - } - private async Task GetMsgContentByField(string orgMsgTemplateContent, JToken fields, short templateType, string msgClassId) - { - var msgTemplateContent = orgMsgTemplateContent; - if (fields != null && !string.IsNullOrWhiteSpace(msgTemplateContent)) - { - var msgPropertys = await _userCenterContext.MsgProperty.Where(t => t.MsgClassId == msgClassId).AsNoTracking().Select(t => new - { - t.Name, - t.Field - }).ToListAsync(); - foreach (var msgProperty in msgPropertys) - { - if (msgTemplateContent.Contains($"${{{msgProperty.Name}}}")) - { - if (fields[msgProperty.Field] != null) - { - var value = fields[msgProperty.Field]; - if (templateType == (short)MsgServiceApplyEnum.SMS) - { - if (value.ToString().Length > 20) - { - value = value.ToString().Substring(0, 20); - } - msgTemplateContent = msgTemplateContent.Replace($"${{{msgProperty.Name}}}", value.ToString()); - } - else - { - msgTemplateContent = msgTemplateContent.Replace($"${{{msgProperty.Name}}}", value.ToString()); - } - } - } - } - } - return msgTemplateContent; - } - private string GetInternalMsgContent(string title, string msgContent, string extend) - { - return $"{{\"title\":\"{title}\",\"content\":\"{msgContent}\",\"extend\":{extend}}}"; - } - /// - /// 发送消息-短信 - /// - /// - /// - /// - /// - /// - private async Task> SendEMS(List phoneNums, string msgContent, string msgClassId, MsgSMSDto msgProviderConfig) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var smsHelperService = scope.ServiceProvider.GetRequiredService(); - - var sign = msgProviderConfig.Signs.FirstOrDefault(); - foreach (var phoneNumber in phoneNums) - { - SmsResposeModel? smsResposeModel = null; - try - { - smsResposeModel = smsHelperService.SendSms(phoneNumber, sign.SignName, sign.TemplateCode, msgContent, msgProviderConfig.ApiKey, msgProviderConfig.SecretKey, msgProviderConfig.Url); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.InnerException, ex.StackTrace)).GetNlogMessage().ToString()); - } - finally - { - var smsRespose = string.Empty; - if (smsResposeModel != null) - { - smsRespose = JsonConvert.SerializeObject(smsResposeModel); - } - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{phoneNumber}发送短信{smsRespose}").GetNlogMessage().ToString()); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{phoneNums.Join(",")}发送成功{msgContent}").GetNlogMessage().ToString()); - } - return result; - } - private async Task>> SendInternalMsg(long sendMsgId, List userIds, string pushMethod, string msgContent, object extend, string title) - { - var sendUserMsgs = new List { }; - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = sendUserMsgs }; - try - { - //var sendContent = $"{{\"title\":\"{title}\",\"content\":\"{msgContent}\",\"extend\":{JsonConvert.SerializeObject(extend)}}}"; - var sendContent = GetInternalMsgContent(title, msgContent, JsonConvert.SerializeObject(extend)); - using var scope = _serviceScopeFactory.CreateScope(); - var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); - var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); - foreach (var userId in userIds) - { - var isSend = false; - var keys = await msgWebSocketClientInstance.GetClientIds(userId, pushMethod, string.Empty); - Console.WriteLine($"发送:{userId}" + JsonConvert.SerializeObject(keys)); - if (keys != null && keys.Any()) - { - foreach (var key in keys) - { - await myWebSocketHandler.SendMessageAsync(key, sendContent); - } - isSend = true; - } - - sendUserMsgs.Add(new SendUserMsg - { - Id = UidGenerator.Uid(), - UserId = userId, - MsgId = sendMsgId, - IsSend = isSend, - SendType = (short)SendTypeMeta.PcMsg, - IsRead = 0, - CreateTime = DateTime.Now - }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - } - finally - { - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{userIds.Join(",")}发送成功{msgContent}").GetNlogMessage().ToString()); - } - return result; - } - /// - /// 重发消息 - /// - /// - /// - public async Task> ResendInternalMsg(long userId) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - var payloads = await (from sum in _userCenterContext.SendUserMsg - join sm in _userCenterContext.SendMsgs on sum.MsgId equals sm.Id - join mt in _userCenterContext.MsgTemplate on sm.MsgTemplateId equals mt.Id - where sum.UserId == userId && sum.IsSend == false && mt.TemplateType == (short)MsgTemplateTypeEnum.Internal - && sum.CreateTime >= DateTime.Now.AddDays(-3) && sum.Retries <= 10 - orderby sum.CreateTime ascending - select new - { - sm.Payload, - MsgTemplateId = mt.Id, - SendUserMsgId = sum.Id, - mt.TemplateContent, - mt.TemplateType, - mt.MsgClassId, - mt.Code - }).ToListAsync(); - if (!payloads.Any()) - { - return result; - } - - using var scope = _serviceScopeFactory.CreateScope(); - var myWebSocketHandler = scope.ServiceProvider.GetRequiredService(); - var msgWebSocketClientInstance = scope.ServiceProvider.GetRequiredService(); - - var sendUserMsgIds = payloads.Select(t => t.SendUserMsgId).ToList(); - var sendUserMsgs = await _userCenterContext.SendUserMsg.Where(t => sendUserMsgIds.Contains(t.Id)).ToListAsync(); - - foreach (var payload in payloads) - { - try - { - MsgTempateEventDto msg = JsonConvert.DeserializeObject(payload.Payload); - var msgContent = await GetMsgContentByField(payload.TemplateContent, msg.Fields, payload.TemplateType, payload.MsgClassId); - var extend = string.Empty; - if (msg.Extend != null) - { - extend = JsonConvert.SerializeObject(msg.Extend); - } - var sendContent = GetInternalMsgContent(msg.Title, msgContent, extend); - var pushMethod = $"{payload.Code}_method"; - var isSend = false; - var keys = await msgWebSocketClientInstance.GetClientIds(userId, pushMethod, string.Empty); - - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, $"{userId}重新发送站内消息{JsonConvert.SerializeObject(keys)}").GetNlogMessage().ToString()); - if (keys != null && keys.Any()) - { - foreach (var key in keys) - { - await myWebSocketHandler.SendMessageAsync(key, sendContent); - } - isSend = true; - } - var sendUserMsg = sendUserMsgs.FirstOrDefault(t => t.Id == payload.SendUserMsgId); - _userCenterContext.SendUserMsg.Attach(sendUserMsg); - _userCenterContext.Entry(sendUserMsg).Property(u => u.UpdateTime).IsModified = true; - _userCenterContext.Entry(sendUserMsg).Property(u => u.Retries).IsModified = true; - if (isSend) - { - _userCenterContext.Entry(sendUserMsg).Property(u => u.IsSend).IsModified = true; - sendUserMsg.IsSend = isSend; - } - sendUserMsg.UpdateTime = DateTime.Now; - sendUserMsg.Retries += 1; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - await _userCenterContext.SaveChangesAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - result.Code = RequestBackStatuEnum.fail.Value; - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs deleted file mode 100644 index d72ef6a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Message/UniPushInstance.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Msg.Core.Model; -using Msg.Core.UniPush; -using System; -using System.Collections.Concurrent; -using System.Linq; - -namespace WeiCloud.Core.Services.Message -{ - public class UniPushInstance - { - private readonly ConcurrentDictionary instances = new ConcurrentDictionary(); - - private readonly UniPushGeTui _uniPushGeTui; - private readonly ILogger _logger; - public UniPushInstance(UniPushGeTui uniPushGeTui, ILogger logger) - { - _uniPushGeTui = uniPushGeTui; - _logger = logger; - } - public UniPushUtilV02 Instance(string appName) - { - var instance = instances.GetOrAdd(appName, key => - { - try - { - var pushConfig = _uniPushGeTui.Configs.FirstOrDefault(t => t.AppName == appName); - var instance = new UniPushUtilV02(_uniPushGeTui.Url, pushConfig.AppId, pushConfig.AppKey, pushConfig.MasterSecret, pushConfig.TTL); - return instance; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return null; - }); - return instance; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs deleted file mode 100644 index 3440279..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleManagerCoreService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.SysModule; - -namespace WeiCloud.Core.Services -{ - public interface IModuleManagerCoreService - { - Task> GetProjectSysModule(List projectIds); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs deleted file mode 100644 index 5b7ad5b..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/IModuleMenuCoreService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public interface IModuleMenuCoreService - { - Task> GetProjectMenusLevel1(List projectIds, List sysModuleIds); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs deleted file mode 100644 index 134af7a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleManagerCoreService.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.SysModule; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public class ModuleManagerCoreService : IModuleManagerCoreService - { - private readonly WeiCloudDBUserCenterContext _context; - private readonly IDictionaryService _dictionaryService; - private readonly ILogger _logger; - - public ModuleManagerCoreService(WeiCloudDBUserCenterContext context, ILogger logger, IDictionaryService dictionaryService) - { - _context = context; - _logger = logger; - _dictionaryService = dictionaryService; - } - /// - /// 项目获取所有模块 - /// - /// - /// - public async Task> GetProjectSysModule(List projectIds) - { - var query = from sm in _context.SysModule - join psm in _context.ProjectSysModule on sm.Id equals psm.Sysmoduleid - into tmp - from smpsm in tmp.DefaultIfEmpty() - where sm.Sysid == 0 || (sm.Sysid == 2 && smpsm.Isenable == true && projectIds.Contains(smpsm.Projectid)) - select new ProjectSysModuleModel - { - SysModuleId = sm.Id, - SysModuleName = sm.Name, - ProjectId = smpsm == null ? 0 : smpsm.Projectid, - PackageName = sm.Packagename, - ActiveRule = sm.Activerule, - SysId = sm.Sysid, - Order = smpsm == null ? (short)0 : smpsm.Order, - SysModelType = sm.Sysmodeltype - }; - var items = await query.OrderBy(t => t.Order).ToListAsync(); - return items; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs deleted file mode 100644 index 4eaf781..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Module/ModuleMenuCoreService.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public class ModuleMenuCoreService: IModuleMenuCoreService - { - private readonly WeiCloudDBUserCenterContext _context; - private readonly ILogger _logger; - - public ModuleMenuCoreService(WeiCloudDBUserCenterContext context, ILogger logger) - { - _context = context; - _logger = logger; - } - /// - /// 一级菜单 - /// - /// - /// - /// - public async Task> GetProjectMenusLevel1(List projectIds, List sysModuleIds) - { - var projectMenusQuery = _context.ProjectMenu.Where(t => t.Isusing == 1 && t.Parentid == 0); //_context.ProjectMenu.Where(t => t.Isusing == 1 && t.Projectid == projectId && sysModuleIds.Contains(t.Sysmoduleid) && t.Parentid == 0); - if (projectIds != null && projectIds.Count() > 0) - { - projectMenusQuery = projectMenusQuery.Where(t => projectIds.Contains(t.Projectid)); - } - if (sysModuleIds != null && sysModuleIds.Count() > 0) - { - projectMenusQuery = projectMenusQuery.Where(t => sysModuleIds.Contains(t.Sysmoduleid)); - } - return await projectMenusQuery.ToListAsync(); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs deleted file mode 100644 index 3936b5c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/IMsgService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.Context.AirDB; - -namespace WeiCloud.Core -{ - public interface IMsgService - { - Task PushFaultMsg(TbFaultHistory tbFaultHistory); - Task PushNoticeInfoMsg(SendInfoGic info); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs deleted file mode 100644 index 40e3940..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Msg/MsgService.cs +++ /dev/null @@ -1,163 +0,0 @@ -using Microsoft.Extensions.Logging; -using WeiCloud.Core.EventBus; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core; -using WeiCloud.Entity; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.UserCenter; -using Microsoft.Extensions.Configuration; - -namespace WeiCloud.Core -{ - public class MsgService : IMsgService - { - private readonly ILogger _logger; - private readonly IDictionaryService _dictionaryService; - - private readonly IPublisherService _publisherService; - public MsgService(ILogger logger, IDictionaryService dictionaryService, IConfiguration configuration, IPublisherService publisherService) - { - _logger = logger; - _dictionaryService = dictionaryService; - - _publisherService = publisherService; - } - public async Task PushFaultMsg(TbFaultHistory tbFaultHistory) - { - try - { - if (tbFaultHistory.Projectid == null) - { - return; - } - var projectInfo = _dictionaryService.GetValue(typeof(ProjectInfo).Name)[tbFaultHistory.Projectid.ToString()]; - - var userCache = _dictionaryService.GetValue(typeof(Users).Name); - var userCacheKeys = userCache.Keys; - var users = new List { }; - - foreach (var userCacheKey in userCacheKeys) - { - var user = userCache[userCacheKey]; - if (user.Isusing == 1) - { - users.Add(user); - } - } - if (users.Count() == 0) - { - return; - } - - var userIds = new List { }; - var userGroupCache = _dictionaryService.GetValue(typeof(UserGroups).Name); - var userGroupCacheKeys = userGroupCache.Keys; - foreach (var userGroupCacheKey in userGroupCacheKeys) - { - var userGroup = userGroupCache[userGroupCacheKey]; - if (userGroup.Isusing == 1 && userGroup.Ownerid == projectInfo.Ownerid) - { - var _userIds = users.Where(t => (t.UniClientId == null || t.UniClientId == "0") && t.Usergroup != null && t.Usergroup == userGroup.Id).Select(t => t.Id).ToList(); - if (_userIds.Count() > 0) - { - userIds.AddRange(_userIds); - } - } - } - if (userIds.Count() == 0) - { - return; - } - userIds = userIds.Distinct().ToList(); - - - var equip = _dictionaryService.GetValue("EquipmentInfo", new string[] { tbFaultHistory.Eqid.ToString() }).FirstOrDefault().Value; - - var msgObj = new ProduceMsgModel - { - EquId = tbFaultHistory.Eqid, - Id = tbFaultHistory.Id, - Title = "设备报警", - Content = tbFaultHistory.Faudesc, - ProjectId = tbFaultHistory.Projectid, - //UserIds = users.Select(t => t.Id).Distinct().ToList(), - UserIds = userIds, - SendTypes = new List { (int)SendTypeMeta.PcMsg }, - MsgTopic = "", - EmergencyType = 0, - MainId = tbFaultHistory.Id, - MsgType = 3, - ProjectName = projectInfo.Projectname, - ProjectShortName = projectInfo.Shortname, - EquName = equip.Eqname - }; - await _publisherService.PublishNoticeMsg(msgObj); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("PushFaultMsg", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); - } - } - public async Task PushNoticeInfoMsg(SendInfoGic info) - { - List userIdList = new List(); - try - { - string[] userId = info.UserId.Split(','); - if (userId != null && userId.Count() > 0) - { - foreach (var s in userId) - { - if (!string.IsNullOrEmpty(s)) - { - var id = long.Parse(s); - if (id > 0) - { - userIdList.Add(id); - } - } - } - } - - if (userIdList.Count == 0) - { - return; - } - userIdList = userIdList.Distinct().ToList(); - var projectInfo = _dictionaryService.GetValue(typeof(ProjectInfo).Name, new String[] { info.ProjectId.ToString() }).FirstOrDefault().Value; - - var msgObj = new ProduceMsgModel - { - EquId = 0, - Id = info.Id, - Title = info.Title, - Content = info.Message, - ProjectId = info.ProjectId, - //UserIds = users.Select(t => t.Id).Distinct().ToList(), - UserIds = userIdList, - //SendTypes = new List { (int)SendTypeMeta.AppMsg, (int)SendTypeMeta.PcMsg } - SendTypes = info.SendType, - EmergencyType = 0, - MainId = info.Id, - MsgType = 4, - ProjectName = projectInfo.Projectname, - ProjectShortName = projectInfo.Projectname, - EquName = "" - }; - await _publisherService.PublishNoticeMsg(msgObj); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("PushNoticeInfoMsg 推送异常", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs deleted file mode 100644 index 3bb10ee..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/NlogCoreService.cs +++ /dev/null @@ -1,299 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils.Common; -using WeiCloud.Entity.Context.UserCenter; -using Microsoft.Extensions.DependencyInjection; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.InfoModels; -using Microsoft.Extensions.Configuration; -using Microsoft.AspNetCore.JsonPatch.Internal; -using NPOI.XSSF.UserModel; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using System.Net.Http; -using Newtonsoft.Json; - -namespace WeiCloud.Core.Services -{ - public class NlogCoreService : WeiCloud.Core.BaseCore.Grain, INlogCoreService - { - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly ILogger _logger; - public NlogCoreService(IServiceScopeFactory serviceScopeFactory, ILogger logger) - { - _serviceScopeFactory = serviceScopeFactory; - _logger = logger; - } - //获取内网IP - private IPAddress GetInternalIP() - { - NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); - - foreach (NetworkInterface adapter in nics) - { - foreach (var uni in adapter.GetIPProperties().UnicastAddresses) - { - if (uni.Address.AddressFamily == AddressFamily.InterNetwork) - { - return uni.Address; - } - } - } - return null; - } - /// - /// 日志写入数据库 - /// - /// 日志实体 - /// 操作结果值 - public async Task PostNlogsParam(string actionName, int? type, string oldValue, string newValue, string message, long operatorId = 0, string operatorName = "") - { - var result = true; - long userId = operatorId; - string userName = operatorName; - if (userId == 0) - { - var currentUser = CurrentContext.GetContext(); - userId = currentUser.UserId; - userName = currentUser.UserName; - } - if (string.IsNullOrEmpty(userName)) - { - userName = "无"; - } - Nlog log = new Nlog(); - try - { - log.Id = UidGenerator.Uid(); - log.MachineIp = GetInternalIP().ToString(); - log.CreateUserId = userId; - log.CreateTime = DateTime.Now;//创建时间 - log.ActionName = actionName; - log.LogType = type; - log.OldParmValue = oldValue; - log.NewParmValue = newValue; - log.Message = message; - log.CreateUserName = userName; - using var scope = _serviceScopeFactory.CreateScope(); - var _context = scope.ServiceProvider.GetRequiredService(); - _context.Nlog.Add(log); - //数据库中更新用户状态 - await _context.SaveChangesAsync(); - } - catch (Exception ex) - { - result = false; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " PostNlogsParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - /// - /// - /// - /// - /// - public async Task> UpdateOrAndNlogs(List nlogs) - { - var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value }; - if (nlogs == null || nlogs.Count() == 0) - { - return result; - } - using var scope = _serviceScopeFactory.CreateScope(); - var configuration = scope.ServiceProvider.GetRequiredService(); - var _context = scope.ServiceProvider.GetRequiredService(); - long userId = 0; - string userName = string.Empty; - string remoteIPAddress = string.Empty; - var nlog = nlogs.FirstOrDefault(t => t.CreateUserId > 0); - var currentUser = CurrentContext.GetContext(); - remoteIPAddress = currentUser.RemoteIPAddress; - if (nlog == null) - { - try - { - userId = currentUser.UserId; - userName = currentUser.UserName; - } - catch (Exception ex) - { - _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}"); - } - } - else - { - userId = nlog.CreateUserId; - userName = nlog.CreateUserName; - } - - try - { - foreach (var item in nlogs) - { - var log = new Nlog() - { - Id = item.Id == 0 ? UidGenerator.Uid() : item.Id, - ActionName = item.ActionName, - CreateUserId = userId, - CreateUserName = userName ?? "", - MachineIp = remoteIPAddress, - ProjectId = item.ProjectId, - EquipId = item.EquipId, - Message = item.Message, - LogType = item.LogType, - Parameter = item.Parameter, - OldParmValue = item.OldParmValue, - NewParmValue = item.NewParmValue, - CreateTime = DateTime.Now, - TerminalType = item.TerminalType, - EndDateTime = item.EndDateTime, - IphomePlace = item.IphomePlace, - }; - _context.Add(log); - } - var sqlint = _context.SaveChanges(); - result.Code = sqlint > 0 ? RequestBackStatuEnum.success.Value : RequestBackStatuEnum.fail.Value; - result.Data = sqlint; - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = ex.Message; - _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}--InnerEx:{ex.InnerException}"); - } - return result; - } - public async Task> UpdateOrAndNlogs(CmdNlogBoNew item) - { - var result = new ApiResult() { Code = RequestBackStatuEnum.success.Value }; - using var scope = _serviceScopeFactory.CreateScope(); - var _context = scope.ServiceProvider.GetRequiredService(); - try - { - - var nlog = new Nlog() - { - Id = item.Id == 0 ? UidGenerator.Uid() : item.Id, - ActionName = item.ActionName, - CreateUserId = item.CreateUserId, - CreateUserName = item.CreateUserName, - MachineIp = item.MachineIp, - ProjectId = item.ProjectId, - EquipId = item.EquipId, - Message = item.Message, - LogType = item.LogType, - Parameter = item.Parameter, - OldParmValue = item.OldParmValue, - NewParmValue = item.NewParmValue, - CreateTime = DateTime.Now, - TerminalType = item.TerminalType, - EndDateTime = item.EndDateTime, - IphomePlace = item.IphomePlace, - }; - _context.Add(nlog); - var sqlint = _context.SaveChanges(); - result.Code = sqlint > 0 ? RequestBackStatuEnum.success.Value : RequestBackStatuEnum.fail.Value; - result.Data = sqlint; - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = ex.Message; - _logger.LogError($"{this.GetType().FullName}-->>UpdateOrAndNlogs抛出异常:ex:{ex.Message}"); - } - return result; - } - /// - /// 添加日志 - /// - /// - /// - public async Task> UpdateOrAndNlog(CmdNlogBoNew item) - { - var result = await UpdateOrAndNlogs(new List { item }); - return result; - } - public async Task> GetIPHomePlaces(List ips) - { - var ipHomePlaceDic = new Dictionary { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var configuration = scope.ServiceProvider.GetRequiredService(); - var httpCilent = scope.ServiceProvider.GetRequiredService(); - var requestIPHomePlaceUrl = configuration["SysLog:IPHomePlace"]; - var userCenterDB = scope.ServiceProvider.GetRequiredService(); - var ipHomePlaces = await userCenterDB.IphomePlace.Where(t => ips.Contains(t.Ipaddress)).AsNoTracking().ToListAsync(); - var newIphomePlaces = new List { }; - foreach (var ip in ips) - { - if (string.IsNullOrEmpty(ip) || newIphomePlaces.Any(t => t.Ipaddress == ip)) - { - continue; - } - var ipHomePlace = ipHomePlaces.FirstOrDefault(t => t.Ipaddress == ip); - if (ipHomePlace == null && !string.IsNullOrEmpty(requestIPHomePlaceUrl)) - { - #region 获取归属IP地址 - try - { - var apiUrl = requestIPHomePlaceUrl + $"?query={ip}&co=&resource_id=6006&oe=utf8"; - var client = httpCilent.CreateClient(); - client.Timeout = TimeSpan.FromSeconds(1); - var httpResponse = await client.GetAsync(apiUrl); - var responseBody = string.Empty; - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - responseBody = await httpResponse.Content.ReadAsStringAsync(); - var responseBodyObj = JsonConvert.DeserializeObject(responseBody); - if (responseBodyObj != null && responseBodyObj.data != null && responseBodyObj.data.Count() > 0) - { - newIphomePlaces.Add(new IphomePlace - { - Ipaddress = ip, - HomePlace = responseBodyObj.data.FirstOrDefault().location - }); - ipHomePlaceDic.TryAdd(ip, responseBodyObj.data.FirstOrDefault().location); - } - } - } - catch (Exception) - { - } - #endregion - } - else - { - ipHomePlaceDic.TryAdd(ip, ipHomePlace.HomePlace); - } - } - if (newIphomePlaces.Count > 0) - { - userCenterDB.IphomePlace.AddRange(newIphomePlaces); - await userCenterDB.SaveChangesAsync(); - } - } - catch (Exception ex) - { - _logger.LogError($"{this.GetType().FullName}-->>抛出异常:ex:{ex.Message}"); - } - return ipHomePlaceDic; - } - } -} -internal class IpHomePlaceModel -{ - public List data { get; set; } -} -internal class IpHomePlaceDataModel -{ - public string location { get; set; } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs deleted file mode 100644 index 77e80ef..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/FunPermissionCoreService.cs +++ /dev/null @@ -1,100 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Utils.RedisUtil; - -namespace WeiCloud.Core.Services.Permission -{ - public class FunPermissionCoreService : WeiCloud.Core.BaseCore.Grain, IFunPermissionCoreService - { - private readonly WeiCloudDBUserCenterContext _context; - private readonly IStringService _stringService; - private readonly ILogger _logger; - public FunPermissionCoreService(IStringService stringService, WeiCloudDBUserCenterContext context, ILogger logger) - { - _logger = logger; - _context = context; - _stringService = stringService; - } - - /// - /// 获取当前人角色权限 - /// - /// - public async Task> GetCurrentUserFunPermissions() - { - var currentUser = CurrentContext.GetContext(); - List result = null; - try - { - result = _stringService.Get>(string.Format(FamilyDecorationEnum.RoleFunPermissionCacheKey, currentUser.RoleId)); - if (result == null) - { - result = await _context.RoleFunPermission.Where(t => t.RoleId == currentUser.RoleId).AsNoTracking().Select(t => t.FunPermissionId).ToListAsync(); - _stringService.Set(string.Format(FamilyDecorationEnum.RoleFunPermissionCacheKey, currentUser.RoleId), result, 3600); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return result; - } - /// - /// 获取用户的权限 - /// - /// - public async Task GetCurrentUserFun(long projectId, string path) - { - var currentUser = CurrentContext.GetContext(); - List funIds = new List(); - long result = 1; - try - { - if (projectId == 0) - { - var prof = await _context.ProjectFunPermission.Where(d => d.Address.Contains(path)).FirstOrDefaultAsync(); - if (prof != null) - { - projectId = prof.ProjectId; - } - } - //查询当前用户的菜单 - //var data = await (from f in _context.ProjectFunPermission join p in _context.ProjectMenu on f.MenuId equals p.Menuid where p.Projectid == projectId && f.Address == path select f).ToListAsync(); - var data = await (from f in _context.ProjectFunPermission where f.ProjectId == projectId && f.Address == path select f).ToListAsync(); - if (data == null || data.Count == 0)//菜单没有设置权限 - { - return 1; - } - funIds = data.Select(d => d.Id).ToList(); - //查找角色的功能权限是否存在 - var pr = await (from r in _context.RoleFunPermission - join p in _context.ProjectFunPermission on r.FunPermissionId equals p.Id - where r.RoleId == currentUser.RoleId && funIds.Contains(p.Id) && p.Address == path - select p).ToListAsync(); - if (pr != null && pr.Count > 0) - { - result = 1; - } - else - { - result = 0; - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs deleted file mode 100644 index a4cfd4a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Permission/IFunPermissionCoreService.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; - -namespace WeiCloud.Core.Services.Permission -{ - public interface IFunPermissionCoreService - { - Task> GetCurrentUserFunPermissions(); - Task GetCurrentUserFun(long projectId,string path); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs deleted file mode 100644 index 152c391..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/PermissionsGainCoreService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class PermissionsGainCoreService: IPermissionsGainCoreService - { - private readonly IListService _listService; - private readonly IDictionaryService _dictionaryService; - public PermissionsGainCoreService(IListService listService, IDictionaryService dictionaryService) - { - _listService = listService; - _dictionaryService = dictionaryService; - } - /// - /// 获取全部权限清单 - /// - /// - public async Task> GetAllPermissionsRedis() - { - Permissions press = new Permissions(); - var result = _dictionaryService.GetValue(press.GetType().Name); - var list = result.Values.ToList(); - return await Task.FromResult(list); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs deleted file mode 100644 index 9d8dd3c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/PredicateBuilder.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Text; - -namespace WeiCloud.Core.Services -{ - public static class PredicateBuilder - { - public static Expression> True() { return x => true; } - - public static Expression> False() { return x => false; } - - public static Expression> Or( - this Expression> expr1, - Expression> expr2) - { - var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); - return Expression.Lambda>( - Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); - } - - public static Expression> And( - this Expression> expr1, - Expression> expr2) - { - var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); - return Expression.Lambda>( - Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters); - } - } - -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs deleted file mode 100644 index c5b363a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/IProAlarmService.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.SafetyFirePro; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.ProjectAlarm; - -namespace WeiCloud.Core.Services.ProAlarm -{ - public interface IProAlarmService - { - Task> ArrearsAlarm(string msg, long ammeterId, short state, DateTime alarmTime); - Task> SaveAlarm(List inputs); - Task> SaveEnergyAduitAlarm(long optionId, string msg, DateTime alarmTime); - Task> SaveFaultAlarm(List tbFaultHistorys); - Task> SaveSafetyFireProtectFaultAlarm(List faultHistorys); - Task> TestSaveFaultAlarm(DateTime startTime, DateTime endTime, long projectId); - Task> UpdateAlarmState(long id, short state); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs deleted file mode 100644 index c5d479a..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ProAlarm/ProAlarmService.cs +++ /dev/null @@ -1,418 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Org.BouncyCastle.Tls; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.SafetyFirePro; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.ProjectAlarm; -using WeiCloud.Entity.Models.Sysconfig; -using WeiCloud.Utils.Common; -namespace WeiCloud.Core.Services.ProAlarm -{ - public class ProAlarmService : IProAlarmService - { - private readonly WeiCloudDBContext _dbContext; - private readonly ILogger _logger; - private readonly IServiceScopeFactory _serviceScopeFactory; - public ProAlarmService(WeiCloudDBContext dbContext, ILogger logger, IServiceScopeFactory serviceScopeFactory) - { - _dbContext = dbContext; - _logger = logger; - _serviceScopeFactory = serviceScopeFactory; - } - /// - /// 保存报警信息 - /// - /// - /// - public async Task> SaveAlarm(List inputs) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - if (inputs == null || !inputs.Any()) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "没有需要保存的报警信息"; - return result; - } - var mapIds = inputs.Select(t => t.MapId).ToList(); - var exitProAlarms = await _dbContext.ProAlarm.Where(t => mapIds.Contains(t.MapId)).ToListAsync(); - foreach (var input in inputs) - { - var proAlarm = exitProAlarms.FirstOrDefault(t => t.MapId == input.MapId); - if (proAlarm == null) - { - proAlarm = new WeiCloud.Entity.Context.DB.ProAlarm - { - Id = UidGenerator.Uid(), - AlarmType = input.AlarmType, - AlarmLevel = input.AlarmLevel, - Theme = input.Theme, - Content = input.Content, - AlarmTime = input.AlarmTime, - State = input.State, - MapId = input.MapId, - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - AlarmProcessedTime = input.ProcessTime - }; - await _dbContext.ProAlarm.AddAsync(proAlarm); - } - else - { - // 更新已存在的报警信息 - proAlarm.Theme = input.Theme; - proAlarm.Content = input.Content; - proAlarm.UpdateTime = DateTime.Now; - proAlarm.AlarmProcessedTime = input.ProcessTime; - proAlarm.State = input.State; - _dbContext.Attach(proAlarm).State = EntityState.Modified; - _dbContext.Entry(proAlarm).Property(t => t.Theme).IsModified = true; - _dbContext.Entry(proAlarm).Property(t => t.Content).IsModified = true; - _dbContext.Entry(proAlarm).Property(t => t.UpdateTime).IsModified = true; - _dbContext.Entry(proAlarm).Property(t => t.AlarmProcessedTime).IsModified = true; - _dbContext.Entry(proAlarm).Property(t => t.State).IsModified = true; - } - await _dbContext.SaveChangesAsync(); - } - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); - } - return result; - } - /// - /// 更新报警状态 - /// - /// - /// - /// - public async Task> UpdateAlarmState(long id, short state) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - var proAlarm = await _dbContext.ProAlarm.FirstOrDefaultAsync(t => t.MapId == id); - if (proAlarm == null) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "未找到对应的报警信息"; - return result; - } - proAlarm.State = state; - proAlarm.UpdateTime = DateTime.Now; - _dbContext.Attach(proAlarm).State = EntityState.Modified; - _dbContext.Entry(proAlarm).Property(t => t.State).IsModified = true; - await _dbContext.SaveChangesAsync(); - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); - } - return result; - } - /// - /// 保存故障报警信息-- 设备报警 - /// - /// - /// - public async Task> SaveFaultAlarm(List tbFaultHistorys) - { - var fauClassIds = tbFaultHistorys.Select(t => t.Fauclass ?? 0).Distinct().ToList(); - var faultClasss = await _dbContext.TbFaultClass.Where(t => fauClassIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - var alarms = new List { }; - var faultIds = tbFaultHistorys.Select(t => t.Id).ToList(); - var faultHandles = await _dbContext.TbFaultHandle.Where(t => t.Faultid != null && faultIds.Contains((long)t.Faultid)).Select(t => new - { - t.Faultid, - t.Handletime - }).ToListAsync(); - foreach (var tbFaultHistory in tbFaultHistorys) - { - var faultClass = faultClasss.FirstOrDefault(t => t.Id == tbFaultHistory.Fauclass.GetValueOrDefault()); - var alarmLevel = (short)ProAlarmLevelEnum.Warning; - if (faultClass != null) - { - if (faultClass.Classname.Contains("重大")) - { - alarmLevel = (short)ProAlarmLevelEnum.Critical; - } - else if (faultClass.Classname.Contains("严重")) - { - alarmLevel = (short)ProAlarmLevelEnum.Major; - } - else if (faultClass.Classname.Contains("一般")) - { - alarmLevel = (short)ProAlarmLevelEnum.Minor; - } - else if (faultClass.Classname.Contains("轻微")) - { - alarmLevel = (short)ProAlarmLevelEnum.Warning; - } - } - var state = (short)ProAlarmStatus.Unhandled; - if (tbFaultHistory.Status == 1) - { - state = (short)ProAlarmStatus.Unhandled; - } - else if (tbFaultHistory.Status == 2) - { - state = (short)ProAlarmStatus.NoActionRequired; - } - else if (tbFaultHistory.Status == 3) - { - state = (short)ProAlarmStatus.InProgress; - } - else if (tbFaultHistory.Status == 4 || tbFaultHistory.Status == 5) - { - state = (short)ProAlarmStatus.Completed; - } - else if (tbFaultHistory.Status == 6) - { - state = (short)ProAlarmStatus.FalseAlarm; - } - var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto - { - AlarmType = "Fault_Alarm", - AlarmLevel = alarmLevel, - Theme = "故障报警", - Content = tbFaultHistory.Faudesc, - AlarmTime = tbFaultHistory.Createtime.GetValueOrDefault(), - State = state, - MapId = tbFaultHistory.Id - }; - - var handleTime = faultHandles.FirstOrDefault(t => t.Faultid == tbFaultHistory.Id); - if (handleTime != null && handleTime.Handletime.HasValue) - { - alarm.ProcessTime = handleTime.Handletime.Value; - state = (short)ProAlarmStatus.Completed; - } - alarms.Add(alarm); - } - var result = await SaveAlarm(alarms); - return result; - } - /// - /// 保存欠费报警信息 - /// - /// - /// - /// 1-报警、2-已处理 - /// - /// - public async Task> ArrearsAlarm(string msg, long ammeterId, short state, DateTime alarmTime) - { - var alarms = new List { }; - var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto - { - AlarmType = "Arrears_Warning", - AlarmLevel = (short)ProAlarmLevelEnum.Major, - Theme = "欠费报警", - Content = msg, - AlarmTime = alarmTime, - //State = (short)ProAlarmStatus.Unhandled, - MapId = ammeterId - }; - if (state == 1) - { - alarm.State = (short)ProAlarmStatus.Unhandled; - } - else if (state == 2) - { - alarm.State = (short)ProAlarmStatus.Completed; - alarm.ProcessTime = DateTime.Now; - } - alarms.Add(alarm); - var result = await SaveAlarm(alarms); - return result; - } - /// - /// 保存能源体检报警信息 - /// - /// - /// - /// - /// - public async Task> SaveEnergyAduitAlarm(long optionId, string msg, DateTime alarmTime) - { - var alarms = new List { }; - var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto - { - AlarmType = "Physical_Warning", - AlarmLevel = (short)ProAlarmLevelEnum.Major, - Theme = "能源体检", - Content = msg, - AlarmTime = alarmTime, - MapId = optionId - }; - alarm.State = (short)ProAlarmStatus.NoActionRequired; - alarm.ProcessTime = alarmTime; - alarms.Add(alarm); - var result = await SaveAlarm(alarms); - return result; - } - /// - /// 保存安消报警信息 - /// - /// - /// - public async Task> SaveSafetyFireProtectFaultAlarm(List faultHistorys) - { - if (!faultHistorys.Any()) - { - return new ApiResult - { - Code = RequestBackStatuEnum.fail.Value, - Msg = "没有需要保存的安消报警信息" - }; - } - using var scope = _serviceScopeFactory.CreateScope(); - var safetyFireProContext = scope.ServiceProvider.GetRequiredService(); - //"AlarmLevel,AlarmStatus,AlarmAcceptRes" - var alarmLevelKey = "AlarmLevel"; - var alarmStatusKey = "AlarmStatus"; - var alarmAcceptResKey = "AlarmAcceptRes"; - //报警枚举 - var axSysConfigs = await safetyFireProContext.AxSysConfig.Where(t => t.Key == alarmLevelKey || t.Key == alarmStatusKey || t.Key == alarmAcceptResKey).AsNoTracking().Select(t => new - { - t.Key, - t.KeyMemo, - t.Value - }).ToListAsync(); - var dictionary = new Dictionary>(); - foreach (var axSysConfig in axSysConfigs) - { - dictionary.Add(axSysConfig.Key, JsonConvert.DeserializeObject>(axSysConfig.Value)); - } - - var alarms = new List { }; - - foreach (var faultHistory in faultHistorys) - { - dictionary.TryGetValue(alarmLevelKey, out var alarmLevelList); - var alarmLevel = (short)ProAlarmLevelEnum.Warning; - if (alarmLevelList != null) - { - var axAlarmLevel = alarmLevelList.FirstOrDefault(t => t.Key == faultHistory.Level); - if (axAlarmLevel != null) - { - if (axAlarmLevel.Value.Contains("重大") || axAlarmLevel.Value.Contains("紧急")) - { - alarmLevel = (short)ProAlarmLevelEnum.Critical; - } - else if (axAlarmLevel.Value.Contains("重要")) - { - alarmLevel = (short)ProAlarmLevelEnum.Major; - } - else if (axAlarmLevel.Value.Contains("一般")) - { - alarmLevel = (short)ProAlarmLevelEnum.Minor; - } - else if (axAlarmLevel.Value.Contains("轻微")) - { - alarmLevel = (short)ProAlarmLevelEnum.Warning; - } - } - } - - - dictionary.TryGetValue(alarmStatusKey, out var alarmStatusList); - dictionary.TryGetValue(alarmAcceptResKey, out var alarmAcceptResList); - DateTime? processTime = null;//处理时间 - var state = (short)ProAlarmStatus.Unhandled; - - if (faultHistory.Status == 1) - { - state = (short)ProAlarmStatus.Unhandled; - } - else if (faultHistory.Status == 1 || faultHistory.Status == 2) - { - state = (short)ProAlarmStatus.InProgress; - } - else if (faultHistory.Status == 3) - { - state = (short)ProAlarmStatus.Completed; - processTime = faultHistory.DisposalTime; - } - //if (faultHistory.AcceptRes == 1) - //{ - // state = (short)ProAlarmStatus.InProgress; - //} - //else if (faultHistory.AcceptRes == 2) - //{ - // state = (short)ProAlarmStatus.NoActionRequired; - // processTime = faultHistory.ResponseTime; - //} - //else if (faultHistory.AcceptRes == 3) - //{ - // state = (short)ProAlarmStatus.FalseAlarm; - // processTime = faultHistory.ResponseTime; - //} - if (faultHistory.AcceptRes == 2) - { - state = (short)ProAlarmStatus.NoActionRequired; - processTime = faultHistory.ResponseTime; - } - else if (faultHistory.AcceptRes == 3) - { - state = (short)ProAlarmStatus.FalseAlarm; - processTime = faultHistory.ResponseTime; - } - var alarm = new Entity.LogicModels.ProjectAlarm.ProAlarmDto - { - AlarmType = "Security_Alarm", - AlarmLevel = alarmLevel, - Theme = "安消报警", - Content = faultHistory.Name, - AlarmTime = faultHistory.CreateTime.GetValueOrDefault(), - State = state, - MapId = faultHistory.Id - }; - alarms.Add(alarm); - } - var result = await SaveAlarm(alarms); - return result; - } - - /// - /// 测试保存故障报警信息 - /// - /// - /// - /// - /// - public async Task> TestSaveFaultAlarm(DateTime startTime, DateTime endTime, long projectId) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var airDBContext = scope.ServiceProvider.GetRequiredService(); - var tbFaultHistorys = await airDBContext.TbFaultHistory - .Where(t => t.Projectid == projectId && t.Createtime >= startTime && t.Createtime <= endTime).AsNoTracking().ToListAsync(); - result = await SaveFaultAlarm(tbFaultHistorys); - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs deleted file mode 100644 index 11a7058..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectDWCoreService.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.Context.AirDB; - -namespace WeiCloud.Core.Services -{ - public class ProjectDWCoreService : IProjectDWCoreService - { - private readonly WeiCloudAirDBContext _Aircontext; - private readonly ILogger _logger; - private List projectId; - public ProjectDWCoreService(WeiCloudAirDBContext Aircontext, ILogger logger) - { - _Aircontext = Aircontext; - _logger = logger; - } - /// - /// 获得今年到目前为止的能耗 - /// - /// - public async Task GetCurrentEnergyYear(long? projectid, DateTime dateTime) - { - DateTime now = DateTimeTools.GetSysDateTimeNow(); - DateTime yearfristday = DateTimeTools.GetYearFirstDay(); - double reData = 0; - try - { - var dwData = await _Aircontext.TbProjectDw.Where(a => a.Parm002 == projectid).ToListAsync(); - var result = (from a in dwData - where a.Parm002 == projectid && a.Parm003 > yearfristday && a.Parm003 < now - group a by a.Parm002 into g - select new - { //002 累计用电,004 累计用水 ,006 累计用气 - sum = (g.Max(a => a.PdParm002) - g.Min(a => a.PdParm002)) * 0.123 + (g.Max(a => a.PdParm004) - g.Min(a => a.PdParm004)) * 1.330 - }).Sum(a => a.sum); - if (result != null && result > 0) - { - reData = (double)result; - } - return reData; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("GetCurrentEnergyYear:{0}", ex)).GetNlogMessage()); - return await Task.FromResult(-1); - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs deleted file mode 100644 index 3eb3883..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/ProjectInfoGainCoreService.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class ProjectInfoGainCoreService: IProjectInfoGainCoreService - { - private readonly IListService _listService; - private readonly IDictionaryService _dictionaryService; - public ProjectInfoGainCoreService(IListService listService, IDictionaryService dictionaryService) - { - _listService = listService; - _dictionaryService = dictionaryService; - } - public async Task> GetAllEquipRedis() - { - EquipmentInfo equip = new EquipmentInfo(); - var result = _dictionaryService.GetValue(equip.GetType().Name); - var list = result.Values.ToList(); - - return await Task.FromResult(list); - } - public async Task GetEquipModel(long equipId) - { - EquipmentInfo equip = new EquipmentInfo(); - equip = _dictionaryService.GetValue(equip.GetType().Name)[equipId.ToString()]; - return await Task.FromResult(equip); - } - public async Task> GetEquipListByKeys(string[] keys) - { - List equip = new List(); - EquipmentInfo e = new EquipmentInfo(); - equip = _dictionaryService.GetValue(e.GetType().Name, keys).Select(d => d.Value).ToList(); - if (equip != null) - { - equip = equip.Where(d => d != null && d.Id > 0).ToList(); - } - return await Task.FromResult(equip); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs deleted file mode 100644 index 5fea871..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/PublicFunctionService.cs +++ /dev/null @@ -1,625 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.InfoModels; -using WeiCloud.Entity.LogicModels.SysModule; -using WeiCloud.Utils; -using WeiCloud.Utils.RedisUtil; - -namespace WeiCloud.Core.Services -{ - public class PublicFunctionService:IPublicFunctionService - { - private readonly WeiCloudDBContext _context; - private readonly WeiCloudAirDBContext _airContext; - private readonly ILogger _logger; - //private readonly IOptions _ftpUploadConfig; - private readonly IDictionaryService _dictionaryService; - private readonly IUserProjectPressRedisTreeCoreService _pressService; - private readonly WeiCloudDBUserCenterContext _userCenterContext; - public PublicFunctionService(WeiCloudDBContext context, WeiCloudAirDBContext airContext, ILogger logger, - WeiCloudDBUserCenterContext userCenterContext,IDictionaryService dictionaryService, IUserProjectPressRedisTreeCoreService pressService) - { - _context = context; - _airContext = airContext; - _logger = logger; - _dictionaryService = dictionaryService; - _userCenterContext = userCenterContext; - _pressService = pressService; - } - #region 根据登录者获取相应的项目信息(多用于项目下拉框数据源) - /// - /// 根据登录者获取相应的项目信息 - /// - /// - /// - public async Task>> GetProjectListByRole(CurrentUser user) - { - var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Data = new List() }; - try - { - var redisresult = _dictionaryService.GetValue(HashKeyNames.ProjectInfo); - if (redisresult == null || redisresult.Values == null) - { - result.Code = RequestBackStatuEnum.diy.Value; - result.Data = new List(); - return result; - } - var query = redisresult.Values.Where(x => x.State == 1).Select(p => new GetProjectModel - { - Id = p.Id, - Projectname = p.Projectname, - Shortname = p.Shortname, - Ownerid = p.Ownerid, - State = p.State - }).OrderBy(p => p.Projectname).ToList(); - if (user.RoleCode == SysBaseCodeMeta.AdminCode) - {//超级管理员 - result.Data = query; - - } - else - {//其他角色 - result.Data = query.Where(t => user.ProjectIds.Contains(t.Id)).ToList(); - } - return result; - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = ex.Message; - } - return await Task.FromResult(result); - } - #endregion - - #region 获取能耗-水电气热等类型(多用于下拉跨数据源) - public async Task>> GetEngeryType() - { - ApiResult> result = new ApiResult>() { Code=RequestBackStatuEnum.success.Value,Msg="接口请求成功!"}; - List list = new List(); - try - { - list.Add(new DropSimpleTypeModel() { Id= EngeryTypeEnum.ElectEngery,Name="电"}); - list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.WaterEngery, Name = "水" }); - list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.GasEngery, Name = "气" }); - list.Add(new DropSimpleTypeModel() { Id = EngeryTypeEnum.HeatEngery, Name = "热" }); - result.Data = list; - return await Task.FromResult(result); - } - catch (Exception) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "接口请求失败!"; - return result; - } - } - #endregion - #region 获取空气质量类型(多用于下拉跨数据源) - - public async Task>> GetAirQuantityType() - { - ApiResult> result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "接口请求成功!" }; - List list = new List(); - try - { - list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.Temperature, Name = "温度" }); - list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.Humidity, Name = "湿度" }); - list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.CO2, Name = "CO₂" }); - list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.TVOC, Name = "TVOC" }); - list.Add(new DropSimpleTypeModel() { Id = AirQuantityEnum.PM, Name = "PM2.5" }); - result.Data = list; - return await Task.FromResult(result); - } - catch (Exception) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "接口请求失败!"; - return result; - } - } - #endregion - #region 获取时间间隔数据多用于历史数据查询(下拉跨数据源) - public async Task>> GetTimeSpanData() - { - ApiResult> result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "接口请求成功!" }; - List list = new List(); - try - { - list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.FiveMinute, Name = "5分钟" }); - list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.TenMinute, Name = "10分钟" }); - list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.HalfHour, Name = "30分钟" }); - list.Add(new DropSimpleTypeModel() { Id = TimeSpanEnum.Hour, Name = "一小时" }); - result.Data = list; - return await Task.FromResult(result); - } - catch (Exception) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = "接口请求失败!"; - return result; - } - } - #endregion - #region 天气 - #region 获取当天天气 - /// - /// 获取当天天气 - /// - /// - /// - public async Task> GetWeatherByProId(long proiectId) - { - ApiResult result = new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "接口请求失败!" }; - string now = DateTime.Now.ToString("yyyy-MM-dd"); ; - WeatherTwoGic gic = new WeatherTwoGic(); - try - { - var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); - var sysAreas = await _userCenterContext.SysArea.ToListAsync(); - var data = (from p in projectInfos - join o in sysAreas - on p.Position equals o.RegionCode - join w in _airContext.WeatherTwo - on p.Position equals w.AreaId - where p.Id == proiectId - && w.WeatherDate.Contains(now) - orderby w.UpdateDate descending - select new WeatherTwoGic - { - Id = w.Id, - WeatherDay = w.WeatherDay, - WeatherDate = w.WeatherDate, - WeatherWea = w.WeatherWea, - WeatherWeaImg = w.WeatherWeaImg, - WeatherTem1 = w.WeatherTem1, - WeatherTem2 = w.WeatherTem2, - WeatherTem = w.WeatherTem, - WeatherWin = w.WeatherWin, - WeatherWinSpeed = w.WeatherWinSpeed, - AreaId = w.AreaId, - PositionName = o.RegionName - } - ).FirstOrDefault(); - if (data != null && !string.IsNullOrEmpty(data.WeatherWin)) - { - var weatherWins = gic.WeatherWin.Split(","); - if (weatherWins.Length > 0) - { - data.WeatherWin = weatherWins[0]; - } - gic = data; - } - result.Code = RequestBackStatuEnum.success.Value; - result.Msg= "接口请求成功!"; - result.Data = gic; - return await Task.FromResult(result); - } - catch (Exception ex) - { - return result; - } - } - #endregion - #region 获取未来7天天气预报 - /// - /// 获取未来7天天气预报 - /// - /// 项目id - /// 天气集合 - public async Task>> Get7DaysWeatherByProId(long proiectId) - { - ApiResult> action = new ApiResult>(); - DateTime now = DateTime.Now.Date; - DateTime end = DateTime.Now.AddDays(7).Date; - List gic = new List(); - WeatherTwoGic nowWeather = new WeatherTwoGic(); - try - { - nowWeather = (await GetWeatherByProIdNow(proiectId)).Data; - var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); - gic = (from p in projectInfos - join w in _airContext.WeatherTwo - on p.Position equals w.AreaId - where p.Id == proiectId - //&& Convert.ToDateTime(w.WeatherDate) >= now - //&& Convert.ToDateTime(w.WeatherDate) <= end - orderby w.WeatherDate, w.UpdateDate - select new WeatherTwoGic - { - Id = w.Id, - WeatherDay = (w.WeatherDay.Substring(0, w.WeatherDay.IndexOf("("))), - WeatherDate = w.WeatherDate, - WeatherWea = w.WeatherWea, - WeatherWeaImg = w.WeatherWeaImg, - WeatherTem1 = w.WeatherTem1, - WeatherTem2 = w.WeatherTem2, - WeatherTem = w.WeatherTem, - WeatherWin = w.WeatherWin.Contains(",") ? w.WeatherWin.Substring(0, w.WeatherWin.IndexOf(",")) : w.WeatherWin, - WeatherWinSpeed = w.WeatherWinSpeed, - AreaId = w.AreaId, - // PositionName = o.RegionName - } - ).OrderByDescending(d => d.WeatherDate).DistinctBy(d => d.WeatherDay).Where(d => d != null).ToList(); - gic = gic.Where(d => Convert.ToDateTime(d.WeatherDate) >= now && Convert.ToDateTime(d.WeatherDate) <= end).OrderBy(d => d.WeatherDate).ToList(); - gic.Insert(0, nowWeather); - action.Data = gic; - action.Code = RequestBackStatuEnum.success.Value; - action.Msg = "请求成功"; - } - catch (Exception ex) - { - action.Data = null; - action.Code = RequestBackStatuEnum.fail.Value; - action.Msg = "服务器请求失败"; - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetWeatherByProId", string.Format("获取手机端天气信息报错:{0}", ex)).GetNlogMessage()); - } - return await Task.FromResult(action); - } - #endregion - #region 获取现在时刻天气 - /// - /// 获取现在时刻天气 - /// - /// - /// - public async Task> GetWeatherByProIdNow(long proiectId) - { - ApiResult result = new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "接口请求失败!" }; - WeatherTwoGic gic = new WeatherTwoGic(); - try - { - var projectInfos = await _userCenterContext.ProjectInfo.ToListAsync(); - gic = (from p in projectInfos - join w in _airContext.WeatherThree - on p.Position equals w.AreaId - where p.Id == proiectId - && w.WeatherDate == DateTime.Now.Date - orderby w.Id descending - select new WeatherTwoGic - { - Id = w.Id, - WeatherDay = w.WeatherDay, - WeatherDate = w.WeatherDate.ToString(), - WeatherWea = w.WeatherWea, - WeatherWeaImg = w.WeatherWeaImg, - WeatherTem = w.WeatherTem, - WeatherWin = w.WeatherWin, - WeatherWinSpeed = w.WeatherWinSpeed, - AreaId = w.AreaId, - } - ).FirstOrDefault(); - result.Code = RequestBackStatuEnum.success.Value; - result.Msg = "接口请求成功!"; - result.Data = gic; - return await Task.FromResult(result); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("GetWeatherByProIdNow:{0}", ex)).GetNlogMessage()); - return result; - } - } - #endregion - #endregion - #region 根据项目id获取项目名称以及logo - public async Task> GetProjectBaseInfo(long projectid) - { - try - { - var projectInfo = await (from project in _userCenterContext.ProjectInfo - where project.State == 1 && project.Id == projectid - select new ProjectBaseInfo - { - ProjectName = project.Shortname, - ProjectLogoUrl = project.ProjectLogoUrl - }).FirstOrDefaultAsync(); - if (projectInfo != null) - { - return new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = projectInfo }; - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetProjectBaseInfo", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - return new ApiResult { Code = RequestBackStatuEnum.fail.Value, Msg = ex.Message }; - } - return new ApiResult { Code = RequestBackStatuEnum.fail.Value, Msg = "数据为空!" }; - } - #endregion - #region 获取项目看板页底部的菜单 - /// - /// 获取项目看板页底部的菜单 - /// - /// - /// - /// - /// - /// - public async Task>> GetProjectMenuSysModule(string roleCode, long projectId, long parentId, long? modelType = 0) - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - try - { - if (projectId == 0) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "项目Id为空!"; - return result; - } - var query = (from sm in _userCenterContext.SysModule - join psm1 in _userCenterContext.ProjectSysModule on sm.Id equals psm1.Sysmoduleid into tmppsm - from psm in tmppsm.DefaultIfEmpty() - where psm.Isenable == true && (sm.Sysid == 0 || psm.Projectid == projectId) - select new - { - SysModuleId = sm.Id, - PackageName = sm.Packagename, - ActiveRule = sm.Activerule, - ProjectId = psm.Projectid, - OwnerId = psm.Ownerid, - SysModuleName = sm.Name, - SysId = sm.Sysid, - SysModelType = sm.Sysmodeltype, - DisplayType = psm.Displaytype, - }); - if (modelType > 0) - { - query = query.Where(d => d.SysModelType == modelType); - } - else - { - query = query.Where(d => d.SysModelType != 1); - } - var sysModules = query.Select(t => new - { - SysModuleId = t.SysModuleId, - PackageName = t.PackageName, - ActiveRule = t.ActiveRule, - SysModuleName = t.SysModuleName, - SysId = t.SysId, - DisplayType = t.DisplayType, - SysModelType = t.SysModelType - - }).Distinct().ToList().Select(t => new SysUserModuleMenuModel - { - SysModuleId = t.SysModuleId, - PackageName = t.PackageName, - ActiveRule = t.ActiveRule, - SysModuleName = t.SysModuleName, - SysId = t.SysId, - DisplayType = (t.DisplayType == null || (bool)t.DisplayType == false) ? (short)0 : (short)1, - SysModelType = t.SysModelType - }).ToList(); - - - - var menus = _userCenterContext.ProjectMenu.Where(t => t.Isusing == 1 && t.Projectid == projectId).Select(t => new Permissions - { - Id = t.Id, - Permissname = t.Menuname, - Permisscode = t.Menucode, - Permisstype = t.Menutype, - Parentid = t.Parentid, - Isusing = t.Isusing, - Url = t.Url, - IName = t.IName, - Order = t.Order, - Sysmoduleid = t.Sysmoduleid - }).OrderBy(t => t.Order).ToList(); - - menus = menus.OrderBy(t => t.Order).ToList(); - - #region 菜单权限 - - if (roleCode != SysBaseCodeMeta.AdminCode) - { - var userPressStr = await _pressService.GetUserRolePress(); - List pressIdList = new List(); - //有权限才找找菜单树 - if (!string.IsNullOrEmpty(userPressStr)) - { - string[] arr = userPressStr.Split(','); - foreach (string s in arr) - { - if (!string.IsNullOrEmpty(s)) - { - long id = 0; - long.TryParse(s, out id); - if (id > 0) - { - pressIdList.Add(id); - } - } - } - } - menus = menus.Where(t => pressIdList.Contains(t.Id)).ToList(); - } - #endregion - - List firstLevelMenus = menus.Where(t => t.Parentid == parentId).ToList(); - var oneLevelPermissions = GetPermissionsGroupLevel(firstLevelMenus); - oneLevelPermissions = oneLevelPermissions.OrderBy(t => t.Order).ToList(); - var items = new List { }; - var model = (from m in _userCenterContext.ConModule select m).ToList(); - foreach (var oneLevelPermission in oneLevelPermissions) - { - var sysModule = sysModules.FirstOrDefault(t => t.SysModuleId == oneLevelPermission.Sysmoduleid); - if (sysModule == null && oneLevelPermission.Sysmoduleid != 0) - { - continue; - } - var item = new SysUserMenuModuleModel - { - Name = oneLevelPermission.Permissname, - Url = oneLevelPermission.Url, - Id = oneLevelPermission.Id, - IName = oneLevelPermission.IName, - Actions = GetActionList(oneLevelPermission.Id, menus), - //Childs = GetMenuTree1(menus, oneLevelPermission.Id, model), - MenuCode = oneLevelPermission.Permisscode, - ModelId = GetModelId(model, oneLevelPermission.Permissname), - SysModule = sysModule, - ParentId = oneLevelPermission.Parentid - }; - if (sysModule != null && sysModule.DisplayType == 1) - {//横向排序,只有下一级菜单横向显示 - var secondLevelMenus = menus.Where(t => t.Parentid == item.Id).ToList(); - var secondLevelPermissions = GetPermissionsGroupLevel(secondLevelMenus); - secondLevelPermissions = secondLevelPermissions.OrderBy(t => t.Order).ToList(); - foreach (var secondLevelPermission in secondLevelPermissions) - { - var sysModule2 = sysModules.FirstOrDefault(t => t.SysModuleId == secondLevelPermission.Sysmoduleid); - if (sysModule2 == null && secondLevelPermission.Sysmoduleid != 0) - { - continue; - } - var item2 = new SysUserMenuModuleModel - { - Name = secondLevelPermission.Permissname, - Url = secondLevelPermission.Url, - Id = secondLevelPermission.Id, - IName = secondLevelPermission.IName, - Actions = GetActionList(secondLevelPermission.Id, menus), - Childs = GetMenuTree1(menus, secondLevelPermission.Id, model, sysModules), - MenuCode = !string.IsNullOrEmpty(secondLevelPermission.Permisscode) ? secondLevelPermission.Permisscode : secondLevelPermission.Id.ToString(), - ModelId = GetModelId(model, secondLevelPermission.Permissname), - SysModule = sysModule, - ParentId = secondLevelPermission.Parentid - }; - items.Add(item2); - } - } - else - { - item.Childs = GetMenuTree1(menus, oneLevelPermission.Id, model, sysModules); - items.Add(item); - } - } - result.Data = items; - } - catch (Exception ex) - { - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = ex.Message; - _logger.LogError(new NlogMessageHelper(System.Reflection.MethodBase.GetCurrentMethod().Name, string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - private long GetModelId(List modelList, string name) - { - long id = 0; - ConModule model = new ConModule(); - model = (from m in modelList where m.ModuleName.Contains(name) select m).ToList().FirstOrDefault(); - if (model != null) - { - id = model.Id; - } - return id; - } - private List GetMenuTree1(List allPermissions, long id, List model, List sysModules) - { - var items = new List { }; - var childs = allPermissions.Where(t => t.Parentid == id && (t.Permisstype == null || t.Permisstype == 0)).ToList();//只显示菜单t.Permisstype == 0 - foreach (var child in childs) - { - var item = new SysUserMenuModuleModel - { - Name = child.Permissname, - Url = child.Url, - Id = child.Id, - IName = child.IName, - MenuCode = !string.IsNullOrEmpty(child.Permisscode) ? child.Permisscode : child.Id.ToString(), - Actions = GetActionList(child.Id, allPermissions), - ModelId = GetModelId(model, child.Permissname), - Childs = GetMenuTree1(allPermissions, child.Id, model, sysModules), - ParentId = child.Parentid - }; - items.Add(item); - var sysModule = sysModules.FirstOrDefault(t => t.SysModuleId == child.Sysmoduleid); - if (sysModule != null) - { - item.SysModule = sysModule; - } - } - return items; - } - private List GetActionList(long parentId, List pressList) - { - List codeList = new List(); - if (pressList != null && pressList.Count > 0 && parentId >= 0) - { - //查询子集中所有得操作权限code - var data = (from p in pressList where p.Parentid == parentId && p.Permisstype == 1 select p.Permisscode).ToList(); - if (data != null && data.Count > 0) - { - codeList = data; - } - } - return codeList; - } - private List GetPermissionsGroupLevel(List permissions) - { - var parentPermissions = new List { }; - foreach (var permission in permissions) - { - //if (permission.Parentid == null || permission.Parentid == 0) - //{ - // parentPermissions.Add(permission); - //} - //else - //{ - // var parent = permissions.FirstOrDefault(t => t.Id == permission.Parentid); - // if (parent == null) - // { - // parentPermissions.Add(permission); - // } - // else if (parent.Parentid == null || permission.Parentid == 0) - // { - // parentPermissions.Add(parent); - // } - // else - // { - // var _permission = GetPermissionsGroupLevel(permissions, parent); - // } - //} - var _permission = GetPermissionsGroupLevel(permissions, permission); - if (_permission != null) - { - parentPermissions.Add(_permission); - } - } - parentPermissions = parentPermissions.Distinct().ToList(); - return parentPermissions; - } - private Permissions GetPermissionsGroupLevel(List permissions, Permissions permission) - { - var parent = permissions.FirstOrDefault(t => t.Id == permission.Parentid); - if (parent == null) - { - return permission; - } - else if (parent.Parentid == null || permission.Parentid == 0) - { - return parent; - } - else - { - return GetPermissionsGroupLevel(permissions, parent); - } - } - #endregion - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs deleted file mode 100644 index de8ff15..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/IRealDataCoreService.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Core.BaseCore; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.DataCollection; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.RealData -{ - public interface IRealDataCoreService : IGrainWithIntegerKey - { - Task> GetRealValueByProAndKey(long? projectid, string[] paramIds); - Task> GetRealValueFromRedisByPro(long? projectid); - Task PutRealDatas(List tbRealDatas); - Task> ModifyRealData(TbRealData tbRealData); - Task> GetRealValueFromRedisByProEdit(long? projectid); - Task UpdateRealValueToRedisByPro(long? projectid, List tbRealDatas); - Task UpdateRealvalueOnValue(long? projectid, RealDataOnlyValueBo realDataOnlyValueBo); - Task UpdateRealValueToRedisByPro(long? projectid, TbRealData tbRealData); - Task> GetRealValueFromRedisByPro(long projectid, List realdIds, List realDatas = null); - Task> CalculationHisotryVirtualParameters(List tbRealDatasOrg, DateTime? startTime, DateTime? endTime, long projectId, short timeUnit = (short)QueryTimeTypeEnum.Hour); - Task UpdateRealvalueOnValue(long projectId, List realDataOnlyValueBos); - Task> GetRealValueFromDBMaxMin(QueryRealDataTimeZonesMaxMinModel input, List realDatas = null); - Task> GetRealValueFromRedisByProVirtualByEquipId(long projectid, List realdIds, List realDatas = null); - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs deleted file mode 100644 index 030597e..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/RealData/RealDataCoreService.cs +++ /dev/null @@ -1,1761 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Utils.RedisUtil; -using WeiCloud.Entity.LogicModels.DataCollection; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity; -using Microsoft.EntityFrameworkCore; -using WeiCloud.Utils.Common; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Utils.Calculation; -using Microsoft.Extensions.DependencyInjection; -using WeiCloud.Core.Services.DataStream; -using Newtonsoft.Json; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.LogicModels.Report; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Core.Services.Report; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.IotDS; -using NPOI.SS.UserModel; -using NPOI.HSSF.Record.Chart; - -namespace WeiCloud.Core.RealData -{ - public class RealDataCoreService : IRealDataCoreService - { - private readonly IDictionaryService _dictionaryService; - private readonly ILogger _logger; - private readonly WeiCloudDBContext _weiCloudDBContext; - private readonly WeiCloudDBUserCenterContext _weiCloudDBUserCenterContext; - private readonly IStringService _stringService; - private readonly LocalData _localData; - private readonly IServiceScopeFactory _serviceScopeFactory; - private readonly ITimeSeqService _timeSeqService; - private readonly List virtualParameterUniqueCodes = new List { "NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" }; - public RealDataCoreService( - ITimeSeqService timeSeqService, - IServiceScopeFactory serviceScopeFactory, - IStringService stringService, - IDictionaryService dictionaryService, - ILogger logger, - WeiCloudDBContext weiCloudDBContext, - LocalData localData, - WeiCloudDBUserCenterContext weiCloudDBUserCenterContext) - { - _serviceScopeFactory = serviceScopeFactory; - _dictionaryService = dictionaryService; - _logger = logger; - _weiCloudDBContext = weiCloudDBContext; - _stringService = stringService; - _localData = localData; - _timeSeqService = timeSeqService; - _weiCloudDBUserCenterContext = weiCloudDBUserCenterContext; - } - public async Task UpdateRealvalueOnValue(long? projectid, RealDataOnlyValueBo realDataOnlyValueBo) - { - try - { - var onlyvaluehashid = HashKeyNames.ProRealValueAndTime + projectid.ToString(); - _dictionaryService.PushValue(onlyvaluehashid, realDataOnlyValueBo.Id.ToString(), realDataOnlyValueBo, 1); - return 1; - } - catch (Exception ex) - { - return -1; - } - } - /// - /// 批量保存 - /// - /// - /// - /// - public async Task UpdateRealvalueOnValue(long projectId, List realDataOnlyValueBos) - { - try - { - var onlyvaluehashid = HashKeyNames.ProRealValueAndTime + projectId.ToString(); - var newdic = realDataOnlyValueBos.ToDictionary(x => x.Id.ToString(), y => new RealDataOnlyValueBo { Id = y.Id, Realvalue = y.Realvalue, Updatetime = y.Updatetime }); - _dictionaryService.PushValue(onlyvaluehashid, newdic, 1); - return 1; - } - catch (Exception ex) - { - return -1; - } - } - /// - /// 更加项目id更新一个参数 - /// - /// - /// - /// - public async Task UpdateRealValueToRedisByPro(long? projectid, TbRealData tbRealData) - { - var result = 1; - try - { - - _dictionaryService.PushValue(HashKeyNames.ProEqRealValue + projectid.ToString(), tbRealData.Id.ToString(), tbRealData, 1); - - return await Task.FromResult(result); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " UpdateRealValueToRedisByPro", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - return -1; - } - } - /// - /// 根据项目id更新多个参数 - /// - /// - /// - /// - public async Task UpdateRealValueToRedisByPro(long? projectid, List tbRealDatas) - { - var result = 0; - if (projectid == null || tbRealDatas == null || tbRealDatas.Count == 0) - { - return result; - } - try - { - var dickey = $"{HashKeyNames.ProEqRealValue}{projectid}"; - var dic = tbRealDatas.Where(x => x != null && x.Id > 0).ToList().ToDictionary(x => x.Id.ToString(), y => y); - _dictionaryService.PushValue(dickey, dic, 1); - - return await Task.FromResult(result); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " UpdateRealValueToRedisByPro", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - return -1; - } - } - public async Task> GetRealValueFromRedisByProEdit(long? projectid) - { - try - { - var templist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); - if (templist == null || templist.Count == 0) - { - templist = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid select a).ToListAsync(); - if (templist != null) - { - _dictionaryService.PushValue(HashKeyNames.TbRealData, templist.ToDictionary(x => x.Id.ToString(), y => y), 1); - } - } - return templist; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - return null; - } - } - - /// - /// 获得项目下所有的实时参数 - /// - /// 项目id - /// - public async Task> GetRealValueFromRedisByPro(long? projectid) - { - try - { - //var templist = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); - var templist = await _localData.GetTbRealDatas(projectid ?? 0); - var realIdStrs = templist.Select(t => t.Id.ToString()).ToArray(); - //var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realIdStrs, 1, 1).Values.ToList(); - if (templist == null || templist.Count() == 0) - {//没有配置信息 - templist = new List { }; - } - var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realIdStrs, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); - if (realvaluelist == null || realvaluelist.Count == 0) - {//没有实时值 - return templist; - } - var isRefresh = await _localData.CheckProIdIsRefresh(projectid ?? 0, templist.Select(t => t.Id).ToList(), realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); - if (isRefresh) - { - templist = await _localData.GetTbRealDatas(projectid ?? 0); - } - var list = new List { }; - - foreach (var temp in templist) - { - var r = realvaluelist.FirstOrDefault(t => t.Id == temp.Id); - if (r != null) - { - temp.Realvalue = r.Realvalue; - temp.Updatetime = r.Updatetime; - } - list.Add(temp); - } - var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); - if (virtualRealDatas.Count() > 0) - { - var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid.GetValueOrDefault()); - foreach (var virtualItem in virtualItems) - { - var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); - if (l != null) - { - l.Realvalue = virtualItem.Realvalue; - l.Updatetime = virtualItem.Updatetime; - } - } - } - return await Task.FromResult(list); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - return new List { }; - } - } - /// - /// 使用虚拟点-设备Id - /// - /// - /// - /// - /// - public async Task> GetRealValueFromRedisByProVirtualByEquipId(long projectid, List realdIds, List realDatas = null) - { - try - { - if (realdIds == null || realdIds.Count() == 0) - { - return new List { }; - } - var realdStrIds = realdIds.Select(t => t.ToString()).ToArray(); - if (realDatas == null || realDatas.Count() == 0) - { - //realDatas = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid && realdIds.Contains(a.Id) select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); - //realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); - realDatas = await _localData.GetTbRealDatas(projectid, realdIds); - //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); - } - if (realDatas == null) - { - realDatas = new List(); - } - var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).ToList(); - if (realvaluelist == null || realvaluelist.Count == 0) - { - return realDatas; - } - var isRefresh = await _localData.CheckProIdIsRefresh(projectid, realdIds, realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); - //if (isRefresh) - //{ - // realDatas = await _localData.GetTbRealDatas(projectid, realdIds); - // //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); - //} - - var list = new List { }; - foreach (var realData in realDatas) - { - var realValue = realvaluelist.FirstOrDefault(t => t != null && t.Id == realData.Id); - if (realValue != null) - { - realData.Realvalue = realValue.Realvalue; - realData.Updatetime = realValue.Updatetime; - } - list.Add(realData); - } - //foreach (var r in realvaluelist) - //{ - // if (r == null) - // { - // continue; - // } - // var temp = realDatas.FirstOrDefault(t => t.Id == r.Id); - // if (temp != null) - // { - // temp.Realvalue = r.Realvalue; - // temp.Updatetime = r.Updatetime; - // list.Add(temp); - // } - //} - - var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); - if (virtualRealDatas.Count() > 0) - { - var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid); - foreach (var virtualItem in virtualItems) - { - var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); - if (l != null) - { - l.Realvalue = virtualItem.Realvalue; - l.Updatetime = virtualItem.Updatetime; - } - } - } - - return await Task.FromResult(list); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByProVirtualByEquipId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - return null; - } - } - public async Task> GetRealValueFromRedisByPro(long projectid, List realdIds, List realDatas = null) - { - try - { - if (realdIds == null || realdIds.Count() == 0) - { - return new List { }; - } - if (realDatas == null || realDatas.Count() == 0) - { - //realDatas = await (from a in _weiCloudDBContext.TbRealData where a.Projectid == projectid && realdIds.Contains(a.Id) select a).AsNoTracking().ToListAsync();// _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); - //realDatas = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).Where(t => t != null).ToList(); - realDatas = await _localData.GetTbRealDatas(projectid, realdIds); - //realDatas = realDatas.Where(d => realdIds.Contains(d.Id)).ToList(); - } - if (realDatas == null || realDatas.Count() == 0) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: realDatas为空;")).GetNlogMessage()); - return new List { }; - } - var standarIds = realDatas.Where(t => t.Standarparamid != null && t.Standarparamid > 0).Select(t => t.Standarparamid ?? 0).Distinct().ToList(); - var standarParams = await _weiCloudDBUserCenterContext.StandarParam.Where(t => standarIds.Contains(t.Id)).AsNoTracking().Select(t => new - { - t.Id, - t.Uniquepronoun - }).AsNoTracking().ToListAsync(); - foreach (var realData in realDatas) - { - try - { - if (string.IsNullOrEmpty(realData.JsonContent)) - { - continue; - } - var realParamJson = JsonConvert.DeserializeObject(realData.JsonContent); - if (realData.PointType == 2) - { - foreach (var point in realParamJson.CombinedPoint) - { - if (point.Key > 0) - { - realdIds.Add((long)point.Key); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); - } - } - - var realdStrIds = realdIds.Select(t => t.ToString()).Distinct().ToArray(); - var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), realdStrIds, 1, 1).Select(t => t.Value).ToList(); - if (realvaluelist == null || realvaluelist.Count == 0) - { - return realDatas; - } - - var list = new List { }; - - //foreach (var realValue in realvaluelist) - //{ - // if (realValue==null) - // { - // continue; - // } - // var realData = realDatas.FirstOrDefault(t => t.Id == realValue.Id); - // if (realData == null) - // { - // realData = new TbRealData { Id = realValue.Id }; - // } - // realData.Realvalue = realValue.Realvalue; - // realData.Updatetime = realValue.Updatetime; - // list.Add(realData); - //} - foreach (var realData in realDatas) - { - list.Add(realData); - var realvalue = realvaluelist.Where(t => t != null).FirstOrDefault(t => t.Id == realData.Id); - if (realvalue != null) - { - realData.Realvalue = realvalue.Realvalue; - realData.Updatetime = realvalue.Updatetime; - - try - { - if (realData.Standarparamid > 0) - { - var standarParam = standarParams.FirstOrDefault(t => t.Id == realData.Standarparamid); - - if (standarParam != null) - { - if (standarParam.Uniquepronoun.Equals("CStartTime") || standarParam.Uniquepronoun.Equals("CEndTime") || standarParam.Uniquepronoun.Equals("CPayTime")) - { - DateTime unixEpoch = new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Utc); - DateTime dateTime = unixEpoch.AddSeconds(long.Parse(realData.Realvalue)); - realData.Realvalue = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {3};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); - } - } - } - - //var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); - //if (virtualRealDatas.Count() > 0) - //{ - // var virtualItems = await CalculationVirtualParametersV02(virtualRealDatas, realvaluelist); - // foreach (var virtualItem in virtualItems) - // { - // var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); - // if (l != null) - // { - // l.Realvalue = virtualItem.Realvalue; - // l.Updatetime = virtualItem.Updatetime; - // } - // } - //} - - return await Task.FromResult(list); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1} {2};", ex.Message, ex.StackTrace, realdIds.Join(","))).GetNlogMessage()); - return null; - } - } - public async Task> GetRealValueFromDBMaxMin(QueryRealDataTimeZonesMaxMinModel input, List realDatas = null) - { - var result = new List { }; - try - { - if (input.RealIds == null || input.RealIds.Count() == 0) - { - return new List { }; - } - if (realDatas == null || realDatas.Count() == 0) - { - realDatas = await _localData.GetTbRealDatas(input.ProjectId, input.RealIds); - } - foreach (var realData in realDatas) - { - try - { - var realParamJson = JsonConvert.DeserializeObject(realData.JsonContent); - if (realData.PointType == 2) - { - foreach (var point in realParamJson.CombinedPoint) - { - if (point.Key > 0) - { - input.RealIds.Add((long)point.Key); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - } - - var items = await GetRealDataTimeZonesMaxMin(new QueryRealDataTimeZonesMaxMinModel - { - ProjectId = input.ProjectId, - StartTime = input.StartTime, - EndTime = input.EndTime, - RealIds = input.RealIds - }); - foreach (var realData in realDatas) - { - var item = items.FirstOrDefault(t => t.RealId == realData.Id); - if (item != null) - { - result.Add(item); - } - } - var virtualRealDatas = realDatas.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); - if (virtualRealDatas.Count() > 0) - { - var virtualItems = await CalculationVirtualParametersTimeZonesMaxMin(items, virtualRealDatas); - if (virtualItems.Count() > 0) - { - result.AddRange(virtualItems); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return result; - } - - private async Task> GetRealDataTimeZonesMaxMin(QueryRealDataTimeZonesMaxMinModel input) - { - var items = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var userDbContext = scope.ServiceProvider.GetRequiredService(); - var projectInfo = userDbContext.ProjectInfo.Where(t => t.Id == input.ProjectId).Select(t => new - { - t.Id, - t.Dbstr - }).FirstOrDefault(); - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - items = __contextDB.DsPointHistory.Where(t => input.RealIds.Contains(t.Id) && t.CreateTime >= input.StartTime && t.CreateTime < input.EndTime).GroupBy(g => g.Id).Select(t => new RealDataTimeZonesMaxMinModel - { - RealId = t.Key, - Max = t.Max(m => m.Value ?? 0), - Min = t.Min(m => m.Value ?? 0) - }).ToList(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealDataTimeZonesMaxMin", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - private async Task> GetRealDataTimeZones(QueryRealDataTimeZonesMaxMinModel input) - { - var items = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var userDbContext = scope.ServiceProvider.GetRequiredService(); - var projectInfo = userDbContext.ProjectInfo.Where(t => t.Id == input.ProjectId).Select(t => new - { - t.Id, - t.Dbstr - }).FirstOrDefault(); - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - var pointsHistory = __contextDB.DsPointHistory.Where(t => input.RealIds.Contains(t.Id) && t.CreateTime >= input.StartTime && t.CreateTime < input.EndTime).Select(t => new - { - t.Id, - t.Value, - t.CreateTime - }).OrderBy(t => t.CreateTime).ToList(); - foreach (var point in pointsHistory) - { - var item = items.FirstOrDefault(); - if (item == null) - { - item = new RealDataTimeZonesModel - { - RealId = point.Id, - Items = new List { } - }; - items.Add(item); - } - item.Items.Add(new RealDataTimeZonesItemModel - { - Time = point.CreateTime, - Value = point.Value.GetValueOrDefault() - }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealDataTimeZonesMaxMin", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - private async Task> CalculationVirtualParametersTimeZonesMaxMin(List items, List tbRealDatas) - { - var result = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - - Dictionary dicParamsEquipIds = new Dictionary { }; - - foreach (var tbRealData in tbRealDatas) - { - try - { - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); - var maxFormula = tbRealData.Virtualformula; - var minFormula = tbRealData.Virtualformula; - foreach (var formulaParam in formulaParams) - { - var _param = formulaParam.Split("=").ToList(); - dicParamsEquipIds.TryAdd(_param[0], long.Parse(_param[1])); - } - var pointIds = dicParamsEquipIds.Select(t => t.Value).Distinct().ToList(); - var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); - - foreach (var dicParamEquipId in dicParamsEquipIds) - { - if (!tbRealData.Virtualformula.Contains($"{dicParamEquipId.Key}")) - { - continue; - } - if (dicParamEquipId.Value == 0) - { - continue; - } - var _tbRealData = items.FirstOrDefault(t => t.RealId == dicParamEquipId.Value); - if (_tbRealData != null) - { - maxFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Max.ToString()); - minFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Min.ToString()); - } - else - { - minFormula = maxFormula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", "0"); - } - } - try - { - tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); - result.Add(new RealDataTimeZonesMaxMinModel - { - RealId = tbRealData.Id, - Max = FormulaUtil.InterperterFormula(maxFormula), - Min = FormulaUtil.InterperterFormula(minFormula) - }); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters1", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1} {2}", ex.Message, tbRealData.Transarray, ex.StackTrace)).GetNlogMessage()); - } - dicParamsEquipIds.Clear(); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return result; - } - /// - /// 参数是点 - /// - /// - /// - /// - private async Task> CalculationVirtualParametersV02(List tbRealDatas, List realDatas) - { - try - { - using var scope = _serviceScopeFactory.CreateScope(); - - Dictionary dicParamsEquipIds = new Dictionary { }; - - foreach (var tbRealData in tbRealDatas) - { - try - { - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula) || string.IsNullOrEmpty(tbRealData.Virtualformulaparam)) - { - continue; - } - var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); - foreach (var formulaParam in formulaParams) - { - var _param = formulaParam.Split("=").ToList(); - if (_param.Count() >= 2) - { - dicParamsEquipIds.TryAdd(_param[0], long.Parse(_param[1])); - } - } - var pointIds = dicParamsEquipIds.Select(t => t.Value).Distinct().ToList(); - var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); - - foreach (var dicParamEquipId in dicParamsEquipIds) - { - if (!tbRealData.Virtualformula.Contains($"{dicParamEquipId.Key}")) - { - continue; - } - if (dicParamEquipId.Value == 0) - { - continue; - } - var _tbRealData = realDatas.Where(t => t != null).FirstOrDefault(t => t.Id == dicParamEquipId.Value); - if (_tbRealData != null) - { - if ((tbRealData.Updatetime == null && _tbRealData.Updatetime != null) - || (tbRealData.Updatetime != null && _tbRealData.Updatetime != null && _tbRealData.Updatetime.GetValueOrDefault() < tbRealData.Updatetime.GetValueOrDefault())) - { - tbRealData.Updatetime = _tbRealData.Updatetime; - } - tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", _tbRealData.Realvalue); - } - else - { - tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"{dicParamEquipId.Key}", "0"); - } - } - try - { - tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0};{1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - dicParamsEquipIds.Clear(); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParametersV02", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return tbRealDatas; - } - - /// - /// 获得项目下所有的实时参数 - /// - /// - /// - /// - public async Task> GetRealValueByProAndKey(long? projectid, string[] paramIds) - { - List list = new List(); - //string[] arr = new string[] { }; - try - { - if (paramIds == null || paramIds.Count() == 0) - { - return new List { }; - } - var realIds = paramIds.StrArrayToLongArray(); - var templist1 = await _localData.GetTbRealDatas(projectid ?? 0, realIds); - //templist1 = templist1.Where(t => realIds.Contains(t.Id)).ToList(); - //var templist = _dictionaryService.GetValue(HashKeyNames.ProEqRealValue + projectid.ToString(), 1).Values.ToList(); - if (templist1 == null) - { - templist1 = new List { }; - } - var realvaluelist = _dictionaryService.GetValue(HashKeyNames.ProRealValueAndTime + projectid.ToString(), paramIds, 1, 1).Select(d => d.Value).Where(d => d != null && d.Id > 0).ToList(); - if (realvaluelist == null || realvaluelist.Count == 0) - { - return templist1; - } - var isRefresh = await _localData.CheckProIdIsRefresh(projectid ?? 0, realIds, realvaluelist.Where(t => t != null).Select(t => t.Id).ToList()); - if (isRefresh) - { - //var realDatas = await _localData.GetTbRealDatas(projectid ?? 0); - //templist1 = realDatas.Where(d => realIds.Contains(d.Id)).ToList(); - templist1 = await _localData.GetTbRealDatas(projectid ?? 0, realIds); - } - - list = (from tre in templist1 - join r in realvaluelist on tre.Id equals r.Id - select new TbRealData - { - Id = tre.Id, - Datafmtdesc = tre.Datafmtdesc, - Isalarm = tre.Isalarm, - Datalength = tre.Datalength, - Descname = tre.Descname, - Aitype = tre.Aitype, - Controllsort = tre.Controllsort, - Equid = tre.Equid, - Hi = tre.Hi, - Hihi = tre.Hihi, - Isvoice = tre.Isvoice, - Lo = tre.Lo, - Lolo = tre.Lolo, - Onemean = tre.Onemean, - Paramean = tre.Paramean, - Plcid = tre.Plcid, - Projectid = tre.Projectid, - Realvalue = r.Realvalue, - Setname = tre.Setname, - Updatetime = r.Updatetime, - Standarparamid = tre.Standarparamid, - Startbyte = tre.Startbyte, - Tagname = tre.Tagname, - Transarray = tre.Transarray, - Unit = tre.Unit, - Valuesort = tre.Valuesort, - Valuetype = tre.Valuetype, - Zeromean = tre.Zeromean, - Virtualformula = tre.Virtualformula, - Virtualformulaparam = tre.Virtualformulaparam - }).ToList(); - var virtualRealDatas = list.Where(t => !string.IsNullOrEmpty(t.Virtualformula)).ToList(); - if (virtualRealDatas.Count() > 0) - { - var virtualItems = await CalculationVirtualParameters(virtualRealDatas, projectid.GetValueOrDefault()); - foreach (var virtualItem in virtualItems) - { - var l = list.FirstOrDefault(t => t.Id == virtualItem.Id); - if (l != null) - { - l.Realvalue = virtualItem.Realvalue; - l.Updatetime = virtualItem.Updatetime; - } - } - } - return await Task.FromResult(list); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetRealValueFromRedisByPro", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - return null; - } - } - - /// - /// 批量保存和编辑实时表数据 - /// - /// - /// - public async Task PutRealDatas(List tbRealDatas) - { - if (tbRealDatas == null || tbRealDatas.Count == 0) - { - return 0; - } - try - { - //_context.TbRealData.UpdateRange(tbRealDatas); - foreach (var item in tbRealDatas) - { - var entity = await (from ur in _weiCloudDBContext.TbRealData where ur.Projectid == item.Projectid && ur.Id == item.Id select ur).FirstOrDefaultAsync(); - if (entity != null) - { - - entity.Equid = item.Equid; - entity.Isalarm = item.Isalarm; - entity.Isvoice = item.Isvoice; - entity.Aitype = item.Aitype; - entity.Controllsort = item.Controllsort; - entity.Datafmtdesc = item.Datafmtdesc; - entity.Datalength = item.Datalength; - entity.Descname = item.Descname; - entity.Hi = item.Hi; - entity.Hihi = item.Hihi; - entity.Lo = item.Lo; - entity.Lolo = item.Lolo; - entity.Onemean = item.Onemean; - entity.Zeromean = item.Zeromean; - entity.Plcid = item.Plcid; - entity.Projectid = item.Projectid; - entity.Setname = item.Setname; - entity.Standarparamid = item.Standarparamid; - entity.Startbyte = item.Startbyte; - entity.Tagname = item.Tagname; - entity.Transarray = item.Transarray; - entity.Unit = item.Unit; - entity.Valuesort = item.Valuesort; - entity.Valuetype = item.Valuetype; - entity.Realvalue = item.Realvalue; - entity.Updatetime = item.Updatetime; - - _weiCloudDBContext.Update(entity); - } - else - { - entity = new TbRealData() - { - - Id = UidGenerator.Uid(), - - Equid = item.Equid, - Isalarm = item.Isalarm, - Isvoice = item.Isvoice, - Aitype = item.Aitype, - Controllsort = item.Controllsort, - Datafmtdesc = item.Datafmtdesc, - Datalength = item.Datalength, - Descname = item.Descname, - Hi = item.Hi, - Hihi = item.Hihi, - Lo = item.Lo, - Lolo = item.Lolo, - Onemean = item.Onemean, - Zeromean = item.Zeromean, - Plcid = item.Plcid, - Projectid = item.Projectid, - Setname = item.Setname, - Standarparamid = item.Standarparamid, - Startbyte = item.Startbyte, - Tagname = item.Tagname, - Transarray = item.Transarray, - Unit = item.Unit, - Valuesort = item.Valuesort, - Valuetype = item.Valuetype, - Realvalue = item.Realvalue, - Updatetime = item.Updatetime, - }; - _weiCloudDBContext.Add(entity); - } - } - - var n = await _weiCloudDBContext.SaveChangesAsync(); - if (n > 0) - { - var projectId = tbRealDatas.Select(d => d.Projectid).FirstOrDefault(); - var result1 = await UpdateRealValueToRedisByPro(projectId, tbRealDatas); - } - return n; - - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "PutRealDatas", ex.Message)).GetNlogMessage()); - return -1; - } - } - - public async Task> ModifyRealData(TbRealData tbRealData) - { - var result1 = 0; - try - { - bool isRateChanged = false; - string lastRateStr = string.Empty; - string nowRateStr = string.Empty; - var realvalue = await (from rv in _weiCloudDBContext.TbRealData where rv.Projectid == tbRealData.Projectid && rv.Id == tbRealData.Id select rv).FirstOrDefaultAsync(); - if (realvalue == null) - { - realvalue = new TbRealData() - { - Id = UidGenerator.Uid(), - - Projectid = tbRealData.Projectid, - Descname = tbRealData.Descname, - Tagname = tbRealData.Tagname, - Aitype = tbRealData.Aitype, - Unit = tbRealData.Unit, - Realvalue = tbRealData.Realvalue, - Hihi = tbRealData.Hihi, - Hi = tbRealData.Hi, - Lolo = tbRealData.Lolo, - Lo = tbRealData.Lo, - Isalarm = tbRealData.Isalarm, - Isvoice = tbRealData.Isvoice, - Valuetype = tbRealData.Valuetype, - Startbyte = tbRealData.Startbyte, - Datalength = tbRealData.Datalength, - Zeromean = tbRealData.Zeromean, - Onemean = tbRealData.Onemean, - Valuesort = tbRealData.Valuesort, - Equid = tbRealData.Equid, - Controllsort = tbRealData.Controllsort, - Transarray = 1, - Datafmtdesc = tbRealData.Datafmtdesc, - Plcid = tbRealData.Plcid, - Setname = tbRealData.Setname, - Standarparamid = tbRealData.Standarparamid, - Paramean = tbRealData.Paramean, - - }; - await _weiCloudDBContext.AddAsync(realvalue); - } - else - { - if (!string.IsNullOrEmpty(realvalue.Datafmtdesc) && !realvalue.Datafmtdesc.Equals(tbRealData.Datafmtdesc, StringComparison.OrdinalIgnoreCase)) - { - isRateChanged = true; - lastRateStr = realvalue.Datafmtdesc; - nowRateStr = tbRealData.Datafmtdesc; - } - - realvalue.Projectid = tbRealData.Projectid; - realvalue.Descname = tbRealData.Descname; - realvalue.Tagname = tbRealData.Tagname; - realvalue.Aitype = tbRealData.Aitype; - realvalue.Unit = tbRealData.Unit; - realvalue.Realvalue = tbRealData.Realvalue; - realvalue.Hihi = tbRealData.Hihi; - realvalue.Hi = tbRealData.Hi; - realvalue.Lolo = tbRealData.Lolo; - realvalue.Lo = tbRealData.Lo; - realvalue.Isalarm = tbRealData.Isalarm; - realvalue.Isvoice = tbRealData.Isvoice; - realvalue.Valuetype = tbRealData.Valuetype; - realvalue.Startbyte = tbRealData.Startbyte; - realvalue.Datalength = tbRealData.Datalength; - realvalue.Zeromean = tbRealData.Zeromean; - realvalue.Onemean = tbRealData.Onemean; - realvalue.Valuesort = tbRealData.Valuesort; - realvalue.Equid = tbRealData.Equid; - realvalue.Controllsort = tbRealData.Controllsort; - realvalue.Transarray = 1; - realvalue.Datafmtdesc = tbRealData.Datafmtdesc; - realvalue.Plcid = tbRealData.Plcid; - realvalue.Setname = tbRealData.Setname; - realvalue.Standarparamid = tbRealData.Standarparamid; - realvalue.Paramean = tbRealData.Paramean; - _weiCloudDBContext.Update(realvalue); - } - _logger.LogWarning(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", Newtonsoft.Json.JsonConvert.SerializeObject(tbRealData), Newtonsoft.Json.JsonConvert.SerializeObject(realvalue))).GetNlogMessage()); - var res = await _weiCloudDBContext.SaveChangesAsync(); - if (res > 0) - { - if (isRateChanged) - { - var expireSeconds = (int)DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")).AddDays(1).Subtract(DateTime.Now).TotalSeconds; - _stringService.Set("EquipRateChanged" + tbRealData.Equid.ToString(), DateTime.Now, expireSeconds, 2); - try - { - decimal lastRate = 1; - decimal nowRate = 1; - if (!string.IsNullOrEmpty(lastRateStr)) - { - //var str = Regex.Replace(lastRateStr, @"[^\d.\d]", ""); - //if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) - //{ - // lastRate = decimal.Parse(str); - //} - var formula = lastRateStr.Replace('X', '1'); - lastRate = FormulaUtil.InterperterFormula(formula); - } - - if (!string.IsNullOrEmpty(nowRateStr)) - { - //var str = Regex.Replace(nowRateStr, @"[^\d.\d]", ""); - //if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) - //{ - // nowRate = decimal.Parse(str); - //} - var formula = nowRateStr.Replace('X', '1'); - nowRate = FormulaUtil.InterperterFormula(formula); - } - if (lastRate - nowRate != 0) - { - //var takeDataService = GrainFactory.GetGrain(CurrentContext.GetContext().UserId); - //await takeDataService.ChangedRateModifyHistoryData(lastRate, nowRate, (long)tbRealData.Equid, DateTime.Now); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "ChangedRateModifyHistoryData", ex.Message)).GetNlogMessage()); - } - } - //await DeleteRealValueToRedisByPro(tbRealData.Projectid, tbRealData); - result1 = await UpdateRealValueToRedisByPro(tbRealData.Projectid, realvalue); - if (result1 > 0) - { - return new ApiResult() { Code = RequestBackStatuEnum.success.Value, Data = result1 }; - } - else - { - return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = string.Format("数据库保存成功,Redis保存失败,请查看是否存在Pro{0}", tbRealData.Projectid) }; - } - } - else - { - return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = "数据库保存失败" }; - } - - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("{0}抛出了异常信息: {1};", "ModifyRealData", ex.Message)).GetNlogMessage()); - return new ApiResult() { Code = RequestBackStatuEnum.fail.Value, Msg = ex.Message }; - } - } - /// - /// 参数计算 - /// - /// - /// - /// - /// - private async Task CalculationVirtualParameters(List equipIds, string uniqueCode, long projectId) - {//"NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" - var value = 0D; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var airDBConext = scope.ServiceProvider.GetRequiredService(); - var timeQuery = airDBConext.Times.AsQueryable(); - var nowTime = DateTime.Now; - if (uniqueCode == "NowHourEP") - {//电耗 - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - } - else if (uniqueCode == "NowMonthEP") - {//电耗 - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - } - else if (uniqueCode == "NowDayEP") - {//电耗 - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - } - else if (uniqueCode == "NowHourHE") - { - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - } - else if (uniqueCode == "NowMonthHE") - { - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - } - else if (uniqueCode == "NowDayHE") - { - var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return value; - } - private short GetTimeUnit(string uniqueCode) - { - var timeUnit = (short)QueryTimeTypeEnum.Hour; - if (uniqueCode == "NowHourEP") - { - - } - else if (uniqueCode == "NowMonthEP") - { - timeUnit = (short)QueryTimeTypeEnum.Day; - } - else if (uniqueCode == "NowDayEP") - { - timeUnit = (short)QueryTimeTypeEnum.Hour; - } - else if (uniqueCode == "NowHourHE") - { - - } - else if (uniqueCode == "NowMonthHE") - { - timeUnit = (short)QueryTimeTypeEnum.Day; - } - else if (uniqueCode == "NowDayHE") - { - timeUnit = (short)QueryTimeTypeEnum.Hour; - } - return timeUnit; - } - private async Task> CalculationVirtualParameters(List equipIds, string uniqueCode, long projectId, short timeUnit, DateTime? queryStartTime, DateTime? queryEndTime) - {//"NowHourEP", "NowMonthEP", "NowDayEP", "NowHourHE", "NowMonthHE", "NowDayHE" - var valueItems = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var airDBConext = scope.ServiceProvider.GetRequiredService(); - //var nowTimeHour = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:00:00")); - //var timeQuery = airDBConext.Times.Where(t => t.Fulldatetime < nowTimeHour).AsQueryable(); - var timeQuery = airDBConext.Times.AsQueryable(); - List dws = null; - //var nowTime = DateTime.Now; - var nowTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:00:00")); - if (queryEndTime.HasValue && queryEndTime.GetValueOrDefault() < nowTime) - { - nowTime = queryEndTime.GetValueOrDefault(); - } - var startTime = nowTime; - if (uniqueCode == "NowHourEP") - {//电耗 - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); - } - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.AmParm003 - }).ToListAsync(); - } - else if (uniqueCode == "NowMonthEP") - {//电耗 - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - } - //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.AmParm003 - }).ToListAsync(); - } - else if (uniqueCode == "NowDayEP") - {//电耗 - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - } - //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.AmParm003 ?? 0); - dws = await airDBConext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.AmParm003 - }).ToListAsync(); - } - else if (uniqueCode == "NowHourHE") - { - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); - } - //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd HH:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.HmParm001 - }).ToListAsync(); - } - else if (uniqueCode == "NowMonthHE") - { - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - } - //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-01 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.HmParm001 - }).ToListAsync(); - } - else if (uniqueCode == "NowDayHE") - { - if (queryStartTime.HasValue) - { - startTime = DateTime.Parse(queryStartTime.GetValueOrDefault().ToString("yyyy-MM-dd HH:00:00")); - } - else - { - startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - } - //var startTime = DateTime.Parse(nowTime.ToString("yyyy-MM-dd 00:00:00")); - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < nowTime); - var timeIds = timeQuery.Select(t => t.Id).ToList(); - //value = airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Sum(t => t.HmParm001 ?? 0); - dws = await airDBConext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).Select(t => new DwAccumModel - { - EquipId = t.Parm002, - TimeId = t.Parm001, - Value = t.HmParm001 - }).ToListAsync(); - } - var times = await timeQuery.ToListAsync(); - List> timeGroups = null; - if (timeUnit <= 0) - { - timeUnit = GetTimeUnit(uniqueCode); - } - if (timeUnit == (short)QueryTimeTypeEnum.Hour) - {//小时 - timeGroups = times.GroupBy(t => new - { - t.Year, - t.Month, - t.Day, - t.Hour - }).Select(t => t.ToList()).ToList(); - } - else if (timeUnit == (short)QueryTimeTypeEnum.Day) - { - timeGroups = times.GroupBy(t => new - { - t.Year, - t.Month, - t.Day - }).Select(t => t.ToList()).ToList(); - } - if (timeGroups != null) - { - foreach (var timeGroup in timeGroups) - { - var _timeIds = timeGroup.Select(t => t.Id).ToList(); - var _value = dws.Where(t => _timeIds.Contains(t.TimeId)).Sum(s => s.Value); - var _time = timeGroup.FirstOrDefault().Fulldatetime; - if (_time == null) - { - continue; - } - valueItems.Add(new TimeDBItemValueModel - { - Time = _time.GetValueOrDefault(), - Value = _value - }); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return valueItems; - } - private async Task> QueryEquipIntervalRealDataDoc(DateTime startTime, DateTime endTime, long projectId, List equipIds) - { - var valueItems = new List { }; - - return valueItems; - } - public async Task> QueryEquipRealDataDoc(long projectId, List equipIds, List paramCodes) - { - var resultItems = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var userCenter = scope.ServiceProvider.GetRequiredService(); - var standarParams = await userCenter.StandarParam.Where(t => t.Uniquepronoun != null && paramCodes.Contains(t.Uniquepronoun)).AsNoTracking().Select(t => new - { - t.Id, - t.Uniquepronoun - }).ToListAsync(); - var standarParamIds = standarParams.Select(t => t.Id).ToList(); - var templist = await _localData.GetTbRealDatas(projectId); - var realIds = templist.Where(t => t.Equid != null && equipIds.Contains((long)t.Equid) && t.Standarparamid != null && standarParamIds.Contains((long)t.Standarparamid)).Select(t => t.Id.ToString()).Distinct().ToArray(); - var realDatas = await GetRealValueByProAndKey(projectId, realIds); - foreach (var realData in realDatas) - { - var equipRealDatas = resultItems.FirstOrDefault(t => t.EquipId == realData.Equid); - if (equipRealDatas == null) - { - equipRealDatas = new EquipParamRealDataModel - { - EquipId = realData.Equid.GetValueOrDefault(), - Params = new Dictionary { } - }; - resultItems.Add(equipRealDatas); - } - var standarParam = standarParams.FirstOrDefault(t => t.Id == realData.Standarparamid); - double value = 0; - double.TryParse(realData.Realvalue, out value); - equipRealDatas.Params.Add(standarParam.Uniquepronoun, value); - equipRealDatas.UpdateTime = realData.Updatetime.GetValueOrDefault(); - equipRealDatas.CreateTime = realData.Updatetime.GetValueOrDefault(); - } - var realIdStrs = templist.Select(t => t.Id.ToString()).ToArray(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return resultItems; - } - /// - /// 获取虚拟参数 - /// - /// - /// - /// - private async Task> CalculationVirtualParameters(List tbRealDatasOrg, long projectId) - { - //HourEP:小时电能耗、HourHE:小时热能耗 - //DayEP:日电能耗、DayHE:日热能耗 - //MonthEP:月电能耗、MonthHE:月热能耗 - var tbRealDatas = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(tbRealDatasOrg)); - try - { - using var scope = _serviceScopeFactory.CreateScope(); - var timeSeqService = scope.ServiceProvider.GetRequiredService(); - //var equipIds = new List { }; - - Dictionary> dicParamsEquipIds = new Dictionary> { }; - - foreach (var tbRealData in tbRealDatas) - { - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); - foreach (var formulaParam in formulaParams) - { - var _param = formulaParam.Split("=").ToList(); - dicParamsEquipIds.Add(_param[0], _param[1].Split(",").StrArrayToLongArray()); - } - var equipIds = dicParamsEquipIds.SelectMany(t => t.Value).Distinct().ToList(); - var paramCodes = dicParamsEquipIds.Select(t => t.Key).Distinct().ToList(); - //foreach (var dicParamEquipIds in dicParamsEquipIds) - //{ - // var dicParamEquipParams = dicParamEquipIds.Key.Split("$"); - // if (virtualParameterUniqueCodes.Any(t => t == dicParamEquipParams[0])) - // {//自定义标签 - // var r = await CalculationVirtualParameters(dicParamEquipIds.Value, dicParamEquipParams[0], projectId); - // //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipIds.Key}`", r.ToString()); - // var formulaParam = $"`{dicParamEquipParams[0]}"; - // if (dicParamEquipParams.Length > 1) - // { - // formulaParam += $"${dicParamEquipParams[1]}"; - // } - // formulaParam += "`"; - // tbRealData.Virtualformula = tbRealData.Virtualformula.Replace(formulaParam, r.ToString()); - // } - // else - // { - // //原始 - // equipIds.AddRange(dicParamEquipIds.Value); - // } - //} - if (equipIds.Count() > 0) - { - var documents = await QueryEquipRealDataDoc(projectId, equipIds.Distinct().ToList(), paramCodes); - //var documents = await timeSeqService.QueryEquipRealDataDoc(DateTime.Now, projectId, equipIds.Distinct().ToList()); - if (documents.Count() > 0) - { - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - try - { - foreach (var dicParamEquipId in dicParamsEquipIds) - { - if (!tbRealData.Virtualformula.Contains($"`{dicParamEquipId.Key}`")) - { - continue; - } - if (dicParamEquipId.Value == null || dicParamEquipId.Value.Count() == 0) - { - continue; - } - //只支持一个设备 - var _document = documents.FirstOrDefault(t => dicParamEquipId.Value.Contains(t.EquipId)); - if (_document.Params == null || !_document.Params.ContainsKey(dicParamEquipId.Key.Split("$")[0])) - { - tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipId.Key}`", "0"); - } - else - { - tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipId.Key}`", _document.Params[dicParamEquipId.Key.Split("$")[0]].ToString()); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1};{2}", ex.Message, ex.StackTrace, tbRealData.Transarray)).GetNlogMessage()); - } - } - } - equipIds.Clear(); - dicParamsEquipIds.Clear(); - } - - - - foreach (var tbRealData in tbRealDatas) - { - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - try - { - tbRealData.Realvalue = FormulaUtil.InterperterFormula(tbRealData.Virtualformula).ToString(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters1", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0} {1};", ex.Message, ex.StackTrace)).GetNlogMessage()); - } - return tbRealDatas; - } - - /// - /// 计算虚拟参数历史值 - /// - /// - /// - /// - /// - /// - /// - public async Task> CalculationHisotryVirtualParameters(List tbRealDatasOrg, DateTime? startTime, DateTime? endTime, long projectId, short timeUnit = (short)QueryTimeTypeEnum.Hour) - { - //HourEP:小时电能耗、HourHE:小时热能耗 - //DayEP:日电能耗、DayHE:日热能耗 - //MonthEP:月电能耗、MonthHE:月热能耗 - var tbRealDatas = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(tbRealDatasOrg)); - var calHisVirDatas = new List { }; - try - { - using var scope = _serviceScopeFactory.CreateScope(); - //var timeSeqService = scope.ServiceProvider.GetRequiredService(); - var equipIds = new List { }; - - Dictionary> dicParamsEquipIds = new Dictionary> { }; - - var userCenterContext = scope.ServiceProvider.GetRequiredService(); - var standarParams = await userCenterContext.StandarParam.AsNoTracking().Select(t => new - { - t.Id, - t.Uniquepronoun - }).ToListAsync(); - - foreach (var tbRealData in tbRealDatas) - { - var calHisVirData = new RealTimeDBItemValueModel - { - RealId = tbRealData.Id, - Items = new List { } - }; - calHisVirDatas.Add(calHisVirData); - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - var formulaParams = tbRealData.Virtualformulaparam.Split("|").ToList(); - foreach (var formulaParam in formulaParams) - { - var _param = formulaParam.Split("=").ToList(); - dicParamsEquipIds.Add(_param[0], _param[1].Split(",").StrArrayToLongArray()); - } - foreach (var dicParamEquipIds in dicParamsEquipIds) - { - var dicParamEquipParams = dicParamEquipIds.Key.Split("$"); - if (virtualParameterUniqueCodes.Any(t => t == dicParamEquipParams[0])) - {//自定义标签 - var valueItems = await CalculationVirtualParameters(dicParamEquipIds.Value, dicParamEquipParams[0], projectId, timeUnit, startTime, endTime); - if (valueItems != null) - { - foreach (var valueItem in valueItems) - { - TimeDBItemValueModel _valueItem = calHisVirData.Items.FirstOrDefault(t => t.Time == valueItem.Time); - if (_valueItem == null) - { - _valueItem = valueItem; - calHisVirData.Items.Add(_valueItem); - } - if (string.IsNullOrEmpty(_valueItem.Virtualformula)) - { - _valueItem.Virtualformula = tbRealData.Virtualformula; - } - var formulaParam = $"`{dicParamEquipParams[0]}"; - if (dicParamEquipParams.Length > 1) - { - formulaParam += $"${dicParamEquipParams[1]}"; - } - formulaParam += "`"; - _valueItem.Virtualformula = _valueItem.Virtualformula.Replace(formulaParam, valueItem.Value.GetValueOrDefault().ToString()); - } - } - //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace($"`{dicParamEquipIds.Key}`", r.ToString()); - //var formulaParam = $"`{dicParamEquipParams[0]}"; - //if (dicParamEquipParams.Length > 1) - //{ - // formulaParam += $"${dicParamEquipParams[1]}"; - //} - //formulaParam += "`"; - //tbRealData.Virtualformula = tbRealData.Virtualformula.Replace(formulaParam, r.ToString()); - } - else - { - //原始 - equipIds.AddRange(dicParamEquipIds.Value); - } - } - if (equipIds.Count() > 0) - {//瞬时值 - if (string.IsNullOrWhiteSpace(tbRealData.Virtualformula)) - { - continue; - } - //var valueItems = await QueryEquipIntervalRealDataDoc(startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), projectId, equipIds.Distinct().ToList()); - //var documents = await _timeSeqService.QueryEquipRealDataDoc(DateTime.Now, projectId, equipIds.Distinct().ToList()); - //var documents = await _timeSeqService.QueryEquipIntervalRealDataDoc(startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), projectId, equipIds); - var equipReals = await _weiCloudDBContext.TbRealData.Where(t => t.Projectid == projectId && t.Equid != null && equipIds.Contains((long)t.Equid)).AsNoTracking().Select(t => new - { - t.Id, - t.Equid, - t.Standarparamid - }).ToListAsync(); - var equipRealIds = equipReals.Select(t => t.Id).ToList(); - var dataSourceV03Service = scope.ServiceProvider.GetRequiredService(); - var realDataItems = await dataSourceV03Service.GetHistorys(projectId, startTime.GetValueOrDefault(), endTime.GetValueOrDefault(), equipRealIds); - if (realDataItems.Count() > 0) - { - try - { - var times = realDataItems.Select(t => t.CreateTime).Distinct().ToList(); - foreach (var time in times) - { - var _valueItem = new TimeDBItemValueModel { Time = time, Virtualformula = tbRealData.Virtualformula }; - calHisVirData.Items.Add(_valueItem); - foreach (var dicParamEquipId in dicParamsEquipIds) - { - if (!tbRealData.Virtualformula.Contains($"`{dicParamEquipId.Key}`")) - { - continue; - } - if (dicParamEquipId.Value == null || dicParamEquipId.Value.Count() == 0) - { - continue; - } - //只支持一个设备 - - var standerCode = dicParamEquipId.Key.Split("$")[0]; - var standarParam = standarParams.FirstOrDefault(t => t.Uniquepronoun == standerCode); - if (standarParam == null) - { - continue; - } - var _equipReal = equipReals.FirstOrDefault(t => dicParamEquipId.Value.Contains((long)t.Equid) && t.Standarparamid == standarParam.Id); - - var _realDataItem = realDataItems.Where(t => _equipReal.Id == t.Id && t.CreateTime >= time.AddMinutes(-15) && t.CreateTime <= time).LastOrDefault(); - if (_realDataItem != null) - { - _valueItem.Virtualformula = _valueItem.Virtualformula.Replace($"`{dicParamEquipId.Key}`", _realDataItem.Value.ToString()); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationVirtualParameters", string.Format("抛出了异常信息: {0};{1};{2}", ex.Message, ex.StackTrace, tbRealData.Transarray)).GetNlogMessage()); - } - } - } - equipIds.Clear(); - dicParamsEquipIds.Clear(); - } - - - - foreach (var calHisVirData in calHisVirDatas) - { - if (calHisVirData.Items == null) - { - continue; - } - var failValueItems = new List { }; - foreach (var item in calHisVirData.Items) - { - if (string.IsNullOrWhiteSpace(item.Virtualformula)) - { - continue; - } - try - { - //item.Value = FormulaUtil.InterperterFormula(item.Virtualformula); - double _itemValue = 0; - var _itemValueResult = FormulaUtil.InterperterFormula(item.Virtualformula, ref _itemValue); - if (!_itemValueResult) - {//转换失败 - failValueItems.Add(item); - } - else - { - item.Value = _itemValue; - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationHisotryVirtualParameters1", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - } - if (failValueItems.Count() > 0) - { - calHisVirData.Items.RemoveAll(t => - { - return failValueItems.Any(f => t.Time == f.Time); - }); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " CalculationHisotryVirtualParameters", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return calHisVirDatas; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs deleted file mode 100644 index 15209f3..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/RealDataAnalyzeCoreService.cs +++ /dev/null @@ -1,110 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class RealDataAnalyzeCoreService: IRealDataAnalyzeCoreService - { - private readonly ILogger _logger; - private readonly IDictionaryService _dictionaryService; - private readonly WeiCloudDBContext _weiCloudDBContext; - private int INTERVAL = 60 * 10; //采集间隔 s - - public RealDataAnalyzeCoreService(ILogger logger, IDictionaryService dictionaryService, WeiCloudDBContext weiCloudDBContext) - { - _logger = logger; - _dictionaryService = dictionaryService; - _weiCloudDBContext = weiCloudDBContext; - } - /// - /// 根据设备id查询项目id - /// - /// - /// - private long? GetProjectIdByEquid(long? equid) - { - var equ = _dictionaryService.GetValue("EquipmentInfo", new string[] { equid.ToString() }).FirstOrDefault(); - var projectid = equ.Value.Projectid; - return projectid; - } - public class EquipStatus - { - /// - /// 设备上一个状态 - /// - public short? LastStatus { get; set; } - /// - /// 设备当前状态 - /// - public short? CurrentStatus { get; set; } - } - /// - /// 根据设备id 获取设备的运行状态 - /// - /// 设备ids - /// - public async Task>> GetEquCommStatusAsync(List equids) - { - var result = new ApiResult>() { Code = RequestBackStatuEnum.success.Value, Msg = "获取成功" }; - List equCommStatus = new List(); - try - { - long? projectId = 0; - foreach (var equid in equids) - {//存在redis和数据库数据不一致问题 - try - { - projectId = GetProjectIdByEquid(equid); - } - catch (Exception) - { - - } - if (projectId != null && projectId > 0) - { - break; - } - } - var temp = _dictionaryService.GetValue("EquipStatusPro_" + projectId.ToString()); - foreach (var item in equids) - { - if (!temp.ContainsKey(item.ToString())) //检测如果不存在则添加 - { - equCommStatus.Add(new EquCommStatus - { - EquId = item, - CurrentStatus = 3 - }); - - } - else - { - equCommStatus.Add(new EquCommStatus - { - EquId = item, - CurrentStatus = temp[item.ToString()].CurrentStatus - }); - } - } - result.Data = equCommStatus; - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEquCommStatusAsync", string.Format("执行异常/n/n {0}", ex.Message)).GetNlogMessage()); - result.Data = equCommStatus; - result.Code = RequestBackStatuEnum.fail.Value; - result.Msg = ex.Message; - } - return await Task.FromResult(result); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs deleted file mode 100644 index 6339345..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceService.cs +++ /dev/null @@ -1,284 +0,0 @@ -using AutoMapper; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.RealData; -using WeiCloud.Core.Report; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.DataSource; - -namespace WeiCloud.Core.Services.Report -{ - public class DataSourceCoreService : IDataSourceCoreService - { - private readonly WeiCloudDBDataSourceContext _dataSourceContext; - private readonly WeiCloudDBContext _context; - private readonly IDictionaryService _dictionaryService; - private readonly ILogger _logger; - private readonly IRealDataCoreService _realDataCoreService; - private readonly IRealDataAnalyzeCoreService _realDataAnalyzeCoreService; - private readonly IMapper _mapper; - public DataSourceCoreService(WeiCloudDBContext context, IRealDataAnalyzeCoreService realDataAnalyzeCoreService, IMapper mapper, WeiCloudDBDataSourceContext dataSourceContext, IDictionaryService dictionaryService, ILogger logger, IRealDataCoreService realDataCoreService) - { - _context = context; - _dataSourceContext = dataSourceContext; - _dictionaryService = dictionaryService; - _logger = logger; - _realDataCoreService = realDataCoreService; - _mapper = mapper; - _realDataAnalyzeCoreService = realDataAnalyzeCoreService; - } - /// - /// 获取配置值 - /// - /// - /// - public async Task GetDataSource(long dataSourceId) - { - var result = new DataSourceModel - { - Items = new List - { - - } - }; - try - { - var dataSource = _dataSourceContext.DtDataSource.AsNoTracking().TagWith("SubDB").FirstOrDefault(t => t.Id == dataSourceId); - var dataSouceMaps = await _dataSourceContext.DtDataSouceMap.Where(t => t.DataSourceId == dataSourceId).AsNoTracking().TagWith("SubDB").ToListAsync(); - result.Title = dataSource.Title; - result.ProjectId = dataSource.ProjectId; - var dataSouceMap1s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); - var realIds = dataSouceMap1s.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); - var dataSouceMapModels = new List(); - if (realIds != null && realIds.Count() > 0) - { - var realDatas = await _realDataCoreService.GetRealValueFromRedisByPro(dataSource.ProjectId); - foreach (var dataSouceMap1 in dataSouceMap1s) - { - var realData = realDatas.FirstOrDefault(t => t.Id == dataSouceMap1.SourceId); - if (realData == null) - { - continue; - } - var dataSouceMapItem = _mapper.Map(dataSouceMap1); - var value = 0d; - double.TryParse(realData.Realvalue, out value); - dataSouceMapItem.Value = value; - dataSouceMapModels.Add(dataSouceMapItem); - } - var groups = dataSouceMapModels.Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); - foreach (var group in groups) - { - #region 平均值 - var dataSouceMapGroups = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Average).ToList(); - if (dataSouceMapGroups != null && dataSouceMapGroups.Count() > 0) - { - var dataSouceMapGroupAverages = dataSouceMapGroups.GroupBy(t => new - { - t.Parm, - t.Tag - }).Select(t => new - { - Parm = t.Key.Parm, - Tag = t.Key.Tag, - Value = t.Average(a => a.Value) - }).ToList(); - foreach (var dataSouceMapGroupAverage in dataSouceMapGroupAverages) - { - result.Items.Add(new DataSourceItemModel - { - GroupId = group.GroupId, - GroupParm = group.GroupParm, - GroupTag = group.GroupTag, - Parm = dataSouceMapGroupAverage.Parm, - Tag = dataSouceMapGroupAverage.Tag, - Value = dataSouceMapGroupAverage.Value - }); - } - } - #endregion - #region 组 - //var dataSouceMapGroup2s = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Common).ToList(); - //if(dataSouceMapGroup2s) - #endregion - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetDataSource", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - - - public async Task> GetDataSource_v1(JObject input) - { - var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = new DataSourceModel_v1 { ItemsExplain = new List { }, Data = new JObject { } } }; - try - { - long dataSourceId = 0; - long.TryParse(input["dataSourceId"].ToString(), out dataSourceId); - if (dataSourceId == 0) - { - result.Code = RequestBackStatuEnum.badrequest.Value; - result.Msg = "dataSourceId必填!"; - return result; - } - var dataSource = _dataSourceContext.DtDataSource.AsNoTracking().TagWith("SubDB").FirstOrDefault(t => t.Id == dataSourceId); - var queryDataSouceMap = _dataSourceContext.DtDataSouceMap.Where(t => t.DataSourceId == dataSourceId); - if (!string.IsNullOrWhiteSpace(dataSource.QueryTerms)) - { - try - { - var queryTerms = JsonConvert.DeserializeObject>(dataSource.QueryTerms); - foreach (var queryTerm in queryTerms) - { - if(queryTerm.Field== "constId") - { - long constId = 0; - long.TryParse(input["constId"]?.ToString(), out constId); - if (queryTerm.Operation == "equal" && constId > 0) - { - var equipIds = await _context.EquipmentInfo.Where(t => t.Constid == constId && t.State == 1).AsNoTracking().TagWith("SubDB").Select(t => t.Id).ToListAsync(); - queryDataSouceMap = queryDataSouceMap.Where(t => equipIds.Contains(t.EquipId)); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "GetDataSource_v1", string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - } - - var dataSouceMaps = await queryDataSouceMap.AsNoTracking().ToListAsync(); - result.Data.Title = dataSource.Title; - #region 获取实时Id - var dataSouceMap1s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); - var realIds = dataSouceMap1s.Where(t => t.SourceType == ReportSourceTypeEnum.RealTime).ToList(); - var dataSouceMapModels = new List(); - if (realIds != null && realIds.Count() > 0) - { - #region 获取实时值 - var realDatas = await _realDataCoreService.GetRealValueFromRedisByPro(dataSource.ProjectId); - foreach (var dataSouceMap1 in dataSouceMap1s) - { - var realData = realDatas.FirstOrDefault(t => t.Id == dataSouceMap1.SourceId); - if (realData == null) - { - continue; - } - var dataSouceMapItem = _mapper.Map(dataSouceMap1); - var value = 0d; - double.TryParse(realData.Realvalue, out value); - dataSouceMapItem.Value = Math.Round(value, 2); - dataSouceMapModels.Add(dataSouceMapItem); - } - #endregion - } - #endregion - - #region 获取状态值 - var dataSouceMap2s = dataSouceMaps.Where(t => t.SourceType == ReportSourceTypeEnum.Status).ToList(); - if (dataSouceMap2s != null && dataSouceMap2s.Count() > 0) - { - var equipIds = dataSouceMap2s.Select(t => (long?)t.EquipId).Distinct().ToList(); - var equipsCommStatus = await _realDataAnalyzeCoreService.GetEquCommStatusAsync(equipIds); - foreach (var dataSouceMap2 in dataSouceMap2s) - { - var _equipsCommStatus = equipsCommStatus.Data.FirstOrDefault(t => t.EquId == dataSouceMap2.EquipId); - if (_equipsCommStatus == null) - { - continue; - } - var dataSouceMapItem = _mapper.Map(dataSouceMap2); - dataSouceMapItem.Value = _equipsCommStatus.CurrentStatus ?? 0; - dataSouceMapModels.Add(dataSouceMapItem); - } - } - #endregion - var group0s = dataSouceMapModels.Where(t => t.GroupCalculate == ReportGroupCalculateEnum.Common && t.GroupParentId == 0).Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); - if (group0s != null && group0s.Count() > 0) - { - var items = new JArray { }; - foreach (var group in group0s) - { - #region 组 - var dataSouceMapGroup2s = dataSouceMapModels.Where(t => t.GroupId == group.GroupId && t.GroupCalculate == ReportGroupCalculateEnum.Common).ToList(); - if (dataSouceMapGroup2s != null && dataSouceMapGroup2s.Count() > 0) - { - var item = new JObject { }; - item["GroupTag"] = group.GroupTag; - item["GroupParm"] = group.GroupParm; - foreach (var dataSouceMapGroup2 in dataSouceMapGroup2s) - { - item[dataSouceMapGroup2.Parm] = dataSouceMapGroup2.Value; - result.Data.ItemsExplain.Add(new ItemExplain - { - GroupTag = dataSouceMapGroup2.GroupTag, - GroupParm = dataSouceMapGroup2.GroupParm, - Parm = dataSouceMapGroup2.Parm, - Tag = dataSouceMapGroup2.Tag - }); - } - items.Add(item); - } - #endregion - } - result.Data.Data["Items"] = items; - } - - - var group1s = dataSouceMapModels.Where(t => t.GroupCalculate == ReportGroupCalculateEnum.Average).Select(t => new { t.GroupId, t.GroupParm, t.GroupTag }).Distinct().ToList(); - foreach (var group in group1s) - { - #region 平均值 - var dataSouceMapGroups = dataSouceMapModels.Where(t => t.GroupId == group.GroupId).ToList(); - if (dataSouceMapGroups != null && dataSouceMapGroups.Count() > 0) - { - var dataSouceMapGroupAverages = dataSouceMapGroups.GroupBy(t => new - { - t.Parm, - t.Tag - }).Select(t => new - { - Parm = t.Key.Parm, - Tag = t.Key.Tag, - Value = t.Average(a => a.Value) - }).ToList(); - foreach (var dataSouceMapGroupAverage in dataSouceMapGroupAverages) - { - result.Data.Data[dataSouceMapGroupAverage.Parm] = dataSouceMapGroupAverage.Value; - result.Data.ItemsExplain.Add(new ItemExplain - { - GroupTag = group.GroupTag, - GroupParm = group.GroupParm, - Parm = dataSouceMapGroupAverage.Parm, - Tag = dataSouceMapGroupAverage.Tag - }); - } - } - #endregion - } - - result.Data.ItemsExplain = result.Data.ItemsExplain.Distinct().ToList(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetDataSource", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs deleted file mode 100644 index 96135bb..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV02Service.cs +++ /dev/null @@ -1,1086 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Report; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.Report -{ - public class DataSourceV02Service : IDataSourceV02Service - { - private readonly ILogger _logger; - private readonly WeiCloudAirDBContext _airDBContext; - private readonly WeiCloudDBContext _context; - public DataSourceV02Service(ILogger logger, WeiCloudDBContext context, WeiCloudAirDBContext airDBContext) - { - _logger = logger; - _airDBContext = airDBContext; - _context = context; - } - /// - /// 能耗列表 - /// - /// - /// - public async Task> GetEnergyConsum(QueryDataSourceEnergyConsumModel input) - { - var result = new ResultPageModel { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - if (input.ProjectId <= 0 && (input.ProjectIds == null || input.ProjectIds.Count() == 0 || input.ProjectIds.Any(t => t < 0))) - { - result.Code = RequestBackStatuEnum.diy.Value; - result.Msg = "项目Id不能为空!"; - return result; - } - if ((!input.StartTimeDay.HasValue || !input.EndTimeDay.HasValue) - && (!input.StartTimeHour.HasValue || !input.EndTimeHour.HasValue)) - { - result.Code = RequestBackStatuEnum.diy.Value; - result.Msg = "日期不能为空!"; - return result; - } - try - { - var equipQuery = _context.EquipmentInfo.Where(t => t.State == 1).AsQueryable(); - if (input.ProjectId > 0) - { - equipQuery = equipQuery.Where(t => t.Projectid == input.ProjectId); - } - if (input.ProjectIds != null && input.ProjectIds.Count() > 0) - { - equipQuery = equipQuery.Where(t => t.Projectid != null && input.ProjectIds.Contains((long)t.Projectid)); - } - - if (input.EquipId > 0) - { - equipQuery = equipQuery.Where(t => t.Id == input.EquipId); - } - if (input.EquipIds != null && input.EquipIds.Count() > 0) - { - equipQuery = equipQuery.Where(t => input.EquipIds.Contains(t.Id)); - } - if (input.ConsturctId > 0) - { - equipQuery = equipQuery.Where(t => t.Constid == input.ConsturctId); - } - if (input.ConsturctIds != null && input.ConsturctIds.Count() > 0) - { - equipQuery = equipQuery.Where(t => t.Constid != null && input.ConsturctIds.Contains((long)t.Constid)); - } - if (!string.IsNullOrWhiteSpace(input.KeyWord)) - { - equipQuery = equipQuery.Where(t => t.Eqname.Contains(input.KeyWord)); - } - //result.TotalCount = equipQuery.Count(); - //if (input.PageSize > 0 && input.PageIndex > 0) - //{ - // equipQuery = equipQuery.Skip((input.PageIndex - 1) * input.PageSize); - //} - var equipInfos = await equipQuery.AsNoTracking().ToListAsync(); - if (equipInfos.Count() == 0) - { - return result; - } - var equipIds = equipInfos.Select(t => t.Id).ToList(); - var timeQuery = _airDBContext.Times.AsQueryable(); - var startTime = DateTime.MinValue; - var endTime = DateTime.MinValue; - if (input.StartTimeDay.HasValue) - { - startTime = DateTime.Parse(input.StartTimeDay.Value.ToString("yyyy-MM-dd")); - endTime = DateTime.Parse(input.EndTimeDay.Value.ToString("yyyy-MM-dd")).AddDays(1); - } - else if (input.StartTimeHour.HasValue) - { - startTime = DateTime.Parse(input.StartTimeDay.Value.ToString("yyyy-MM-dd HH:00:00")); - endTime = DateTime.Parse(input.EndTimeDay.Value.ToString("yyyy-MM-dd HH:00:00")).AddHours(1); - } - timeQuery = timeQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime); - var timers = await timeQuery.AsNoTracking().ToListAsync(); - var timeIds = timers.Select(t => t.Id).ToList(); - var energyConsumeDBItems = new List { }; - - IQueryable dwQuery = null; - if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.ElectricPower - || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.ElectricPower)) - || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) - { - var ammeterDwQuery = _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).Select(t => new DataSourceEnergyConsumDBItemModel - { - EquipId = t.Parm002 ?? 0, - Consume = t.AmParm003 ?? 0, - Unit = "kWh", - EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.ElectricPower, - TimeId = t.Parm001 - }); - if (dwQuery == null) - { - dwQuery = ammeterDwQuery; - } - else - { - dwQuery.Union(ammeterDwQuery); - } - } - if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Gas - || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Gas)) - || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) - { - var gasDwQuery = _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - { - EquipId = t.Parm002 ?? 0, - Consume = t.GmParm002 ?? 0, - Unit = "m³", - EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Gas, - TimeId = t.Parm001 - }); - if (dwQuery == null) - { - dwQuery = gasDwQuery; - } - else - { - dwQuery.Union(gasDwQuery); - } - } - if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Heat - || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Heat)) - || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) - { - var heatDwQuery = _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - { - EquipId = t.Parm002 ?? 0, - Consume = t.HmParm001 ?? 0, - Unit = "GJ", - EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Heat, - TimeId = t.Parm001 - }); - if (dwQuery == null) - { - dwQuery = heatDwQuery; - } - else - { - dwQuery.Union(heatDwQuery); - } - } - if (input.EnergyConsumeType == (short)ReportEnergyConsumeTypeEnum.Water - || (input.EnergyConsumeTypes != null && input.EnergyConsumeTypes.Contains((short)ReportEnergyConsumeTypeEnum.Water)) - || (input.EnergyConsumeType == 0 && (input.EnergyConsumeTypes == null || input.EnergyConsumeTypes.Count() == 0))) - { - var waterDwQuery = _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).OrderByDescending(t => t.Parm003).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - { - EquipId = t.Parm002 ?? 0, - Consume = t.WmParm002 ?? 0, - Unit = "t", - EnergyConsumeType = (short)ReportEnergyConsumeTypeEnum.Water, - TimeId = t.Parm001 - }); - if (dwQuery == null) - { - dwQuery = waterDwQuery; - } - else - { - dwQuery.Union(waterDwQuery); - } - } - result.TotalCount = dwQuery.Count(); - if (input.PageSize > 0 && input.PageIndex > 0) - { - dwQuery = dwQuery.Skip((input.PageIndex - 1) * input.PageSize); - } - var resultItems = await dwQuery.AsNoTracking().ToListAsync(); - var constIds = equipInfos.Select(t => t.Constid ?? 0).Distinct().ToList(); - var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - foreach (var resultItem in resultItems) - { - var equipInfo = equipInfos.FirstOrDefault(t => t.Id == resultItem.EquipId); - - result.Data.Add(new DataSourceEnergyConsumModel - { - EquipId = resultItem.EquipId, - EquipName = equipInfo.Eqname, - - }); - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - - /// - /// 获取数据表 - /// - /// - public async Task>> GetDataTables() - { - var result = new ApiResult> { Code = RequestBackStatuEnum.success.Value, Data = new List { } }; - try - { - var iotLabelTypes = await _context.IotLabelType.Where(t => t.IsDeleted == false).AsNoTracking().ToListAsync(); - var levelIotLabelTypes = iotLabelTypes.Where(t => t.ParentId == 0).ToList(); - foreach (var levelIotLabelType in levelIotLabelTypes) - { - var pItem = new DataSourceDataTableModel - { - Id = levelIotLabelType.Id, - Name = levelIotLabelType.Name, - Remark = levelIotLabelType.Remark - }; - if (!string.IsNullOrEmpty(levelIotLabelType.Dimension)) - { - pItem.Dimensions = JsonConvert.DeserializeObject>(levelIotLabelType.Dimension); - } - result.Data.Add(pItem); - var childIotLabelTypes = iotLabelTypes.Where(t => t.ParentId == levelIotLabelType.Id).ToList(); - foreach (var childIotLabelType in childIotLabelTypes) - { - var cItem = new DataSourceDataTableModel - { - Id = childIotLabelType.Id, - Name = childIotLabelType.Name, - Remark = childIotLabelType.Remark - }; - if (!string.IsNullOrEmpty(childIotLabelType.Inputs)) - { - cItem.QueryParams = JsonConvert.DeserializeObject>(childIotLabelType.Inputs); - } - if (!string.IsNullOrEmpty(childIotLabelType.Outputs)) - { - cItem.ReturnParams = JsonConvert.DeserializeObject>(childIotLabelType.Outputs); - } - pItem.Childs.Add(cItem); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - /// - /// 维度-时间 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private List>> GetDataSourceDataByTime(List labels, DateTime? startTime, DateTime? endTime, string dimension, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) - { - var result = new List>>(); - var _startTime = startTime.GetValueOrDefault(); - var _endTime = _startTime; - - while (_startTime < endTime) - { - if (_startTime > DateTime.Now) - { - break; - } - var timeUnit = string.Empty; - if (dimension == IOTLabelDimensionEnum.TimeHour) - { - _endTime = _startTime.AddHours(1); - timeUnit = _startTime.ToString("yyyy-MM-dd HH"); - } - else if (dimension == IOTLabelDimensionEnum.TimeDay) - { - _endTime = _startTime.AddDays(1); - timeUnit = _startTime.ToString("yyyy-MM-dd"); - } - else if (dimension == IOTLabelDimensionEnum.TimeMonth) - { - _endTime = _startTime.AddMonths(1); - timeUnit = _startTime.ToString("yyyy-MM"); - } - else if (dimension == IOTLabelDimensionEnum.TimeYear) - { - _endTime = _startTime.AddYears(1); - timeUnit = _startTime.ToString("yyyy"); - } - foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) - { - var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); - var _timeIds = times.Where(t => t.Fulldatetime >= _startTime && t.Fulldatetime < _endTime).Select(t => t.Id).ToList(); - //var _consume = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).Sum(s => s.Consume); - var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).ToList()); - - var item = result.FirstOrDefault(t => t.Name == iotLabelType.Name); - if (item == null) - { - item = new DataSourceDataModel> { Name = iotLabelType.Name, Data = new List { } }; - result.Add(item); - } - item.Data.Add(new DataSourceDataItemModel - { - Time = timeUnit, - Value = Math.Round(_consume, 2).ToString() - }); - } - _startTime = _endTime; - } - return result; - } - private double CalConsume(short calculation, List dws) - { - double r = 0; - switch (calculation) - { - case (short)IOTLabelCalculateEnum.Sum: - r = dws.Sum(s => s.Consume); - break; - case (short)IOTLabelCalculateEnum.Average: - r = dws.Average(s => s.Consume); - break; - case (short)IOTLabelCalculateEnum.Max: - r = dws.Max(s => s.Consume); - break; - //case (short)IOTLabelCalculateEnum.DuplicateRemoval: - // r = dws.Distinct(s => s.Consume); - // break; - case (short)IOTLabelCalculateEnum.Count: - r = dws.Count(); - break; - case (short)IOTLabelCalculateEnum.Min: - r = dws.Min(s => s.Consume); - break; - } - return r; - } - /// - /// 维度-设备 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private async Task>> GetDataSourceDataByEquip(List labels, DateTime? startTime, DateTime? endTime, List constructionInfos, List equipInfos, List dws, List dimensions, List times, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) - { - var result = new List>(); - foreach (var equipInfo in equipInfos) - { - if (dimensions.Count() == 1) - { - //var _consume = dws.Where(t => t.EquipId == equipInfo.Id).Sum(s => s.Consume); - var dicIotLabelEquipId = dicIotLabelEquipIds.FirstOrDefault(t => t.Value.Any(v => v == equipInfo.Id)); - var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, dws.Where(t => t.EquipId == equipInfo.Id).ToList()); - result.Add(new DataSourceDataModel - { - Name = equipInfo.Eqname, - Data = Math.Round(_consume, 2).ToString() - }); - } - else if (dimensions.Count() > 1) - { - result.Add(new DataSourceDataModel - { - Name = equipInfo.Eqname, - Data = await GetDataSourceData(labels, startTime, endTime, dimensions.Skip(1).ToList(), times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos) - }); - } - } - return result; - } - /// - /// 建筑物 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - private async Task>> GetDataSourceDataByConstruct(List labels, DateTime? startTime, DateTime? endTime, List constructionInfos, List equipInfos, List dws, List dimensions, List times, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) - { - var result = new List>(); - foreach (var constructionInfo in constructionInfos) - { - if (dimensions.Count() == 1) - { - var equipIds = equipInfos.Where(t => t.Constid == constructionInfo.Id).Select(t => t.Id).ToList(); - //var _consume = dws.Where(t => equipIds.Contains(t.EquipId)).Sum(s => s.Consume); - var _consume = CalConsume(labels.First().Calculation, dws.Where(t => equipIds.Contains(t.EquipId)).ToList()); - result.Add(new DataSourceDataModel - { - Name = constructionInfo.Constinfo, - Data = Math.Round(_consume, 2).ToString() - }); - } - else if (dimensions.Count() > 1) - { - result.Add(new DataSourceDataModel - { - Name = constructionInfo.Constinfo, - Data = await GetDataSourceData(labels,startTime, endTime, dimensions.Skip(1).ToList(), times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos) - }); - } - } - return result; - } - - private async Task GetDataSourceData(List labels, DateTime? startTime, DateTime? endTime, - List dimensions, List times, List dws, - Dictionary> dicIotLabelEquipIds, List iotLabelTypes, List equipInfos, List constructionInfos) - { - if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Equip) - { - var r = GetDataSourceDataByEquip(labels, startTime, endTime, constructionInfos, equipInfos, dws, dimensions, times, dicIotLabelEquipIds, iotLabelTypes); - return await r; - } - else if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeYear - || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeMonth - || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeDay - || dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeHour) - { - var r = GetDataSourceDataByTime(labels, startTime, endTime, dimensions.FirstOrDefault(), times, dws, dicIotLabelEquipIds, iotLabelTypes); - return r; - } - else if (dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Consturct) - { - var constIds = equipInfos.Select(t => t.Constid ?? 0).ToList(); - //var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - var r = GetDataSourceDataByConstruct(labels, startTime, endTime, constructionInfos.Where(t => constIds.Contains(t.Id)).ToList(), equipInfos, dws, dimensions, times, dicIotLabelEquipIds, iotLabelTypes); - return await r; - } - return null; - } - - private async Task GetDataSourceDataV02(List labels, DateTime? startTime, DateTime? endTime, List dimensions, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes, List equipInfos, List constructionInfos) - { - var result = new List { }; - var groupKeys = new List { }; - foreach (var dimension in dimensions) - { - if (dimension == IOTLabelDimensionEnum.Equip) - { - groupKeys.Add("EquipName"); - } - else if (dimension == IOTLabelDimensionEnum.TimeYear) - { - groupKeys.Add("Year"); - } - else if (dimension == IOTLabelDimensionEnum.TimeMonth) - { - groupKeys.Add("YearMonth"); - } - else if (dimension == IOTLabelDimensionEnum.TimeDay) - { - groupKeys.Add("YearMonthDay"); - } - else if (dimension == IOTLabelDimensionEnum.TimeHour) - { - groupKeys.Add("YearMonthDayHour"); - } - else if (dimension == IOTLabelDimensionEnum.Consturct) - { - groupKeys.Add("ConstName"); - } - } - //var query = dws.DynamicGroupBy(new string[] { "EquipId" }); - var queryItems = dws.DynamicGroupBy(groupKeys.ToArray()); - foreach (var queryItem in queryItems) - { - var resultItem = new List { }; - var keys = queryItem.Key.Select(t => t.ToString()).ToList(); - - resultItem.AddRange(keys); - var _dws = ((WeiCloud.Core.Services.Report.LinqExt.DGroupBy)queryItem)._innerlist; - foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) - { - var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); - var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, _dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId)).ToList()); - resultItem.Add(Math.Round(_consume, 2)); - } - result.Add(resultItem); - } - return result; - } - private List GetDataSourceDataByTimeV02(List labels, DateTime? startTime, DateTime? endTime, List equipInfos, List constructionInfos, string dimension, List otherDimensions, List times, List dws, Dictionary> dicIotLabelEquipIds, List iotLabelTypes) - { - var result = new List(); - var _startTime = startTime.GetValueOrDefault(); - var _endTime = _startTime; - - while (_startTime < endTime) - { - var resultItem = new List(); - if (_startTime > DateTime.Now) - { - break; - } - var timeUnit = string.Empty; - if (dimension == IOTLabelDimensionEnum.TimeHour) - { - _endTime = _startTime.AddHours(1); - timeUnit = _startTime.ToString("yyyy-MM-dd HH"); - } - else if (dimension == IOTLabelDimensionEnum.TimeDay) - { - _endTime = _startTime.AddDays(1); - timeUnit = _startTime.ToString("yyyy-MM-dd"); - } - else if (dimension == IOTLabelDimensionEnum.TimeMonth) - { - _endTime = _startTime.AddMonths(1); - timeUnit = _startTime.ToString("yyyy-MM"); - } - else if (dimension == IOTLabelDimensionEnum.TimeYear) - { - _endTime = _startTime.AddYears(1); - timeUnit = _startTime.ToString("yyyy"); - } - resultItem.Add(timeUnit); - if (otherDimensions.Count() > 0) - { - foreach (var otherDimension in otherDimensions) - { - if (otherDimension == IOTLabelDimensionEnum.Consturct) - { - //resultItem.Add(otherDimension); - foreach (var constructionInfo in constructionInfos) - { - resultItem.Add(constructionInfo.Constinfo); - } - } - } - } - else - { - - } - - var _timeIds = times.Where(t => t.Fulldatetime >= _startTime && t.Fulldatetime < _endTime).Select(t => t.Id).ToList(); - //var consumeList = GetCalConsume(constructionInfos, equipInfos, otherDimensions, dicIotLabelEquipIds, labels, _timeIds, iotLabelTypes); - _startTime = _endTime; - result.Add(resultItem); - } - return result; - } - private List GetCalConsume(List constructionInfos, List equipInfos, List otherDimensions, List dws, Dictionary> dicIotLabelEquipIds, List labels, List _timeIds, List iotLabelTypes) - { - var result = new List(); - - - foreach (var dicIotLabelEquipId in dicIotLabelEquipIds) - { - var iotLabelType = iotLabelTypes.FirstOrDefault(t => t.Id == dicIotLabelEquipId.Key); - - foreach (var otherDimension in otherDimensions) - { - if (otherDimension == "Consturct") - { - - } - } - //var _consume = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).Sum(s => s.Consume); - var _dws = dws.Where(t => dicIotLabelEquipId.Value.Contains(t.EquipId) && _timeIds.Contains(t.TimeId)).ToList(); - var _consume = CalConsume(labels.First(t => t.LabelId == dicIotLabelEquipId.Key).Calculation, _dws); - - result.Add(_consume); - } - return result; - } - /// - /// 获取数据 - /// - /// - /// - //public async Task> GetDataSourceData(GetDataSourceDataModel input) - //{ - // var result = new ApiResult { Code = RequestBackStatuEnum.success.Value, Data = new object { } }; - // try - // { - // //if (input.Dimensions == null || input.Dimensions.Count() == 0) - // //{ - // // result.Code = RequestBackStatuEnum.diy.Value; - // // result.Msg = "维度不能为空!"; - // // return result; - // //} - // //if (input.Labels == null || input.Labels.Count() == 0) - // //{ - // // result.Code = RequestBackStatuEnum.diy.Value; - // // result.Msg = "项目Id不能为空!"; - // // return result; - // //} - - // if ((input.Dimensions == null || input.Dimensions.Count() == 0) && (input.Labels == null || input.Labels.Count() == 0)) - // { - // result.Code = RequestBackStatuEnum.diy.Value; - // result.Msg = "维度或者指标不能为空!"; - // return result; - // } - - // var labelIds = input.Labels.Select(t => t.LabelId).ToList(); - // var iotLabelTypes = await _context.IotLabelType.Where(t => labelIds.Contains(t.Id) && t.IsDeleted == false).AsNoTracking().ToListAsync(); - // if (iotLabelTypes.Count() == 0 || !iotLabelTypes.Any(t => t.ParentId > 0)) - // { - // result.Code = RequestBackStatuEnum.diy.Value; - // result.Msg = "标签未找到!"; - // return result; - // } - // #region 条件 - // DateTime? startTime = DateTime.MinValue; - // DateTime? endTime = DateTime.Now; - // //var queryTimeType = (short)QueryTimeTypeEnum.Day; - - // if (input.Query != null && input.Query.ContainsKey("TimeDay")) - // { - // startTime = DateTime.Parse(input.Query["TimeDay"].ToString()); - // endTime = startTime.GetValueOrDefault().AddDays(1); - // //queryTimeType = (short)QueryTimeTypeEnum.Day; - // } - // else if (input.Query != null && input.Query.ContainsKey("TimeMonth")) - // { - // startTime = DateTime.Parse($"{input.Query["TimeMonth"].ToString()}-01"); - // endTime = startTime.GetValueOrDefault().AddMonths(1); - // //queryTimeType = (short)QueryTimeTypeEnum.Month; - // } - // else if (input.Query != null && input.Query.ContainsKey("TimeYear")) - // { - // startTime = DateTime.Parse($"{input.Query["TimeYear"].ToString()}-01-01"); - // endTime = startTime.GetValueOrDefault().AddYears(1); - // //queryTimeType = (short)QueryTimeTypeEnum.Year; - // } - // else if (input.Query != null && input.Query.ContainsKey("StartTimeDay") && input.Query.ContainsKey("EndTimeDay")) - // { - // startTime = DateTime.Parse(input.Query["StartTimeDay"].ToString()); - // endTime = DateTime.Parse(input.Query["EndTimeDay"].ToString()).AddDays(1); - // //queryTimeType = (short)QueryTimeTypeEnum.Custom; - // } - // if (startTime != null && startTime >= DateTime.Now) - // { - // result.Code = RequestBackStatuEnum.diy.Value; - // result.Msg = "开始时间不能大于当前时间!"; - // return result; - // } - // #endregion - - - // var labelType = iotLabelTypes.FirstOrDefault(t => t.Type > 0).Type; - // var iotLabelTypeIds = iotLabelTypes.Select(t => t.Id).ToList(); - // var iotThingAttributes = await _context.IotThingAttribute.Where(t => iotLabelTypeIds.Contains(t.LabelCodeId) && t.IsDeleted == false).AsNoTracking().ToListAsync(); - // var equipIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Equip && t.IsDeleted == false).Select(t => t.ThingId).ToList(); - // var constructIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Construct && t.IsDeleted == false).Select(t => t.ThingId).ToList(); - // var paramIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Param && t.IsDeleted == false).Select(t => t.ThingId).ToList(); - // var projectIds = iotThingAttributes.Where(t => t.ThingType == (short)IOTThingTypeEnum.Project && t.IsDeleted == false).Select(t => t.ThingId).ToList(); - // var queryEquipInfos = _context.EquipmentInfo.Where(t => t.State == 1); - - // if (input.Query!=null && input.Query.ContainsKey("EquipId")) - // { - // var _equipId = long.Parse(input.Query["EquipId"].ToString()); - // queryEquipInfos = queryEquipInfos.Where(t => t.Id == _equipId); - // } - // else if (input.Query != null && input.Query.ContainsKey("EquipIds")) - // { - // var _equipIds = JsonConvert.DeserializeObject>(input.Query["EquipIds"].ToString()); - // queryEquipInfos = queryEquipInfos.Where(t => _equipIds.Contains(t.Id)); - // } - // if (input.Query != null && input.Query.ContainsKey("ConsturctId")) - // { - // var _consturctId = long.Parse(input.Query["ConsturctId"].ToString()); - // queryEquipInfos = queryEquipInfos.Where(t => t.Constid == _consturctId); - // } - // else if (input.Query != null && input.Query.ContainsKey("ConsturctIds")) - // { - // var _consturctIds = JsonConvert.DeserializeObject>(input.Query["ConsturctIds"].ToString()); - // queryEquipInfos = queryEquipInfos.Where(t => t.Constid != null && _consturctIds.Contains((long)t.Constid)); - // } - // if (projectIds.Count() > 0) - // { - // queryEquipInfos = queryEquipInfos.Where(t => t.Projectid != null && projectIds.Contains((long)t.Projectid)); - // } - // if (constructIds.Count() > 0) - // { - // queryEquipInfos = queryEquipInfos.Where(t => t.Constid != null && constructIds.Contains((long)t.Constid)); - // } - // List realDatas = null; - // if (paramIds.Count() > 0) - // { - // realDatas = await _context.TbRealData.Where(t => paramIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - // var realDataEquipIds = realDatas.Select(t => t.Equid ?? 0).ToList(); - // equipIds.AddRange(realDataEquipIds); - // } - // if (equipIds.Count() > 0) - // { - // queryEquipInfos = queryEquipInfos.Where(t => equipIds.Contains(t.Id)); - // } - - // Dictionary> dicIotLabelEquipIds = new Dictionary> { }; - // foreach (var iotLabelType in iotLabelTypes) - // { - // var _equipIds = new List(); - // var _iotThingAttributes = iotThingAttributes.Where(t => t.LabelCodeId == iotLabelType.Id).ToList(); - // foreach (var _iotThingAttribute in _iotThingAttributes) - // { - // if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Equip) - // { - // _equipIds.Add(_iotThingAttribute.ThingId); - // } - // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Construct) - // { - // var __equipIds = queryEquipInfos.Where(t => _iotThingAttribute.ThingId == t.Constid).Select(t => t.Id).ToList(); - // if (__equipIds.Count() > 0) - // { - // _equipIds.AddRange(__equipIds); - // } - // } - // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Project) - // { - // var __equipIds = queryEquipInfos.Where(t => _iotThingAttribute.ThingId == t.Projectid).Select(t => t.Id).ToList(); - // if (__equipIds.Count() > 0) - // { - // _equipIds.AddRange(__equipIds); - // } - // } - // else if (_iotThingAttribute.ThingType == (short)IOTThingTypeEnum.Param) - // { - // var __equipIds = realDatas.Where(t => _iotThingAttribute.ThingId == t.Id).Select(t => t.Equid ?? 0).ToList(); - // if (__equipIds.Count() > 0) - // { - // _equipIds.AddRange(__equipIds); - // } - // } - // } - - // _equipIds = _equipIds.Distinct().ToList(); - // dicIotLabelEquipIds.Add(iotLabelType.Id, _equipIds); - // } - // var equipInfos = await queryEquipInfos.AsNoTracking().ToListAsync(); - // var equipInfoIds = equipInfos.Select(t => t.Id).ToList(); - - // if (endTime > DateTime.Now) - // { - // endTime = DateTime.Now; - // } - - // var times = await _airDBContext.Times.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime < endTime).AsNoTracking().ToListAsync(); - // var timeIds = times.Select(t => t.Id).ToList(); - - // var ammeterType = (short)ReportEnergyConsumeTypeEnum.ElectricPower; - // //var ammeterDwQuery = _airDBContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - // //{ - // // EquipId = t.Parm002 ?? 0, - // // Consume = t.AmParm003 ?? 0, - // // Unit = "kWh", - // // EnergyConsumeType = ammeterType, - // // TimeId = t.Parm001 - // //}); - // var ammeterDwQuery = from dw in _airDBContext.TbAmmeterDw - // join time in _airDBContext.Times on dw.Parm001 equals time.Id - // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime - // select new DataSourceEnergyConsumDBItemModel - // { - // EquipId = dw.Parm002 ?? 0, - // Consume = dw.AmParm003 ?? 0, - // Unit = "kWh", - // EnergyConsumeType = ammeterType, - // TimeId = time.Id, - // Year = time.Year.ToString(), - // YearMonth = time.Year + "-" + time.Month, - // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, - // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour - // }; - // var gasType = (short)ReportEnergyConsumeTypeEnum.Gas; - // //var gasDwQuery = _airDBContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - // //{ - // // EquipId = t.Parm002 ?? 0, - // // Consume = t.GmParm002 ?? 0, - // // Unit = "m³", - // // EnergyConsumeType = gasType, - // // TimeId = t.Parm001 - // //}); - // var gasDwQuery = from dw in _airDBContext.TbGasMeterDw - // join time in _airDBContext.Times on dw.Parm001 equals time.Id - // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime - // select new DataSourceEnergyConsumDBItemModel - // { - // EquipId = dw.Parm002 ?? 0, - // Consume = dw.GmParm002 ?? 0, - // Unit = "m³", - // EnergyConsumeType = gasType, - // TimeId = time.Id, - // Year = time.Year.ToString(), - // YearMonth = time.Year + "-" + time.Month, - // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, - // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour - // }; - - // var headType = (short)ReportEnergyConsumeTypeEnum.Heat; - // //var heatDwQuery = _airDBContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - // //{ - // // EquipId = t.Parm002 ?? 0, - // // Consume = t.HmParm001 ?? 0, - // // Unit = "GJ", - // // EnergyConsumeType = headType, - // // TimeId = t.Parm001 - // //}); - // var heatDwQuery = from dw in _airDBContext.TbHeatMeterDw - // join time in _airDBContext.Times on dw.Parm001 equals time.Id - // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime - // select new DataSourceEnergyConsumDBItemModel - // { - // EquipId = dw.Parm002 ?? 0, - // Consume = dw.HmParm001 ?? 0, - // Unit = "GJ", - // EnergyConsumeType = headType, - // TimeId = time.Id, - // Year = time.Year.ToString(), - // YearMonth = time.Year + "-" + time.Month, - // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, - // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour - // }; - - // var waterType = (short)ReportEnergyConsumeTypeEnum.Water; - // //var waterDwQuery = _airDBContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002) && timeIds.Contains(t.Parm001)).AsNoTracking().Select(t => new DataSourceEnergyConsumDBItemModel - // //{ - // // EquipId = t.Parm002 ?? 0, - // // Consume = t.WmParm002 ?? 0, - // // Unit = "t", - // // EnergyConsumeType = waterType, - // // TimeId = t.Parm001 - // //}); - // var waterDwQuery = from dw in _airDBContext.TbWaterMeterDw - // join time in _airDBContext.Times on dw.Parm001 equals time.Id - // where dw.Parm002 != null && equipIds.Contains((long)dw.Parm002) && time.Fulldatetime >= startTime && time.Fulldatetime < endTime - // select new DataSourceEnergyConsumDBItemModel - // { - // EquipId = dw.Parm002 ?? 0, - // Consume = dw.WmParm002 ?? 0, - // Unit = "t", - // EnergyConsumeType = waterType, - // TimeId = time.Id, - // Year = time.Year.ToString(), - // YearMonth = time.Year + "-" + time.Month, - // YearMonthDay = time.Year + "-" + time.Month + "-" + time.Day, - // YearMonthDayHour = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour - // }; - - // //var query = ammeterDwQuery.Union(gasDwQuery).Union(heatDwQuery).Union(waterDwQuery); - // //var list = await query.ToListAsync(); - - - // var ammeterDws = await ammeterDwQuery.ToListAsync(); - // var gasDws = await gasDwQuery.ToListAsync(); - // var heatDws = await heatDwQuery.ToListAsync(); - // var waterDws = await waterDwQuery.ToListAsync(); - - // //dwQuery = ammeterDwQuery.Union(gasDwQuery).Union(heatDwQuery).Union(waterDwQuery); - // //var dws = await dwQuery.ToListAsync(); - // var dws = new List { }; - // if (ammeterDws.Count() > 0) - // { - // dws.AddRange(ammeterDws); - // } - // if (gasDws.Count() > 0) - // { - // dws.AddRange(gasDws); - // } - // if (heatDws.Count() > 0) - // { - // dws.AddRange(heatDws); - // } - // if (waterDws.Count() > 0) - // { - // dws.AddRange(waterDws); - // } - // if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeYear)) - // { - // dws = dws.GroupBy(t => new { t.EquipId, t.Year }).Select(t => new DataSourceEnergyConsumDBItemModel - // { - // EquipId = t.Key.EquipId, - // Consume = t.Sum(s => s.Consume), - // Unit = t.First().Unit, - // EnergyConsumeType = t.First().EnergyConsumeType, - // TimeId = t.First().TimeId, - // Year = t.Key.Year, - // YearMonth = t.First().YearMonth, - // YearMonthDay = t.First().YearMonthDay, - // YearMonthDayHour = t.First().YearMonthDayHour - // }).ToList(); - // } - // else if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeMonth)) - // { - // dws = dws.GroupBy(t => new { t.EquipId, t.YearMonth }).Select(t => new DataSourceEnergyConsumDBItemModel - // { - // EquipId = t.Key.EquipId, - // Consume = t.Sum(s => s.Consume), - // Unit = t.First().Unit, - // EnergyConsumeType = t.First().EnergyConsumeType, - // TimeId = t.First().TimeId, - // Year = t.First().Year, - // YearMonth = t.Key.YearMonth, - // YearMonthDay = t.First().YearMonthDay, - // YearMonthDayHour = t.First().YearMonthDayHour - // }).ToList(); - // } - // else if (input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeDay)) - // { - // dws = dws.GroupBy(t => new { t.EquipId, t.YearMonthDay }).Select(t => new DataSourceEnergyConsumDBItemModel - // { - // EquipId = t.Key.EquipId, - // Consume = t.Sum(s => s.Consume), - // Unit = t.First().Unit, - // EnergyConsumeType = t.First().EnergyConsumeType, - // TimeId = t.First().TimeId, - // Year = t.First().Year, - // YearMonth = t.First().YearMonth, - // YearMonthDay = t.Key.YearMonthDay, - // YearMonthDayHour = t.First().YearMonthDayHour - // }).ToList(); - // } - // else if (!input.Dimensions.Any(t => t == IOTLabelDimensionEnum.TimeHour)) - // { - // dws = dws.GroupBy(t => t.EquipId).Select(t => new DataSourceEnergyConsumDBItemModel - // { - // EquipId = t.Key, - // Consume = t.Sum(s => s.Consume), - // Unit = t.First().Unit, - // EnergyConsumeType = t.First().EnergyConsumeType, - // TimeId = t.First().TimeId, - // Year = t.First().Year, - // YearMonth = t.First().YearMonth, - // YearMonthDay = t.First().YearMonthDay, - // YearMonthDayHour = t.First().YearMonthDayHour - // }).ToList(); - // } - - // var constIds = equipInfos.Select(i => i.Constid ?? 0).ToList(); - // var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - // foreach (var dw in dws) - // { - // var equipInfo = equipInfos.FirstOrDefault(t => t.Id == dw.EquipId); - // if (equipInfo != null) - // { - // dw.EquipName = equipInfo.Eqname; - // } - // var constructionInfo = constructionInfos.FirstOrDefault(t => t.Id == equipInfo.Constid); - // if (constructionInfo != null) - // { - // dw.ConstId = constructionInfo.Id; - // dw.ConstName = constructionInfo.Constinfo; - // } - // //var time = times.FirstOrDefault(t => t.Id == dw.TimeId); - // //if (time != null) - // //{ - // // dw.Year = time.Fulldatetime.GetValueOrDefault().ToString("yyyy"); - // // dw.YearMonth = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM"); - // // dw.YearMonthDay = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM-dd"); - // // dw.YearMonthDayHour = time.Fulldatetime.GetValueOrDefault().ToString("yyyy-MM-dd HH"); - // //} - // } - - // var resultItems = await GetDataSourceDataV02(input.Labels, startTime, endTime, input.Dimensions, times, dws, dicIotLabelEquipIds, iotLabelTypes, equipInfos, constructionInfos); - // result.Data = new - // { - // Labels = iotLabelTypes.Select(t => new { t.Name, t.Id }).ToList(), - // Data = resultItems - // }; - // //if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Equip) - // //{ - // // result.Data = GetDataSourceDataByEquip(equipInfos, dws); - // //} - // //else if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeYear - // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeMonth - // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeDay - // // || input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.TimeHour) - // //{ - // // result.Data = GetDataSourceDataByTime(startTime, endTime, input.Dimensions.FirstOrDefault(), times, dws, dicIotLabelEquipIds, iotLabelTypes); - // //} - // //else if (input.Dimensions.FirstOrDefault() == IOTLabelDimensionEnum.Consturct) - // //{ - // // var constIds = queryEquipInfos.Select(t => t.Constid ?? 0).ToList(); - // // var constructionInfos = await _context.ConstructionInfo.Where(t => constIds.Contains(t.Id)).AsNoTracking().ToListAsync(); - // // result.Data = GetDataSourceDataByConstruct(constructionInfos, equipInfos, dws, input.Dimensions, times, dicIotLabelEquipIds, iotLabelTypes); - // //} - // } - // catch (Exception ex) - // { - // _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - // } - // return result; - //} - } - #region GroupBy - static class LinqExt - { - public class DGroupBy : IGrouping - { - public List _innerlist = new List(); - - private object[] _key; - - public DGroupBy(object[] key) { _key = key; } - - public object[] Key - { - get { return _key; } - } - - public void Add(T value) - { - _innerlist.Add(value); - } - - public IEnumerator GetEnumerator() - { - return this._innerlist.GetEnumerator(); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return this._innerlist.GetEnumerator(); - } - } - - public static IEnumerable> DynamicGroupBy(this IEnumerable data, string[] keys) - { - List> list = new List>(); - foreach (var item in data.Select(x => new { - k = keys.Select(y => x.GetType().GetProperty(y).GetValue(x, null)).ToArray(), - v = x - })) - { - DGroupBy existing = list.SingleOrDefault(x => x.Key.Zip(item.k, (a, b) => a.Equals(b)).All(y => y)); - if (existing == null) - { - existing = new DGroupBy(item.k); - list.Add(existing); - } - existing.Add(item.v); - } - return list; - } - } - - #endregion -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs deleted file mode 100644 index 89167fc..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/DataSourceV03Service.cs +++ /dev/null @@ -1,787 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using MySqlConnector; -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.Report -{ - public class DataSourceV03Service : IDataSourceV03Service - { - private readonly ILogger _logger; - private readonly WeiCloudDBUserCenterContext _userCenterContext; - private readonly WeiCloudDBContext _dbContext; - public DataSourceV03Service(ILogger logger, WeiCloudDBUserCenterContext userCenterContext , WeiCloudDBContext dbContext) - { - _logger = logger; - _userCenterContext = userCenterContext; - _dbContext = dbContext; - } - /// - /// 获取参数历史数据 - /// - /// - /// - /// - /// - /// - public async Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds) - { - var items = new List { }; - try - { - // var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); - - // var contextOptions = new DbContextOptionsBuilder() - //.UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - // using var __contextDB = new WeiCloudDBContext(contextOptions); - // items = await __contextDB.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).OrderBy(t => t.CreateTime).ToListAsync(); - //直接注入 - items = await _dbContext.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).ToListAsync(); - // items = await _dbContext.DsPointHistory - //.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime) - //.GroupBy(t => new { t.Id, Hour = t.CreateTime.Hour, Date = t.CreateTime.Date }) - //.Select(g => g.OrderBy(t => t.CreateTime).FirstOrDefault()) - //.OrderBy(t => t.CreateTime) - //.ToListAsync(); - - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - /// - /// 获取历史数据(间隔) - /// - /// - /// - /// - /// - /// 1-5分钟、2-10分钟、3-30分钟、4-1小时 - /// - public async Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds, short intervalType) - { - var items = new List { }; - try - { - var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - if (intervalType == 1) - { - items = await __contextDB.DsPointHistory.Where(t => pointIds.Contains(t.Id) && t.CreateTime >= startTime && t.CreateTime < endTime).OrderBy(t => t.CreateTime).ToListAsync(); - } - else - { - var dateFormat = string.Empty; - var dateFormatValueSql = string.Empty; - if (intervalType == 2) - { - dateFormat = "i"; - dateFormatValueSql = "%10=0"; - } - else if (intervalType == 3) - { - dateFormat = "i"; - dateFormatValueSql = "%30=0"; - } - else if (intervalType == 4) - { - dateFormat = "i"; - dateFormatValueSql = "=0"; - } - string sql = $"SELECT * FROM `DS_Point_History` ph WHERE ph.`Id` IN ({pointIds.ListToStr()}) AND ph.`CreateTime`>='{startTime.ToString("yyyy-MM-dd HH:mm:ss")}' AND ph.`CreateTime`<'{endTime.ToString("yyyy-MM-dd HH:mm:ss")}' AND DATE_FORMAT(`CreateTime`,'%{dateFormat}'){dateFormatValueSql} ORDER BY ph.`CreateTime` ASC"; - using var conn = __contextDB.Database.GetDbConnection(); - if (conn.State == ConnectionState.Closed) - { - conn.Open(); - } - using var cmd = conn.CreateCommand(); - cmd.CommandText = sql; - using var reader = await cmd.ExecuteReaderAsync(); - DataTable dt = new DataTable(); - dt.Load(reader); - foreach (DataRow row in dt.Rows) - { - try - { - var item = new DsPointHistory - { - Id = long.Parse(row["Id"].ToString()), - Time = DateTime.Parse(row["Time"].ToString()), - //Value = double.Parse(row["Value"].ToString()), - CreateTime = DateTime.Parse(row["CreateTime"].ToString()) - }; - items.Add(item); - if (!string.IsNullOrEmpty(row["Value"].ToString())) - { - item.Value = double.Parse(row["Value"].ToString()); - } - } - catch (Exception ex) - { - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetHistorys", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - /// - /// 获取参数历史数据 - /// - /// - /// - /// - /// - public async Task> GetHistorys(long projectId, DateTime queryTime, List pointIds) - { - //var startTime = queryTime.AddMinutes(-30); - var startTime = queryTime.AddHours(-1); - var endTime = queryTime; - var items = new List { }; - try - { - if (pointIds == null || pointIds.Count() == 0) - { - return items; - } - var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - - //string sql = @"SELECT t1.* FROM `DS_Point_History` t1 - //INNER JOIN ( - //SELECT t2.`Id`,MAX(t2.`CreateTime`) AS CreateTime FROM `DS_Point_History` t2 WHERE t2.`Id` IN (@Ids) AND t2.`CreateTime`>@StartTime AND t2.`CreateTime`<=@EndTime GROUP BY t2.`Id` - //) AS t3 ON t1.`Id`=t3.Id AND t1.`CreateTime`=t3.CreateTime"; - string sql = string.Format(@"SELECT t1.* FROM `DS_Point_History` t1 -INNER JOIN ( -SELECT t2.`Id`,MAX(t2.`CreateTime`) AS CreateTime FROM `DS_Point_History` t2 WHERE t2.`Id` IN ({0}) -AND t2.`CreateTime`>@StartTime AND t2.`CreateTime`<=@EndTime GROUP BY t2.`Id` -) AS t3 ON t1.`Id`=t3.Id AND t1.`CreateTime`=t3.CreateTime", pointIds.Join(",")); - //items = await __contextDB.DsPointHistory.FromSqlRaw(sql).AsNoTracking().ToListAsync(); - - var queryParameters = new List { - //new MySqlParameter("@Ids", pointIds.Join(",")), - //new MySqlParameter("@Ids", pointIds.ToArray()), - new MySqlParameter("@StartTime", startTime), - new MySqlParameter("@EndTime", endTime) - }; - items = await __contextDB.DsPointHistory.FromSqlRaw(sql, queryParameters.ToArray()).AsNoTracking().ToListAsync(); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - - /// - /// 获取时间区间内的最大和最小值 - /// - /// - /// - /// - /// - /// - public async Task> GetIntervalMaxMinHistorys(ProjectInfo projectInfo, DateTime startTime, DateTime endTime, List pointIds) - { - var items = new List { }; - try - { - if (pointIds == null || pointIds.Count() == 0 || projectInfo == null || string.IsNullOrEmpty(projectInfo.Dbstr)) - { - return items; - } - //var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == projectId); - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - - string sql = string.Format(@"SELECT t2.`Id`,MAX(t2.`Value`) Mx,MIN(t2.`Value`) Mn FROM `DS_Point_History` t2 -WHERE t2.`Id` IN ({0}) -AND t2.`CreateTime`>=@StartTime AND t2.`CreateTime`<=@EndTime AND t2.`Value`>=0 GROUP BY t2.`Id`", pointIds.Join(",")); - - using var conn = __contextDB.Database.GetDbConnection(); - if (conn.State == ConnectionState.Closed) - { - conn.Open(); - } - using var cmd = conn.CreateCommand(); - cmd.CommandText = sql; - cmd.Parameters.Add(new MySqlParameter("@StartTime", startTime)); - cmd.Parameters.Add(new MySqlParameter("@EndTime", endTime)); - using var reader = await cmd.ExecuteReaderAsync(); - DataTable dt = new DataTable(); - dt.Load(reader); - items = DataTableHelper.ConvertToModel(dt); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return items; - } - - /// - /// 获取设备历史数据 - /// - /// - /// - public async Task>> GetEquipHistorys(GetEquipHistoryModel input) - { - var result = new ResultPageModel> { Data = new List> { } }; - try - { - if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) - { - return result; - } - var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - - var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new - { - t.Id, - t.Equid, - t.Standarparamid - }).AsNoTracking().ToListAsync(); - var standarParamIds = realDatas.Select(t => t.Standarparamid ?? 0).Distinct().ToList(); - var realDataIds = realDatas.Select(t => t.Id).ToList(); - - var standarParams = await _userCenterContext.StandarParam.Where(t => standarParamIds.Contains(t.Id)).AsNoTracking().Select(t => new - { - t.Id, - t.Descname - }).ToListAsync(); - - StringBuilder sbCol = new StringBuilder(); - for (var i = 0; i < standarParams.Count(); i++) - { - var standarParam = standarParams[i]; - sbCol.Append("SUM(IF(r.`standarparamid` = ").Append(standarParam.Id).Append(",ph.`Value`,0)) AS '").Append(standarParam.Descname).Append("',"); - } - string otherConditions = string.Empty; - if (input.Interval > 0) - { - switch (input.Interval) - { - case 1: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; - break; - case 2: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; - break; - case 3: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; - break; - case 4: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; - break; - } - } - string sql = string.Format(@"SELECT r.`equid` as Equid,e.`eqname` as EquName, ph.`CreateTime` -,{1} -FROM `DS_Point_History` ph -INNER JOIN `Tb_RealData` r ON ph.id=r.id -INNER JOIN `EquipmentInfo` e ON r.`equid`=e.id -WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} -GROUP BY r.`equid`,ph.`CreateTime`", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions); - - string sqlResult = string.Empty; - if (input.PageIndex > 0 && input.PageSize > 0) - { - sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.`CreateTime` desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); - } - else - { - sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.`CreateTime` desc", sql); - } - - string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); - - using var conn = __contextDB.Database.GetDbConnection(); - if (conn.State == ConnectionState.Closed) - { - conn.Open(); - } - using var cmd = conn.CreateCommand(); - cmd.CommandText = sqlResult; - cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); - cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); - using var reader = await cmd.ExecuteReaderAsync(); - DataTable dt = new DataTable(); - dt.Load(reader); - - foreach (DataRow row in dt.Rows) - { - var dic = new Dictionary { }; - var equipObj = row["Equid"]; - dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); - var equipNameObj = row["EquName"]; - dic.Add("EquName", equipNameObj == null ? "" : equipNameObj.ToString()); - var createTimeObj = row["CreateTime"]; - dic.Add("CreateTime", createTimeObj == null ? "" : Convert.ToDateTime(createTimeObj.ToString()).ToString("yyyy-MM-dd HH:mm:ss") ); - foreach (var standarParam in standarParams) - { - var colObj = row[standarParam.Descname]; - dic.Add(standarParam.Descname, colObj == null ? "" : colObj.ToString()); - } - result.Data.Add(dic); - } - #region 获取数据总个数 - cmd.CommandText = sqlCount; - var totalCount = cmd.ExecuteScalar(); - if (totalCount != null) - { - result.TotalCount = int.Parse(totalCount.ToString()); - } - #endregion - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEnergyConsum", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - /// - /// 获取设备历史数据 - /// - /// - /// - public async Task>> GetEquipHistorysV03(GetEquipHistoryModel input) - { - var result = new ResultPageModel> { Data = new List> { } }; - try - { - if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) - { - return result; - } - var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); - - - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - - var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new - { - t.Id, - t.Equid, - t.Descname - }).AsNoTracking().ToListAsync(); - realDatas = realDatas.OrderBy(d=>d.Descname).ToList(); - var realDataIds = realDatas.Select(t => t.Id).ToList(); - StringBuilder sbCol = new StringBuilder(); - for (var i = 0; i < realDatas.Count(); i++) - { - var realData = realDatas[i]; - sbCol.Append("SUM(IF(ph.id = ").Append(realData.Id).Append(",ph.`Value`,0)) AS '").Append(realData.Id).Append("',"); - } - string otherConditions = string.Empty; - string groupStr = "ph.`CreateTime` as dates "; - //if (input.Interval > 0) - //{ - // switch (input.Interval) - // { - // case 1: - // //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; - // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:50:00')"; - // break; - // case 2: - // otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; - // break; - // case 3: - // otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; - // break; - // case 4: - // //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; - // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; - // break; - // case 5: - // //groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; - // otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; - // break; - // } - //} - if (input.Interval < 5) - { - string sql = string.Format(@"SELECT r.`equid` as Equid,{3} -,{1} -FROM `DS_Point_History` ph -INNER JOIN `Tb_RealData` r ON ph.id=r.id -WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} -GROUP BY r.`equid`,dates", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions, groupStr); - - string sqlResult = string.Empty; - //if (input.PageIndex > 0 && input.PageSize > 0) - //{ - // sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); - //} - //else - //{ - // sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); - //} - sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); - //string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); - string sqlCount = string.Empty; - using var conn = __contextDB.Database.GetDbConnection(); - if (conn.State == ConnectionState.Closed) - { - conn.Open(); - } - using var cmd = conn.CreateCommand(); - cmd.CommandText = sqlResult; - cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); - cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); - using var reader = await cmd.ExecuteReaderAsync(); - DataTable dt = new DataTable(); - dt.Load(reader); - - foreach (DataRow row in dt.Rows) - { - var createTimeObj = row["dates"]; - if (createTimeObj == null) - { - continue; - } - if (DateTime.TryParse(createTimeObj.ToString(), out DateTime tm)) - { - if (input.Interval > 0) - { - switch (input.Interval) - { - case 1: - //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; - //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:50:00')"; - if (tm.Minute % 5 != 0) - { - continue; - } - break; - case 2: - //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; - if (tm.Minute % 10 != 0) - { - continue; - } - break; - case 3: - //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; - if (tm.Minute % 30 != 0) - { - continue; - } - break; - case 4: - //otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; - //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; - if (tm.Minute != 0) - { - continue; - } - break; - case 5: - //groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; - //otherConditions += " AND ph.CreateTime = DATE_FORMAT(ph.CreateTime, '%Y-%m-%d %H:00:00')"; - if (tm.Minute != 0) - { - continue; - } - break; - } - } - } - else - { - continue; - } - - var dic = new Dictionary { }; - var equipObj = row["Equid"]; - dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); - - - dic.Add("CreateTime", createTimeObj == null ? "" : createTimeObj.ToString()); - foreach (var realData in realDatas) - { - var colObj = row[realData.Id.ToString()]; - dic.Add(realData.Id.ToString(), colObj == null ? "" : colObj.ToString()); - } - result.Data.Add(dic); - } - #region 获取数据总个数 - sqlCount = result.Data.Count().ToString(); - if (input.PageIndex > 0 && input.PageSize > 0) - { - result.Data = result.Data.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList(); - } - cmd.CommandText = sqlCount; - var totalCount = cmd.ExecuteScalar(); - if (totalCount != null) - { - result.TotalCount = int.Parse(totalCount.ToString()); - } - #endregion - } - else if (input.Interval == 5) //按照天进行计算 - { - var dspointdatas = await __contextDB.DsPointHistory.Where(x => realDataIds.Contains(x.Id) && x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime).ToListAsync(); - var st = input.EndTime - input.StartTime; - result.TotalCount = input.EquipIds.Count * st.Days + 1; - - int c = 0; - int end = 0; - int start = (input.PageIndex - 1) * input.PageSize; - if (dspointdatas == null || dspointdatas.Count == 0) - { - end = 0; - } - else if(input.PageIndex > 0 && input.PageSize > 0) - { - end = input.PageIndex * input.PageSize - 1; - } - else - { - end = dspointdatas.Count - 1; - } - foreach (var equ in input.EquipIds) - { - - while (input.EndTime.Date >= input.StartTime.Date) - { - if (start <= c && c <= end) - { - var dic = new Dictionary { }; - - dic.TryAdd("Equid", equ.ToString()); - dic.TryAdd("CreateTime", input.EndTime.Date.ToStringYMD24HMS()); - foreach (var realData in realDatas) - { - var value = dspointdatas.Where(x => x.Id == realData.Id && x.CreateTime >= input.EndTime.Date && x.CreateTime < input.EndTime.Date.AddDays(1)).OrderByDescending(x => x.CreateTime).FirstOrDefault(); - if(value != null) - { - dic.TryAdd("CreateTime", value.CreateTime.ToStringYMD24HMS()); - } - dic.TryAdd(realData.Id.ToString(), value?.Value.ToString()); - } - - result.Data.Add(dic); - } - input.EndTime = input.EndTime.Date.AddDays(-1); - c++; - } - } - if (result.Data.Count == 0) - { - result.TotalCount = 0; - } - - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEquipHistorysV02", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - public async Task>> GetEquipHistorysV02(GetEquipHistoryModel input) - { - var result = new ResultPageModel> { Data = new List> { } }; - try - { - if (input.EquipIds == null || input.EquipIds.Count() == 0 || input.ProjectId <= 0) - { - return result; - } - var projectInfo = _userCenterContext.ProjectInfo.AsNoTracking().FirstOrDefault(t => t.Id == input.ProjectId); - - - - var contextOptions = new DbContextOptionsBuilder() - .UseMySql(projectInfo.Dbstr, new MySqlServerVersion(new Version(8, 0, 19))).Options; - using var __contextDB = new WeiCloudDBContext(contextOptions); - - var realDatas = await __contextDB.TbRealData.Where(t => t.Equid != null && input.EquipIds.Contains((long)t.Equid)).Select(t => new - { - t.Id, - t.Equid, - t.Descname - }).AsNoTracking().ToListAsync(); - realDatas = realDatas.OrderBy(d => d.Descname).ToList(); - var realDataIds = realDatas.Select(t => t.Id).ToList(); - StringBuilder sbCol = new StringBuilder(); - for (var i = 0; i < realDatas.Count(); i++) - { - var realData = realDatas[i]; - sbCol.Append("SUM(IF(ph.id = ").Append(realData.Id).Append(",ph.`Value`,0)) AS '").Append(realData.Id).Append("',"); - } - string otherConditions = string.Empty; - string groupStr = "ph.`CreateTime` as dates "; - if (input.Interval > 0) - { - switch (input.Interval) - { - case 1: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%5=0"; - break; - case 2: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%10=0"; - break; - case 3: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')%30=0"; - break; - case 4: - otherConditions += " AND DATE_FORMAT(`CreateTime`,'%i')=0"; - break; - case 5: - groupStr = " DATE_FORMAT(ph.`CreateTime`, '%Y-%m-%d') AS dates"; - break; - } - } - if (input.Interval < 5) - { - string sql = string.Format(@"SELECT r.`equid` as Equid,{3} -,{1} -FROM `DS_Point_History` ph -INNER JOIN `Tb_RealData` r ON ph.id=r.id -WHERE r.`equid` in ({0}) AND ph.`CreateTime`>=@StartTime AND ph.`CreateTime`<=@EndTime {2} -GROUP BY r.`equid`,dates", input.EquipIds.Join(","), sbCol.ToString().TrimEnd(","), otherConditions, groupStr); - - string sqlResult = string.Empty; - if (input.PageIndex > 0 && input.PageSize > 0) - { - sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc limit {1} offset {2}", sql, input.PageSize, (input.PageIndex - 1) * input.PageSize); - } - else - { - sqlResult = string.Format(@"select * from ({0}) tmp order by tmp.dates desc", sql); - } - - string sqlCount = string.Format(@"select count(1) as PageCount from ({0}) tmp", sql); - - using var conn = __contextDB.Database.GetDbConnection(); - if (conn.State == ConnectionState.Closed) - { - conn.Open(); - } - using var cmd = conn.CreateCommand(); - cmd.CommandText = sqlResult; - cmd.Parameters.Add(new MySqlParameter("@StartTime", input.StartTime)); - cmd.Parameters.Add(new MySqlParameter("@EndTime", input.EndTime)); - using var reader = await cmd.ExecuteReaderAsync(); - DataTable dt = new DataTable(); - dt.Load(reader); - - foreach (DataRow row in dt.Rows) - { - var dic = new Dictionary { }; - var equipObj = row["Equid"]; - dic.Add("Equid", equipObj == null ? "" : equipObj.ToString()); - var createTimeObj = row["dates"]; - dic.Add("CreateTime", createTimeObj == null ? "" : createTimeObj.ToString()); - foreach (var realData in realDatas) - { - var colObj = row[realData.Id.ToString()]; - dic.Add(realData.Id.ToString(), colObj == null ? "" : colObj.ToString()); - } - result.Data.Add(dic); - } - #region 获取数据总个数 - cmd.CommandText = sqlCount; - var totalCount = cmd.ExecuteScalar(); - if (totalCount != null) - { - result.TotalCount = int.Parse(totalCount.ToString()); - } - #endregion - } - else if (input.Interval == 5) //按照天进行计算 - { - var dspointdatas = await __contextDB.DsPointHistory.Where(x => realDataIds.Contains(x.Id) && x.CreateTime >= input.StartTime && x.CreateTime <= input.EndTime).ToListAsync(); - var st = input.EndTime - input.StartTime; - result.TotalCount = input.EquipIds.Count * st.Days + 1; - - int c = 0; - int end = 0; - int start = (input.PageIndex - 1) * input.PageSize; - if (dspointdatas == null || dspointdatas.Count == 0) - { - end = 0; - } - else if (input.PageIndex > 0 && input.PageSize > 0) - { - end = input.PageIndex * input.PageSize - 1; - } - else - { - end = dspointdatas.Count - 1; - } - foreach (var equ in input.EquipIds) - { - - while (input.EndTime.Date >= input.StartTime.Date) - { - if (start <= c && c <= end) - { - var dic = new Dictionary { }; - - dic.TryAdd("Equid", equ.ToString()); - dic.TryAdd("CreateTime", input.EndTime.Date.ToStringYMD24HMS()); - foreach (var realData in realDatas) - { - var value = dspointdatas.Where(x => x.Id == realData.Id && x.CreateTime >= input.EndTime.Date && x.CreateTime < input.EndTime.Date.AddDays(1)).OrderByDescending(x => x.CreateTime).FirstOrDefault(); - if (value != null) - { - dic.TryAdd("CreateTime", value.CreateTime.ToStringYMD24HMS()); - } - dic.TryAdd(realData.Id.ToString(), value?.Value.ToString()); - } - - result.Data.Add(dic); - } - input.EndTime = input.EndTime.Date.AddDays(-1); - c++; - } - } - if (result.Data.Count == 0) - { - result.TotalCount = 0; - } - - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper("GetEquipHistorysV02", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs deleted file mode 100644 index 3f5243b..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/EnergyConsumService.cs +++ /dev/null @@ -1,380 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Services.Report -{ - public class EnergyConsumService: IEnergyConsumService - { - private readonly WeiCloudDBContext _context; - private readonly WeiCloudAirDBContext _airContext; - private readonly ILogger _logger; - public EnergyConsumService(WeiCloudDBContext context, WeiCloudAirDBContext airContext, ILogger logger) - { - _context = context; - _airContext = airContext; - _logger = logger; - } - public double GetEnergyConsumSum(List equipIds, DateTime startTime, DateTime endTime, int eqType) - { - double sum = 0; - - if (eqType == 1 || eqType == 5) - { - var _ammeterDwQuery = _airContext.TbAmmeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - #region 电 - var ammeterDwQuery = from ammeterDw in _ammeterDwQuery - join tm in _airContext.Times on ammeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = ammeterDw.AmParm003 ?? 0 - }; - - ammeterDwQuery = ammeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - - #endregion - sum += ammeterDwQuery.Sum(t => t.Consum); - } - else if (eqType == 2) - { - var _gasMeterDwQuery = _airContext.TbGasMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - #region 气 - var gasMeterDwQuery = from gasMeterDw in _gasMeterDwQuery - join tm in _airContext.Times on gasMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = gasMeterDw.GmParm002 ?? 0 - }; - gasMeterDwQuery = gasMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - #endregion - sum += gasMeterDwQuery.Sum(t => t.Consum); - } - else if (eqType == 3) - { - var _waterMeterDw = _airContext.TbWaterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - #region 水 - var waterMeterDwQuery = from waterMeterDw in _waterMeterDw - join tm in _airContext.Times on waterMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = waterMeterDw.WmParm002 ?? 0 - }; - waterMeterDwQuery = waterMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - - #endregion - sum += waterMeterDwQuery.Sum(t => t.Consum); - } - else if (eqType == 4) - { - var _heatMeterDw = _airContext.TbHeatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - #region 热 - var heatMeterDwQuery = from heatMeterDw in _heatMeterDw - join tm in _airContext.Times on heatMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = heatMeterDw.HmParm001 ?? 0 - }; - heatMeterDwQuery = heatMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - #endregion - sum += heatMeterDwQuery.Sum(t => t.Consum); - } - return sum; - } - - /// - /// 计算能耗 - /// - /// - /// - /// - /// - /// 间隔单位1-分,2-时,3-日,4-月,5-年 - /// - public async Task> GetRunEnergyConsum(List equipIds, DateTime startTime, DateTime endTime, double interval, int intervalUnit) - { - var startYear = startTime.Year; - var startMonth = startTime.Month; - var startDay = startTime.Day; - var startHour = startTime.Hour; - - var endYear = endTime.Year; - var endMonth = endTime.Month; - var endDay = endTime.Day; - var endHour = endTime.Hour; - - #region 电 - var _ammeterDwQuery = _airContext.TbAmmeterDw.AsQueryable(); - var _waterMeterDw = _airContext.TbWaterMeterDw.AsQueryable(); - var _gasMeterDwQuery = _airContext.TbGasMeterDw.AsQueryable(); - var _heatMeterDw = _airContext.TbHeatMeterDw.AsQueryable(); - if (equipIds != null && equipIds.Count() > 0) - { - _ammeterDwQuery = _ammeterDwQuery.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - _waterMeterDw = _waterMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - _gasMeterDwQuery = _gasMeterDwQuery.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - _heatMeterDw = _heatMeterDw.Where(t => t.Parm002 != null && equipIds.Contains((long)t.Parm002)); - } - var ammeterDwQuery = from ammeterDw in _ammeterDwQuery - join tm in _airContext.Times on ammeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = ammeterDw.AmParm003 - }; - - ammeterDwQuery = ammeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - var ammeterDwItems = ammeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new - { - Year = t.Key.Year, - Month = t.Key.Month, - Day = t.Key.Day, - Hour = t.Key.Hour, - Fulldatetime = t.Key.Fulldatetime, - Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) - }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); - #endregion - #region 水 - var waterMeterDwQuery = from waterMeterDw in _waterMeterDw - join tm in _airContext.Times on waterMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = waterMeterDw.WmParm002 - }; - waterMeterDwQuery = waterMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - - var waterMeterDwItems = waterMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new - { - Year = t.Key.Year, - Month = t.Key.Month, - Day = t.Key.Day, - Hour = t.Key.Hour, - Fulldatetime = t.Key.Fulldatetime, - Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) - }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); - #endregion - #region 气 - var gasMeterDwQuery = from gasMeterDw in _gasMeterDwQuery - join tm in _airContext.Times on gasMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = gasMeterDw.GmParm002 - }; - gasMeterDwQuery = gasMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - var gasMeterDwItems = gasMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new - { - Year = t.Key.Year, - Month = t.Key.Month, - Day = t.Key.Day, - Hour = t.Key.Hour, - Fulldatetime = t.Key.Fulldatetime, - Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) - }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); - #endregion - #region 热 - var heatMeterDwQuery = from heatMeterDw in _heatMeterDw - join tm in _airContext.Times on heatMeterDw.Parm001 equals tm.Id - select new - { - Year = tm.Year, - Month = tm.Month, - Day = tm.Day, - Hour = tm.Hour, - Fulldatetime = tm.Fulldatetime, - Consum = heatMeterDw.HmParm001 - }; - heatMeterDwQuery = heatMeterDwQuery.Where(t => t.Fulldatetime >= startTime && t.Fulldatetime <= endTime); - var heatMeterDwItems = heatMeterDwQuery.GroupBy(t => new { t.Year, t.Month, t.Day, t.Hour, t.Fulldatetime }).Select(t => new - { - Year = t.Key.Year, - Month = t.Key.Month, - Day = t.Key.Day, - Hour = t.Key.Hour, - Fulldatetime = t.Key.Fulldatetime, - Consum = t.Sum(s => Math.Abs(s.Consum ?? 0)) - }).ToList().OrderBy(t => t.Year).ThenBy(t => t.Month).ThenBy(t => t.Day).ThenBy(t => t.Hour).ToList(); - #endregion - var time = startTime; - - var result = new List(); - int maxCount = 100; - int count = 0; - do - { - if (time > DateTime.Now) - { - break; - } - if (count > maxCount) - { - break; - } - count++; - - var timeStartYear = time.Year; - var timeStartMonth = time.Month; - var timeStartDay = time.Day; - var timeStartHour = time.Hour; - #region 截止时间 - DateTime _endTime; - if (intervalUnit == 1) - { - _endTime = time.AddMinutes(interval); - } - else if (intervalUnit == 2) - { - _endTime = time.AddHours(interval); - } - else if (intervalUnit == 3) - { - _endTime = time.AddDays(interval); - } - else if (intervalUnit == 4) - { - _endTime = time.AddMonths((int)Math.Round(interval)); - } - else - { - _endTime = time.AddYears((int)Math.Round(interval)); - } - var timeEndYear = _endTime.Year; - var timeEndMonth = _endTime.Month; - var timeEndDay = _endTime.Day; - var timeEndHour = _endTime.Hour; - #endregion - double ammeterDw = 0; - double waterMeterDw = 0; - double gasMeterDw = 0; - double heatMeterDw = 0; - if (_endTime > endTime) - { - var _ammeterDwItems = ammeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); - var _waterMeterDwItems = waterMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); - var _gasMeterDwItems = gasMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); - var _heatMeterDwItems = heatMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < endTime); - - ammeterDw = _ammeterDwItems.Sum(t => t.Consum); - waterMeterDw = _waterMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Water; - gasMeterDw = _gasMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Gas; - heatMeterDw = _heatMeterDwItems.Sum(t => t.Consum); - } - else - { - var _ammeterDwItems = ammeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); - var _waterMeterDwItems = waterMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); - var _gasMeterDwItems = gasMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); - var _heatMeterDwItems = heatMeterDwItems.Where(t => t.Fulldatetime >= time && t.Fulldatetime < _endTime); - - ammeterDw = _ammeterDwItems.Sum(t => t.Consum); - waterMeterDw = _waterMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Water; - gasMeterDw = _gasMeterDwItems.Sum(t => t.Consum);// * EquivalentElectricEnum.Gas; - heatMeterDw = _heatMeterDwItems.Sum(t => t.Consum); - } - - - result.Add(new RunEnergyConsumItemModel - { - Year = timeStartYear, - Month = timeStartMonth, - Day = timeStartDay, - Hour = timeStartHour, - Consum = Math.Round(ammeterDw + waterMeterDw + gasMeterDw + heatMeterDw, 2) - }); - time = _endTime; - } while (time <= endTime); - return result; - } - - - /// - /// 获取设备分组 通过menuId - /// - /// - /// - /// - /// - public async Task> GetEquipmentGroupByMenuId(List groups, int eqType, long menuId) - { - var groupParentIds = await _context.EquipmentGroupMenuShip.Where(x => groups.Select(t => t.Id).Contains(x.Groupid) && x.Menuid == menuId).Select(x => x.Groupid).ToListAsync(); - List list = new List(); - foreach (var pid in groupParentIds) - { - var gr = groups.Where(x => x.Id == pid && x.Itemtype == eqType).FirstOrDefault(); - if (gr?.Id > 0) - { - var rest = GetSons(groups, pid); - list.AddRange(rest); - } - } - return list; - } - /// - /// 获取父节点的孩子 - /// - /// - /// - /// - private IEnumerable GetSons(IList list, long Fid) - { - var query = list.Where(p => p.Id == Fid).ToList(); - var list2 = query.Concat(GetSonList(list, Fid)); - return list2; - } - /// - /// 递归子孩子的子孩子 - /// - /// - /// - /// - private IEnumerable GetSonList(IList list, long Fid) - { - var query = list.Where(p => p.Parentid == Fid).ToList(); - return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.Id))); - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs deleted file mode 100644 index 22a4cb0..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.Report -{ - public interface IDataSourceCoreService - { - Task GetDataSource(long dataSourceId); - Task> GetDataSource_v1(JObject input); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs deleted file mode 100644 index 9d7ac97..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV02Service.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.Report -{ - public interface IDataSourceV02Service - { - //Task> GetDataSourceData(GetDataSourceDataModel input); - Task>> GetDataTables(); - Task> GetEnergyConsum(QueryDataSourceEnergyConsumModel input); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs deleted file mode 100644 index 2c5bcb1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IDataSourceV03Service.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Report; - -namespace WeiCloud.Core.Services.Report -{ - public interface IDataSourceV03Service - { - Task>> GetEquipHistorys(GetEquipHistoryModel input); - Task>> GetEquipHistorysV02(GetEquipHistoryModel input); - Task>> GetEquipHistorysV03(GetEquipHistoryModel input); - Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds); - Task> GetHistorys(long projectId, DateTime queryTime, List pointIds); - Task> GetHistorys(long projectId, DateTime startTime, DateTime endTime, List pointIds, short intervalType); - Task> GetIntervalMaxMinHistorys(ProjectInfo projectInfo, DateTime startTime, DateTime endTime, List pointIds); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs deleted file mode 100644 index 083c147..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Report/IEnergyConsumService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.LogicModels.InfoModels; - -namespace WeiCloud.Core.Services.Report -{ - public interface IEnergyConsumService - { - double GetEnergyConsumSum(List equipIds, DateTime startTime, DateTime endTime, int eqType); - Task> GetRunEnergyConsum(List equipIds, DateTime startTime, DateTime endTime, double interval, int intervalUnit); - Task> GetEquipmentGroupByMenuId(List groups, int eqType, long menuId); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs deleted file mode 100644 index f906481..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/StandarParamsCoreService.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class StandarParamsCoreService: IStandarParamsCoreService - { - private readonly WeiCloudDBContext _cloudContext; - private readonly WeiCloudAirDBContext _context; - private readonly ILogger _logger; - private readonly IDictionaryService _dictionaryService; - private readonly WeiCloudDBUserCenterContext _userCenterContext; - - public StandarParamsCoreService(IDictionaryService dictionaryService,WeiCloudAirDBContext context, WeiCloudDBContext cloudContext, ILogger logger, WeiCloudDBUserCenterContext userCenterContext) - { - _cloudContext = cloudContext; - _context = context; - _logger = logger; - _dictionaryService = dictionaryService; - _userCenterContext = userCenterContext; - } - /// - /// 根据id查询标准点表信息 - /// - /// 标准点表id - /// 标准点表信息 - public async Task GetStandarParam(int id) - { - return _userCenterContext.StandarParam.TagWith("SubDB").FirstOrDefault(t => t.Id == id); - } - public async Task> GetStandarParam() - { - StandarParam standar = new StandarParam(); - try - { - var result = _dictionaryService.GetValue(standar.GetType().Name); - var list = result.Values.ToList(); - return await Task.FromResult(list); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetStandarParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - throw; - } - - } - public async Task> GetStandarParamByAllKes(string[] keys) - { - List standar = new List(); - try - { - var result = _dictionaryService.GetValue(new StandarParam().GetType().Name, keys).Select(d => d.Value).ToList(); - if (result != null) - { - standar = result.Where(d => d != null && d.Id > 0).ToList(); - } - return await Task.FromResult(standar); - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetStandarParam", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - throw; - } - - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs deleted file mode 100644 index 87d8ba2..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/SteamHeatCalculateService.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public class SteamHeatCalculateService: ISteamHeatCalculateService - { - /*蒸汽热量=蒸汽流量(t/s)*1000 *比热(KJ/Kg .°C)*温差(°C)/潜热(KJ/Kg) - 做一个公共函数,传参数(蒸汽流量,蒸汽出温度,进水温度) - 汽化潜热的比焓值:2258. 2kJ/kg - */ - private readonly WeiCloudDBUserCenterContext _context; - public SteamHeatCalculateService(WeiCloudDBUserCenterContext context) - { - _context = context; - - } - public async Task CalculateSteamHeat(double steamFlow, double steamOutTemperature, double waterInTemperature) - { - double steamHeat = 0; - double temp = (int)Math.Round(steamOutTemperature / 10.0) * 10; - var spec =await _context.SpecificHeatCapacity.Where(d => d.Temperature == temp).FirstOrDefaultAsync(); - if (spec == null) - { - return steamHeat; - } - if ((steamOutTemperature - waterInTemperature) <= 0) - { - return steamHeat; - } - steamHeat = steamFlow*1000 * spec.SpecificHeat * (steamOutTemperature - waterInTemperature) / 2258.2; - steamHeat = Math.Round(steamHeat, 2); - return steamHeat; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs deleted file mode 100644 index 949af36..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/ITenantEMSService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Tenant; - -namespace WeiCloud.Core.Services.Tenement -{ - public interface ITenantEMSService - { - Task> SendHttpRequest(TenantSendMsgDto payload, string accessKey, string accessSecret, string url); - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs deleted file mode 100644 index 9677167..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/Tenement/TenantEMSService.cs +++ /dev/null @@ -1,73 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.Tenant; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services.Tenement -{ - public class TenantEMSService : ITenantEMSService - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly IConfiguration _configuration; - public TenantEMSService( - IHttpClientFactory httpClientFactory, - ILogger logger, - IConfiguration configuration) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _configuration = configuration; - } - /// - /// 发送短信 - /// - /// - /// - /// - /// - /// - public async Task> SendHttpRequest(TenantSendMsgDto payload, string accessKey, string accessSecret, string url) - { - //AccessKey:anxiao 秘钥:ZrhSAF#2025 - - using var client = _httpClientFactory.CreateClient(); - - var ts = DateTime.Now.ToString("yyyyMMddHHmm"); - var accessSign = MD5Helper.getMd5Hash($"{accessKey}{accessSecret}{ts}"); - - var jsonStr = JsonConvert.SerializeObject(payload); - var contentBytes = Encoding.UTF8.GetBytes(jsonStr); - var content = new ByteArrayContent(contentBytes); - content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - using var request = new HttpRequestMessage(HttpMethod.Post, url) - { - Content = content - }; - request.Headers.Add("AccessKey", accessKey); - request.Headers.Add("AccessSign", accessSign); - - using var response = await client.SendAsync(request); - - if (response.IsSuccessStatusCode) - { - var detail = await response.Content.ReadAsStringAsync(); - _logger.LogError("发送短信成功: {Status} | {Body}", response.StatusCode, detail); - return ApiResult.IsSuccess(true); - } - - var detail1 = await response.Content.ReadAsStringAsync(); - - _logger.LogError("发送短信失败: {Status} | {Body}", response.StatusCode, detail1); - return ApiResult.IsFail("发送短信失败"); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs deleted file mode 100644 index 6ed116c..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/UserGroupsGainCoreService.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Utils; - -namespace WeiCloud.ProConfiguration.Service -{ - public class UserGroupsGainCoreService : IUserGroupsGainCoreService - { - private readonly IListService _listService; - private readonly IDictionaryService _dictionaryService; - public UserGroupsGainCoreService(IListService listService, IDictionaryService dictionaryService) - { - _listService = listService; - _dictionaryService = dictionaryService; - } - - public async Task deleteUserGroupsInfo(string[] keys) - { - - try - { - UserGroups userGroups = new UserGroups(); - _dictionaryService.DeleteValue(userGroups.GetType().Name, keys); - return await Task.FromResult(1); - } - catch (Exception ex) - { - - throw; - } - } - - public async Task PushUserGroupsToRedis(UserGroups userGroups) - { - try - { - _dictionaryService.PushValue(userGroups.GetType().Name, userGroups.Id.ToString(), userGroups); - - return await Task.FromResult(1); - } - catch (Exception) - { - - throw; - } - } - public async Task GetUserGroupsModelById(long id) - { - try - { - UserGroups group = new UserGroups(); - group = _dictionaryService.GetValue(group.GetType().Name)[id.ToString()]; - return await Task.FromResult(group); - } - catch (Exception) - { - - throw; - } - } - public async Task> GetAllUserGroupsRedis() - { - UserGroups group = new UserGroups(); - var result = _dictionaryService.GetValue(group.GetType().Name); - var list = result.Values.ToList(); - return await Task.FromResult(list); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs deleted file mode 100644 index b9d8574..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPermissionsCoreService.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.UserCenter; - -namespace WeiCloud.Core.Services -{ - public class UserProjectPermissionsCoreService : IUserProjectPermissionsCoreService - { - private readonly IDictionaryService _dictionaryService; - public UserProjectPermissionsCoreService(IDictionaryService dictionaryService) - { - _dictionaryService = dictionaryService; - } - /// - /// 获取当前用户权限 - /// - /// - /// - /// - public async Task GetCurrentUserPermission(string userRoleId, string userGroupId) - { - var permission = new CurrentUserPermissionModel { }; - - var userRole = _dictionaryService.GetValue(typeof(UserRoles).Name, userRoleId.ToString()); - if (userRole.Isusing == 0) - { - return permission; - } - permission.RoleId = userRole.Id; - permission.RoleName = userRole.Rolename; - permission.RoleCode = userRole.Rolecode; - var userGroup = _dictionaryService.GetValue(typeof(UserGroups).Name, userGroupId); - if (userGroup != null) - { - permission.OwerId = userGroup.Ownerid; - } - - return await Task.FromResult(permission); - } - /// - /// 获取当前用户权限 - /// - /// - /// - public async Task GetCurrentUserPermission(string userId) - { - var permission = new CurrentUserPermissionModel { }; - var user = _dictionaryService.GetValue(typeof(Users).Name, userId.ToString()); - if (user == null || user.Userrole == null || user.Userrole == 0) - { - return permission; - } - - var userRole = _dictionaryService.GetValue(typeof(UserRoles).Name, user.Userrole.ToString()); - if (userRole.Isusing == 0) - { - return permission; - } - permission.RoleId = userRole.Id; - permission.RoleName = userRole.Rolename; - permission.RoleCode = userRole.Rolecode; - if (user.Usergroup != 0) - { - var userGroup = _dictionaryService.GetValue(typeof(UserGroups).Name, user.Usergroup.ToString()); - if (userGroup != null) - { - permission.OwerId = userGroup.Ownerid; - } - } - - return await Task.FromResult(permission); - } - public async Task> GetAllGroupPressRedis() - { - UserProjectPermissions group = new UserProjectPermissions(); - var result = _dictionaryService.GetValue(group.GetType().Name); - var list = result.Values.ToList(); - return await Task.FromResult(list); - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs deleted file mode 100644 index 5021969..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/UserProjectPressRedisTreeCoreService.cs +++ /dev/null @@ -1,639 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Core.Common; -using WeiCloud.Core.EnumTools; -using WeiCloud.Entity.LogicModels; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Utils; -using WeiCloud.Entity.Context.UserCenter; -using Microsoft.EntityFrameworkCore; -using System.Diagnostics; - -namespace WeiCloud.Core.Services -{ - public class UserProjectPressRedisTreeCoreService: WeiCloud.Core.BaseCore.Grain, IUserProjectPressRedisTreeCoreService - { - private readonly WeiCloudDBUserCenterContext _userContext; - private readonly WeiCloudDBContext _context; - private readonly IDictionaryService _dictionaryService; - private List constIdList = new List(); - private List constPressIdList = new List(); - private readonly ILogger _logger; - - public UserProjectPressRedisTreeCoreService(WeiCloudDBContext context,WeiCloudDBUserCenterContext userContext, IDictionaryService dictionaryService, ILogger logger) - { - _context = context; - _userContext = userContext; - _dictionaryService = dictionaryService; - _logger = logger; - } - /// - /// 获取redis中的菜单权限拼接串 - /// - /// 角色id - /// 权限拼接串 - private string GetUserPermRedisByUserId(string roleid) - { - string returnStr = string.Empty; - UserPermissions userPerm = new UserPermissions(); - var userPermissions = _dictionaryService.GetValue(userPerm.GetType().Name)[roleid]; - if (userPermissions != null) - { - returnStr = userPermissions.Permisscodes; - } - else - { - returnStr = string.Empty; - } - return returnStr; - } - private List GetPermissionsRedis() - { - List list = new List(); - Permissions press = new Permissions(); - var data = _dictionaryService.GetValue(press.GetType().Name); - list = data.Values.ToList(); - return list; - } - private Users GetUsersRedis(string userId) - { - Users users = new Users(); - users = _dictionaryService.GetValue(users.GetType().Name, userId.ToString()); - return users; - } - /// - /// 获取用户的菜单权限菜单id拼接串 - /// - /// 用户id - /// 用户的菜单权限菜单id拼接串 - public async Task GetUserRolePress() - { - //登录者角色code - string code = CurrentContext.GetContext().RoleCode; - long userId = CurrentContext.GetContext().UserId; - string userPressStr = string.Empty; - StringBuilder build = new StringBuilder(); - try - { - //超级管理员权限 - if (code == SysBaseCodeMeta.AdminCode) - { - var press = GetPermissionsRedis(); - if (press == null || press.Count == 0) - { - var mysqlPress = (from p in _userContext.Permissions select p).ToList(); - if (mysqlPress != null && mysqlPress.Count > 0) - { - press = mysqlPress; - } - } - if (press != null && press.Count > 0) - { - foreach (Permissions p in press) - { - build.Append(p.Id.ToString() + ","); - } - userPressStr = build.ToString(); - } - } - //不是超级管理员 - else - { - var users = GetUsersRedis(userId.ToString()); - if (users != null && users.Userrole > 0) - { - //获取登录者的菜单权限 - userPressStr = GetUserPermRedisByUserId(users.Userrole.ToString()); - } - //redis读取不到权限,则数据库读取 - if (string.IsNullOrEmpty(userPressStr)) - { - var userPress = (from u in _userContext.Users - join p in _userContext.UserPermissions - on u.Userrole equals p.Roleid - where u.Userrole > 0 && u.Id == userId - select p).FirstOrDefault(); - if (userPress != null && !string.IsNullOrEmpty(userPress.Permisscodes)) - { - userPressStr = userPress.Permisscodes; - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetUserRolePress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - //throw; - } - return await Task.FromResult(userPressStr); - } - public async Task GetUserRolePress(long? userId, string code) - { - //登录者角色code - //string code = CurrentContext.GetContext().RoleCode; - //long userId = CurrentContext.GetContext().UserId; - string userPressStr = string.Empty; - StringBuilder build = new StringBuilder(); - try - { - //超级管理员权限 - if (code == SysBaseCodeMeta.AdminCode) - { - var press = GetPermissionsRedis(); - if (press == null || press.Count == 0) - { - var mysqlPress = (from p in _userContext.Permissions select p).ToList(); - if (mysqlPress != null && mysqlPress.Count > 0) - { - press = mysqlPress; - } - } - if (press != null && press.Count > 0) - { - foreach (Permissions p in press) - { - build.Append(p.Id.ToString() + ","); - } - userPressStr = build.ToString(); - } - } - //不是超级管理员 - else - { - var users = GetUsersRedis(userId.ToString()); - if (users != null && users.Userrole > 0) - { - //获取登录者的菜单权限 - userPressStr = GetUserPermRedisByUserId(users.Userrole.ToString()); - } - //redis读取不到权限,则数据库读取 - if (string.IsNullOrEmpty(userPressStr)) - { - var userPress = (from u in _userContext.Users - join p in _userContext.UserPermissions - on u.Userrole equals p.Roleid - where u.Userrole > 0 && u.Id == userId - select p).FirstOrDefault(); - if (userPress != null && !string.IsNullOrEmpty(userPress.Permisscodes)) - { - userPressStr = userPress.Permisscodes; - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetUserRolePress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - //throw; - } - return await Task.FromResult(userPressStr); - } - /// - /// 根据数据权限信息组织登录者的数据权限 - /// - /// 用户组id - /// 项目id拼接串 - /// 建筑物id拼接串 - /// 组织好的数据权限 - private ProAndConstPression SetUserGroupProPress(long? userGroupId, string projestStr, string constStr) - { - ProAndConstPression pression = new ProAndConstPression(); - //int res = 0; - List projectIds = new List(); - List constIds = new List(); - try - { - if (!string.IsNullOrEmpty(projestStr) && !string.IsNullOrEmpty(constStr)) - { - string[] arrProject = projestStr.Split(','); - string[] arrConst = constStr.Split(','); - //项目 - foreach (string s in arrProject) - { - long id = 0; - long.TryParse(s, out id); - if (id > 0) - { - projectIds.Add(id); - } - } - //建筑物 - foreach (string s in arrConst) - { - long cid = 0; - long.TryParse(s, out cid); - if (cid > 0) - { - constIds.Add(cid); - } - } - } - if (projectIds != null && projectIds.Count > 0 && constIds != null && constIds.Count > 0) - { - constPressIdList = constPressIdList.Union(constIds).Distinct().ToList(); - var constAll = (from c in _context.ConstructionInfo - where c.Projectid != null && projectIds.Contains((long)c.Projectid) - select new ConstructionInfo - { - Id = c.Id, - Projectid = c.Projectid, - Constarea = c.Constarea, - Constcode = c.Constcode, - Constcount = c.Constcount, - Constinfo = c.Constinfo, - }).ToList(); - var projects = _userContext.ProjectInfo.Where(p => p.State == 1 && projectIds.Contains(p.Id)).AsNoTracking().ToList(); - var tree = (from p in projects - select new ProAndConstTree - { - Id = p.Id, - Code = p.Projectcode, - Label = p.Projectname, - Projectid = p.Id, - Type = 0, - Children = GetConstInfoByParentId(0, p.Id, constIds, constAll, false) - }).ToList(); - if (tree != null && tree.Count() > 0 && userGroupId > 0) - { - pression.UserGroupId = (long)userGroupId; - pression.ProjectIds = projectIds; - pression.ConstIds = constPressIdList; - pression.ProAndConstTree = tree; - //res = PushProtPermssionToRedis(pression); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + "SetUserGroupProPress", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - throw; - } - return pression; - } - private UserRoles GetUsersRoleRedis(string roleId) - { - UserRoles role = new UserRoles(); - role = _dictionaryService.GetValue(role.GetType().Name, roleId.ToString()); - return role; - } - private List GetAllConstructionInfoRedis() - { - ConstructionInfo construction = new ConstructionInfo(); - var result = _dictionaryService.GetValue(construction.GetType().Name); - var list = result.Values.ToList(); - - return list; - } - private List GetAllConstructionInfoRedis(string hashId) - { - ConstructionInfo construction = new ConstructionInfo(); - var result = _dictionaryService.GetValue(hashId); - var list = result.Values.ToList(); - return list; - } - private List GetAllProjectRedis() - { - ProjectInfo project = new ProjectInfo(); - var result = _dictionaryService.GetValue(project.GetType().Name); - var list = result.Values.ToList(); - - return list; - } - /// - /// 获取子建筑物递归方法 - /// - /// - /// - /// - /// - /// - /// - private List GetConstInfoByParentId(long parentId, long projectId, List constId, List constList, bool isNote) - { - List conSmpleList = new List(); - conSmpleList = (from c in constList - where c.Projectid == projectId && - c.Parentid == parentId - && (parentId == 0 ? constId.Contains(c.Id) : true) - orderby c.Constcode - select new ProAndConstTree - { - Id = c.Id, - Code = c.Constcode, - Label = c.Constinfo, - Projectid = projectId, - Type = 1, - Children = GetConstInfoByParentId(c.Id, projectId, constId, constList, false) - }).ToList(); - if (conSmpleList != null && conSmpleList.Count > 0) - { - var listid = (from c in conSmpleList select c.Id).ToList(); - if (listid != null && listid.Count > 0) - { - constPressIdList = constPressIdList.Union(listid).ToList(); - } - } - return conSmpleList; - } - /// - /// 根据项目id和父节点获取建筑物的集合(递归) - /// - /// 父id - /// 项目id - /// 建筑物id - /// 建筑物树 - private List GetConstInfoByParentId(long parentId, long projectId, List constList) - { - List conSmpleList = new List(); - if (constList == null || constList.Count() == 0) - { - return conSmpleList; - } - ////逻辑根建筑物去掉 - //if (parentId == 0) - //{ - // var constInfo = (from c in constList - // where (int)c.Projectid == projectId - // && c.Parentid == 0 && c.Isusing == 1 - // select c).FirstOrDefault(); - // if (constInfo != null && constInfo.Id > 0) - // { - // parentId = constInfo.Id; - // } - //} - conSmpleList = (from c in constList - where c.Projectid == projectId && - c.Parentid == parentId - orderby c.Constcode - select new ProAndConstTree - { - Id = c.Id, - Code = c.Constcode, - Label = c.Constinfo, - Projectid = projectId, - Type = 1, - Children = GetConstInfoByParentId(c.Id, projectId, constList) - }).ToList(); - if (conSmpleList != null && conSmpleList.Count > 0) - { - var idList = (from c in conSmpleList select c.Id).ToList(); - if (idList != null && idList.Count > 0) - { - //存储用户的建筑物id集合 - constIdList = constIdList.Union(idList).ToList(); - } - } - return conSmpleList; - } - /// - /// 获取登录者的数据权限树状结构 - /// - /// 用户id - /// 权限集合 - public async Task GetProIdAndConstPressTreeByUserId(long userId) - { - ProAndConstPression pression = new ProAndConstPression(); - List pressList = new List(); - List projectId = new List(); - List constId = new List(); - try - { - //读取redis中用户信息 - var user = GetUsersRedis(userId.ToString()); - //redis中的用户信息为空则读取mysql中的用户信息 - if (user == null) - { - var mysqlUser = (from u in _userContext.Users where u.Id == userId select u).FirstOrDefault(); - if (mysqlUser != null) - { - user = mysqlUser; - } - } - if (user != null && user.Userrole > 0) - { - //读redis中的角色信息 - var role = GetUsersRoleRedis(user.Userrole.ToString()); - //redis中的角色信息为空则读mysql - if (role == null) - { - var mysqlRole = (from r in _userContext.UserRoles where r.Id == user.Userrole select r).FirstOrDefault(); - if (mysqlRole != null) - { - role = mysqlRole; - } - } - //超级管理员要查询所有权限 - if (role != null && role.Rolecode == SysBaseCodeMeta.AdminCode)//超级管理员 - { - var projectList = (from p in _userContext.ProjectInfo where p.State == 1 select p).AsNoTracking().Select(t => new ProjectInfo - { - Id = t.Id, - Projectcode = t.Projectcode, - Projectname = t.Projectname, - Engabb = t.Engabb - }).ToList(); - var projectIds = projectList.Select(t => t.Id).ToList(); - //redis建筑物集合 - List constInfo = new List { }; - //var constInfo = GetAllConstructionInfoRedis(); - var typeNameConstructionInfo = typeof(ConstructionInfo).Name; - foreach (var project in projectList) - { - var _constInfo = GetAllConstructionInfoRedis($"{project.Engabb}_{typeNameConstructionInfo}"); - if (_constInfo != null && _constInfo.Count() > 0) - { - constInfo.AddRange(_constInfo); - } - } - //List constInfo = null; - //redis中没有建筑物信息则读取 - if (constInfo == null || constInfo.Count == 0) - { - var mysqlConstInfo = (from c in _context.ConstructionInfo - where c.Projectid != null && projectIds.Contains((long)c.Projectid) - select new ConstructionInfo - { - Id = c.Id, - Constinfo = c.Constinfo, - Parentid = c.Parentid, - Constcode = c.Constcode, - Projectid = c.Projectid, - Constarea = c.Constarea, - Constcount = c.Constcount, - Consttype = c.Consttype, - Latitude = c.Latitude, - Longitude = c.Longitude, - Isshow = c.Isshow, - Isusing = c.Isusing, - Unicode = c.Unicode, - }).ToList(); - if (mysqlConstInfo != null && mysqlConstInfo.Count > 0) - { - constInfo = mysqlConstInfo; - } - } - if (projectList != null && projectList.Count > 0) - { - pressList = (from p in projectList - //where p.State == 1 - select new ProAndConstTree - { - Id = p.Id, - Code = p.Projectcode, - Label = p.Projectname, - Projectid = p.Id, - Type = 0, - Children = GetConstInfoByParentId(0, p.Id, constInfo) - }).ToList(); - } - //获取用户的建筑物id集合 - if (pressList != null && pressList.Count > 0) - { - var idList = (from p in pressList select p.Id).ToList(); - if (idList != null && idList.Count > 0) - { - projectId = idList; - } - } - pression.UserGroupId = 0; - pression.ProjectIds = projectId; - pression.ConstIds = constIdList; - pression.ProAndConstTree = pressList; - } - //读取redis中设置的权限 - else - { - //redis中的用户组权限读取 - pression = _dictionaryService.GetValue(pression.GetType().Name, user.Usergroup.ToString()); - //redis中的数据为空则读mysql中的 - if (pression == null) - { - var mysqlPress = (from p in _userContext.UserProjectPermissions where p.Groupid == user.Usergroup select p).FirstOrDefault(); - if (mysqlPress != null && !string.IsNullOrEmpty(mysqlPress.Projectpermiss) && !string.IsNullOrEmpty(mysqlPress.Constpermiss)) - { - var mysqlPressData = SetUserGroupProPress(user.Usergroup, mysqlPress.Projectpermiss, mysqlPress.Constpermiss); - if (mysqlPressData != null) - { - pression = mysqlPressData; - } - } - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProIdAndConstPressTreeByUserId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - throw; - } - return await Task.FromResult(pression); - } - - public async Task GetProIdAndConstPressTreeByUserId(CurrentUser currentUser) - { - ProAndConstPression pression = new ProAndConstPression(); - List pressList = new List(); - List projectId = new List(); - List constId = new List(); - try - { - //超级管理员要查询所有权限 - if (currentUser.RoleCode == SysBaseCodeMeta.AdminCode)//超级管理员 - { - var projectList = (from p in _userContext.ProjectInfo where p.State == 1 select p).AsNoTracking().Select(t => new ProjectInfo - { - Id = t.Id, - Projectcode = t.Projectcode, - Projectname = t.Projectname - }).ToList(); - var projectIds = projectList.Select(t => t.Id).ToList(); - //redis建筑物集合 - var constInfo = GetAllConstructionInfoRedis(); - //redis中没有建筑物信息则读取 - if (constInfo == null || constInfo.Count == 0) - { - var mysqlConstInfo = (from c in _context.ConstructionInfo - where c.Projectid != null && projectIds.Contains((long)c.Projectid) - select new ConstructionInfo - { - Id = c.Id, - Constinfo = c.Constinfo, - Parentid = c.Parentid, - Constcode = c.Constcode, - Projectid = c.Projectid, - Constarea = c.Constarea, - Constcount = c.Constcount, - Consttype = c.Consttype, - Latitude = c.Latitude, - Longitude = c.Longitude, - Isshow = c.Isshow, - Isusing = c.Isusing, - Unicode = c.Unicode, - }).ToList(); - if (mysqlConstInfo != null && mysqlConstInfo.Count > 0) - { - constInfo = mysqlConstInfo; - } - } - - if (projectList != null && projectList.Count > 0) - { - pressList = (from p in projectList - //where p.State == 1 - select new ProAndConstTree - { - Id = p.Id, - Code = p.Projectcode, - Label = p.Projectname, - Projectid = p.Id, - Type = 0, - Children = GetConstInfoByParentId(0, p.Id, constInfo) - }).ToList(); - } - //获取用户的建筑物id集合 - if (pressList != null && pressList.Count > 0) - { - var idList = (from p in pressList select p.Id).ToList(); - if (idList != null && idList.Count > 0) - { - projectId = idList; - } - } - pression.UserGroupId = 0; - pression.ProjectIds = projectId; - pression.ConstIds = constIdList; - pression.ProAndConstTree = pressList; - } - //读取redis中设置的权限 - else - { - //redis中的用户组权限读取 - pression = _dictionaryService.GetValue(pression.GetType().Name, currentUser.UserGroupId.ToString()); - //redis中的数据为空则读mysql中的 - if (pression == null) - { - var mysqlPress = (from p in _userContext.UserProjectPermissions where p.Groupid == currentUser.UserGroupId select p).FirstOrDefault(); - if (mysqlPress != null && !string.IsNullOrEmpty(mysqlPress.Projectpermiss) && !string.IsNullOrEmpty(mysqlPress.Constpermiss)) - { - var mysqlPressData = SetUserGroupProPress(currentUser.UserGroupId, mysqlPress.Projectpermiss, mysqlPress.Constpermiss); - if (mysqlPressData != null) - { - pression = mysqlPressData; - } - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName + " GetProIdAndConstPressTreeByUserId", string.Format("抛出了异常信息: {0};", ex.Message)).GetNlogMessage()); - throw; - } - return await Task.FromResult(pression); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs deleted file mode 100644 index e592257..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersCoreService.cs +++ /dev/null @@ -1,247 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Entity.LogicModels.ConfigModels; -using WeiCloud.Entity.LogicModels.Users; -using WeiCloud.Utils; -using Microsoft.Extensions.Options; -using DotNetCore.CAP; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.DependencyInjection; -using WeiCloud.Utils.Common; -using System.IdentityModel.Tokens.Jwt; -using NewLife.Model; - -namespace WeiCloud.Core.Services -{ - public class UsersCoreService : IUsersCoreService - { - private readonly WeiCloudDBUserCenterContext _context; - private readonly IDictionaryService _dictionaryService; - private readonly IOptions _identityClientConfig; - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - public UsersCoreService(WeiCloudDBUserCenterContext context, IDictionaryService dictionaryService, - IOptions identityClientConfig, IHttpClientFactory httpClientFactory, - ILogger logger) - { - _context = context; - _dictionaryService = dictionaryService; - _httpClientFactory = httpClientFactory; - _identityClientConfig = identityClientConfig; - _logger = logger; - } - public async Task GetUsersByName(string name) - { - var users = _dictionaryService.GetValue(); - var user = users.FirstOrDefault(t => t.Value.Username == name).Value; - return await Task.FromResult(user); - } - public async Task GetUsersById(long id) - { - var user = _dictionaryService.GetValue(typeof(Users).Name, id.ToString()); - //var user = users.FirstOrDefault(t => t.Value.Id == id).Value; - return await Task.FromResult(user); - } - public async Task GetUsersByIdV02(long id) - { - var users = _dictionaryService.GetValue(typeof(Users).Name, new string[] { id.ToString() }); - var user = users.FirstOrDefault().Value; - return await Task.FromResult(user); - } - - public async Task GetAdmin() - { - var users = _context.Users.Where(t => t.Usercode == "admin").Select(t => new Users - { - Id = t.Id - }).FirstOrDefault(); - return await Task.FromResult(users); - } - /// - /// 获取子部门所有人员 - /// - /// - /// - /// - public async Task> GetChildDeptUsers(List userGroups, long deptId) - { - var allChildDepts = GetAllChildDepts(userGroups, deptId); - var childDeptIds = allChildDepts.Select(t => t.Id).ToList(); - if (childDeptIds.Count() > 0) - { - return await _context.Users.Where(t => t.Usergroup != null && childDeptIds.Contains((long)t.Usergroup)).AsNoTracking().ToListAsync(); - } - return new List { }; - } - private List GetAllChildDepts(List userGroups, long parentDeptId) - { - var resultItems = new List { }; - var childUserGroups = userGroups.Where(t => t.Parentid == parentDeptId); - foreach (var childUserGroup in childUserGroups) - { - resultItems.Add(childUserGroup); - var _childUserGroups = GetAllChildDepts(userGroups, childUserGroup.Id); - if (_childUserGroups.Count() > 0) - { - resultItems.AddRange(_childUserGroups); - } - } - return resultItems; - } - /// - /// 更加项目Id获取所有账号Id - /// - /// - /// - public async Task> GetUserIdsByProjectId(long projectId) - { - var userIds = new List { }; - try - { - var _project = _context.ProjectInfo.Where(t => t.Id == projectId).Select(t => new - { - t.Ownerid, - t.Id - }).FirstOrDefault(); - if (_project != null) - { - var _ownerId = _project.Ownerid; - if (_ownerId > 0) - { - var _deptIds = await _context.UserGroups.Where(t => t.Ownerid == _ownerId && t.Isusing == 1).AsNoTracking().Select(t => t.Id).ToListAsync(); - if (_deptIds.Any()) - { - userIds = await _context.Users.Where(t => t.Usergroup != null && _deptIds.Contains((long)t.Usergroup) && t.Isusing == 1).AsNoTracking().Select(t => t.Id).ToListAsync(); - } - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, string.Format("抛出了异常信息: {0};", ex.Message.ToString())).GetNlogMessage().ToString()); - } - return userIds; - } - /// - /// 根据token获取用户信息 - /// - /// - /// - public async Task GetUserInfoByJwt(string token) - { - UserInfoJwtViewModel result = new UserInfoJwtViewModel { }; - try - { - var url = $"{_identityClientConfig.Value.Authority}/connect/userinfo"; - var client = _httpClientFactory.CreateClient(); - using var request = new HttpRequestMessage(HttpMethod.Get, url); - request.Headers.Add("Authorization", token); - using var httpResponse = await client.SendAsync(request); - if (httpResponse.StatusCode == HttpStatusCode.OK) - { - var httpresultStr = await httpResponse.Content.ReadAsStringAsync(); - if (!string.IsNullOrEmpty(httpresultStr)) - { - result = Newtonsoft.Json.JsonConvert.DeserializeObject(httpresultStr); - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - } - return result; - } - public UserInfoJwtViewModel GetUserInfoByJwtStr(string token) - { - UserInfoJwtViewModel result = new UserInfoJwtViewModel { }; - try - { - token = token.Substring("Bearer ".Length).Trim(); - var jwtHandler = new JwtSecurityTokenHandler(); - var jwtToken = jwtHandler.ReadJwtToken(token); - - foreach (var claim in jwtToken.Claims) - { - if (claim.Type == "sub") - { - result.Sub = claim.Value; - } - else if (claim.Type == "nickname") - { - result.NickName = claim.Value; - } - else if (claim.Type == "name") - { - result.Name = claim.Value; - } - } - } - catch (Exception ex) - { - _logger.LogError(new NlogMessageHelper(this.GetType().FullName, ex).GetNlogMessage().ToString()); - } - return result; - } - - public async Task PushUserToRedis(Users users) - { - try - { - _dictionaryService.PushValue(users.GetType().Name, users.Id.ToString(), users); - return await Task.FromResult(1); - } - catch (Exception) - { - throw; - } - } - /// - /// 修改用户密码 - /// - /// - /// - /// - public async Task ChangeUserPassword(long userId, string newPwd) - { - var result = RequestBackStatuEnum.success.Value; - try - { - //查看是否存在user - var userReal0 = (from u in _context.Users where u.Id == userId select u).FirstOrDefault(); - if (userReal0 != null) - { - DateTime createTime = (DateTime)userReal0.Createtime; - string passEndStr = createTime.ToString("HHmmss");//加密需要 - userReal0.Password = MD5Helper.getMd5Hash(newPwd + passEndStr);//新密码加盐 - userReal0.Updatetime = DateTime.Now; - _context.Entry(userReal0).State = EntityState.Modified; - //数据库中更新用户状态 - var res = await _context.SaveChangesAsync(); - //redis中更新用户状态 - - var res1 = await PushUserToRedis(userReal0); - } - else - { - result = RequestBackStatuEnum.notfound.Value; - } - } - catch (Exception ex) - { - result = RequestBackStatuEnum.badrequest.Value; - } - return result; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs deleted file mode 100644 index 2fb6322..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/UsersGainCoreService.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.DB; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Utils; - -namespace WeiCloud.Core.Services -{ - public class UsersGainCoreService: IUsersGainCoreService - { - private readonly IListService _listService; - private readonly IDictionaryService _dictionaryService; - public UsersGainCoreService(IListService listService, IDictionaryService dictionaryService) - { - _listService = listService; - _dictionaryService = dictionaryService; - } - public async Task PushUserToRedis(Users users) - { - try - { - _dictionaryService.PushValue(users.GetType().Name, users.Id.ToString(), users); - return await Task.FromResult(1); - } - catch (Exception) - { - throw; - } - } - public async Task GetUserModelById(long id) - { - Users users = new Users(); - users = _dictionaryService.GetValue(users.GetType().Name)[id.ToString()]; - return await Task.FromResult(users); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs b/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs deleted file mode 100644 index f39c153..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/Services/WorkflowService.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Policy; -using System.Text; -using System.Threading.Tasks; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using NewLife.Log; -using Newtonsoft.Json; -using WeiCloud.Entity.LogicModels.BaseModels; -using WeiCloud.Entity.LogicModels.DataModels; - -namespace WeiCloud.Core.Services -{ - public class WorkflowService : IWorkflowService - { - private readonly string _wfUrl; - private readonly IHttpClientFactory _clientFactory; - public IConfiguration Configuration { get; } - private readonly ILogger _logger; - public WorkflowService(IHttpClientFactory clientFactory, IConfiguration configuration, ILogger logger) - { - _clientFactory = clientFactory; - _logger = logger; - Configuration = configuration; - _wfUrl = Configuration.GetSection("WF:AutoCreateWFUrl").Value; - } - /// - /// 保存工作流 - /// - /// - /// - public async Task SaveWorkflowAsync(WorkOrderAggregateDto dto) - { - var client = _clientFactory.CreateClient(); - var reqMsg = JsonConvert.SerializeObject(dto); - using (HttpContent httpContent = new StringContent(reqMsg)) - { - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - using (var httpClient = new HttpClient()) - { - httpClient.Timeout = new TimeSpan(0, 0, 10); - HttpResponseMessage resp = await httpClient.PostAsync(_wfUrl, httpContent); - string res = await resp.Content.ReadAsStringAsync(); - _logger.LogWarning($"{reqMsg}保存工作流返回结果:{res}"); - ApiResult data = JsonConvert.DeserializeObject>(res); - if (data.Code == 200) - { - return data.Data; - } - else - { - return -1; - } - } - - } - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs b/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs deleted file mode 100644 index 71981a5..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/StartUp/ShardingCoreExtend.cs +++ /dev/null @@ -1,166 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using MySqlConnector; -using ShardingCore; -using ShardingCore.Bootstrappers; -using ShardingCore.TableExists; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using WeiCloud.Entity.Context.AirDB; -using WeiCloud.Entity.Context.ContextCore.Route; -using WeiCloud.Entity.Context.DB; - -namespace WeiCloud.Core.StartUp -{ - public class autostart : IHostedService - { - private readonly IConfiguration _config; - private readonly IServiceProvider _serviceProvider; - public autostart(IShardingBootstrapper shardingBootstrapper, IConfiguration config, IServiceProvider serviceProvider) - { - shardingBootstrapper.Start(); - _serviceProvider = serviceProvider; - _config = config; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - //var _weiCloudDBconn = _config.GetConnectionString("WeiCloudDBConn"); - //if (string.IsNullOrEmpty(_weiCloudDBconn)) - //{ - // var dbContext = _serviceProvider.GetRequiredService(); - // var n = dbContext.ConstructionInfo.Count(); - //} - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - } - public static class ShardingCoreExtend - { - public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder => - { - //builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name).AddConsole(); - }); - public static IServiceCollection AddShardingCore(this IServiceCollection services, IConfiguration configuration) - { - var _weiCloudDBUserCenterConn = configuration.GetConnectionString("WeiCloudUserCenterDBConn"); - var _weiCloudAirDBConn = configuration.GetConnectionString("WeiCloudAirDBConn"); - var _weiCloudDBconn = configuration.GetConnectionString("WeiCloudDBConn"); - services.AddHostedService(); - #region EFShardingCore - if (!string.IsNullOrEmpty(_weiCloudAirDBConn)) - { - services.AddShardingDbContext() - .AddEntityConfig(op => - { - op.CreateShardingTableOnStart = false; - op.EnsureCreatedWithOutShardingTable = false; - op.UseShardingQuery((conn, builder) => - { - builder.UseMySql(conn, new MySqlServerVersion(new Version(8, 0, 19)), opts => - { - opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); - }).UseLoggerFactory(efLogger); - }); - op.UseShardingTransaction((conn, builder) => - { - builder.UseMySql(conn, new MySqlServerVersion(new Version(8, 0, 19)), opts => - { - opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); - }).UseLoggerFactory(efLogger); - }); - }).AddConfig(op => - { - op.ConfigId = typeof(WeiCloudAirDBContext).Name; - op.AddDefaultDataSource(Guid.NewGuid().ToString("n"), _weiCloudAirDBConn); - }).EnsureConfig(); - } - - - services.AddShardingDbContext().AddEntityConfig(o => - { - o.CreateShardingTableOnStart = false; - o.EnsureCreatedWithOutShardingTable = false; - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - o.AddShardingDataSourceRoute(); - }).AddConfig(op => - { - op.ConfigId = typeof(WeiCloudDBContext).Name; - op.UseShardingQuery((conStr, builder) => - { - builder.UseMySql(conStr, new MySqlServerVersion(new Version(8, 0, 19)), opts => - { - opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); - }).UseLoggerFactory(efLogger);//.EnableSensitiveDataLogging(); - }); - op.UseShardingTransaction((connection, builder) => - { - builder.UseMySql(connection, new MySqlServerVersion(new Version(8, 0, 19)), opts => - { - opts.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: new int[] { 2 }); - }).UseLoggerFactory(efLogger);//.EnableSensitiveDataLogging(); - }); - - op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager()); - if (!string.IsNullOrWhiteSpace(_weiCloudDBconn)) - { - op.AddDefaultDataSource(Guid.NewGuid().ToString("n"), _weiCloudDBconn); - } - else - { - using (var conn = new MySqlConnection(_weiCloudDBUserCenterConn)) - { - conn.Open(); - string sql = "SELECT id,dbstr FROM `ProjectInfo` WHERE state=1 AND dbstr IS NOT NULL;"; -#if DEBUG - sql = "SELECT id,dbstr FROM `ProjectInfo` WHERE state=1 AND dbstr IS NOT NULL LIMIT 1;"; -#endif - MySqlCommand cmd = new MySqlCommand(sql, conn); - cmd.CommandText = sql; - MySqlDataReader rdr = cmd.ExecuteReader(); - int index = 0; - var dicSqlConn = new Dictionary(); - while (rdr.Read()) - { - if (index == 0) - { - op.AddDefaultDataSource(rdr[0].ToString(), rdr[1].ToString()); - } - else - { - dicSqlConn.Add(rdr[0].ToString(), rdr[1].ToString()); - } - index++; - } - rdr.Close(); - if (dicSqlConn.Count() > 0) - { - op.AddExtraDataSource(sp => - { - return dicSqlConn; - }); - } - } - } - }).EnsureConfig(); - #endregion - return services; - } - } -} \ No newline at end of file diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs deleted file mode 100644 index a0129da..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/MultipleTenancyExtension.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.Extensions.DependencyInjection; -using WeiCloud.Entity.Context.DB; -using Microsoft.EntityFrameworkCore; -using WeiCloud.Utils; -using NodaTime.TimeZones; -using WeiCloud.Utils.RedisUtil; - -namespace WeiCloud.Core.TenantDb -{ - public static class MultipleTenancyExtension - { - public static IServiceCollection AddConnectionByDatabase(this IServiceCollection services) - { - services.AddScoped((serviceProvider) => - { - var resolver = serviceProvider.GetRequiredService(); - var redis = serviceProvider.GetRequiredService(); - var prefix = resolver.GetRedisPrefix(); - return new QueueService(redis, prefix); - }); - services.AddScoped((serviceProvider) => - { - var resolver = serviceProvider.GetRequiredService(); - var redis = serviceProvider.GetRequiredService(); - var prefix = resolver.GetRedisPrefix(); - return new ListService(redis, prefix); - }); - services.AddScoped((serviceProvider) => - { - var resolver = serviceProvider.GetRequiredService(); - var redis = serviceProvider.GetRequiredService(); - var prefix = resolver.GetRedisPrefix(); - return new SetService(redis, prefix); - }); - services.AddScoped((serviceProvider) => - { - var resolver = serviceProvider.GetRequiredService(); - var redis = serviceProvider.GetRequiredService(); - var prefix = resolver.GetRedisPrefix(); - return new StringService(redis, prefix); - }); - services.AddScoped((serviceProvider) => - { - var resolver = serviceProvider.GetRequiredService(); - var redis = serviceProvider.GetRequiredService(); - var prefix = resolver.GetRedisPrefix(); - return new DictionaryService(redis, prefix); - }); - services.AddDbContext((serviceProvider, options) => - { - var resolver = serviceProvider.GetRequiredService(); - var connstr = resolver.GetConnection(); - if (!string.IsNullOrEmpty(connstr)) - { - options.UseMySql(connstr, new MySqlServerVersion(new Version(8, 0, 19))); - } - }); - - return services; - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs deleted file mode 100644 index e796fc1..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/SqlConnectionResolver.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Linq; -using Microsoft.Extensions.Configuration; -using WeiCloud.Entity.Context.UserCenter; -using WeiCloud.Utils; -using WeiCloud.Utils.RedisUtil; - -namespace WeiCloud.Core.TenantDb -{ - - public interface ISqlConnectionResolver - { - string GetConnection(); - string GetRedisPrefix(); - } - - public class HttpHeaderSqlConnectionResolver : ISqlConnectionResolver - { - private readonly TenantInfo tenantInfo; - private readonly IConfiguration configuration; - - private readonly IRedisHelper _redisHelper; - public HttpHeaderSqlConnectionResolver(TenantInfo tenantInfo, IConfiguration configuration, IRedisHelper redisHelper) - { - this.tenantInfo = tenantInfo; - this.configuration = configuration; - _redisHelper = redisHelper; - } - public string GetConnection() - { - var connectionString = ""; - var _dictionaryService = new DictionaryService(_redisHelper); - var project = _dictionaryService.GetValue(HashKeyNames.ProjectInfo, new String[] { this.tenantInfo.ProjectId.ToString() }).FirstOrDefault(); - - if (project.Value != null) - { - if (string.IsNullOrEmpty(project.Value.Dbstr)) - { - throw new NullReferenceException($"项目ID {project.Key}无法找到连接串"); - } - connectionString = project.Value.Dbstr; - } - else - { - // throw new NullReferenceException($"项目ID {project.Key}无法找到连接串"); - } - return connectionString; - } - public string GetRedisPrefix() - { - var prefix = ""; - var _dictionaryService = new DictionaryService(_redisHelper); - var project = _dictionaryService.GetValue(HashKeyNames.ProjectInfo, new String[] { this.tenantInfo.ProjectId.ToString() }).FirstOrDefault(); - - if (project.Value != null) - { - if (string.IsNullOrEmpty(project.Value.Engabb)) - { - throw new NullReferenceException($"项目ID {project.Key}无法找到Redis前缀"); - } - prefix = project.Value.Engabb; - if (!project.Value.Engabb.EndsWith("_")) - { - prefix = prefix + "_"; - } - } - else - { - //throw new NullReferenceException($"项目ID {project.Key}无法找到Redis前缀"); - } - return prefix; - } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs deleted file mode 100644 index 47f82e6..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace WeiCloud.Core.TenantDb -{ - /// - /// 多租户信息 - /// - public class TenantInfo - { - /// - /// 项目ID - /// - public long ProjectId { get; set; } - /// - /// redis前缀 - /// - public string RedisPrefix { get; set; } - - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs b/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs deleted file mode 100644 index 244d501..0000000 --- a/WeiCloud.Fusion/WeiCloud.Core/TenantDb/TenantInfoMiddleware.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.AspNetCore.Http; -using System.Threading.Tasks; -using WeiCloud.Utils; -using Microsoft.Extensions.DependencyInjection; - -namespace WeiCloud.Core.TenantDb -{ - public class TenantInfoMiddleware - { - private readonly RequestDelegate _next; - - - public TenantInfoMiddleware(RequestDelegate next) - { - _next = next; - - } - - public async Task InvokeAsync(HttpContext context) - { - var tenantInfo = context.RequestServices.GetRequiredService(); - var projectId = context.Request.Headers["ProjectId"]; - - if (string.IsNullOrEmpty(projectId)) - { - projectId = "-1"; - } - - long.TryParse(projectId, out long d); - tenantInfo.ProjectId = d; - // Call the next delegate/middleware in the pipeline - await _next(context); - } - } -} diff --git a/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj b/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj index 7ab19c4..e0a28f1 100644 --- a/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj +++ b/WeiCloud.Fusion/WeiCloud.Core/WeiCloud.Core.csproj @@ -62,4 +62,7 @@ + + + -- 2.36.2