You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

321 lines
13 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. using Microsoft.Data.SqlClient;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.Logging;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Converters;
  6. using Newtonsoft.Json.Linq;
  7. using Npgsql;
  8. using Oracle.ManagedDataAccess.Client;
  9. using Shentun.Peis.PatientRegisters;
  10. using Shentun.Utilities;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Data.Common;
  14. using System.IdentityModel.Tokens.Jwt;
  15. using System.Linq;
  16. using System.Linq.Dynamic.Core.Tokenizer;
  17. using System.Net.Http.Headers;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. namespace Shentun.Peis.PlugIns
  21. {
  22. public class PlugInsBase
  23. {
  24. protected IConfiguration? AppConfig;
  25. protected IConfiguration? InterfaceConfig;
  26. protected string? AppConnctionStr;
  27. private string? _appBaseAddress;
  28. private static string? _accesToken;
  29. protected string? SelfUser;
  30. protected string? SelfPassword;
  31. protected string? InterfaceSql;
  32. protected string? InterfaceSqlKeyColumn;
  33. protected string? InterfaceDbType;
  34. protected string? InterfaceConnctionStr;
  35. protected string? InterfaceWebApiUrl;
  36. protected Guid ItemColumnReferenceId;
  37. protected Guid AsbitemColumnReferenceId;
  38. protected Guid DepartmentColumnReferenceId;
  39. protected Guid UserColumnReferenceId;
  40. protected ILogger<PlugInsBase> Logger;
  41. static PlugInsBase()
  42. {
  43. Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
  44. }
  45. public PlugInsBase()
  46. {
  47. Init();
  48. }
  49. public PlugInsBase(string parmValue)
  50. {
  51. Init();
  52. Init(parmValue);
  53. }
  54. public void Init()
  55. {
  56. AppConfig = new ConfigurationBuilder()
  57. .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
  58. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  59. .Build();
  60. AppConnctionStr = AppConfig.GetSection("ConnectionStrings")
  61. .GetSection("Default").Value;
  62. _appBaseAddress = AppConfig.GetSection("App")
  63. .GetSection("SelfUrl").Value;
  64. SelfUser = AppConfig.GetSection("App")
  65. .GetSection("SelfUser").Value;
  66. SelfPassword = AppConfig.GetSection("App")
  67. .GetSection("SelfPassword").Value;
  68. using var loggerFactory = LoggerFactory.Create(builder =>
  69. {
  70. });
  71. Logger = loggerFactory.CreateLogger<PlugInsBase>();
  72. }
  73. public void Init(string parmValue)
  74. {
  75. var configurationBuilder = new ConfigurationBuilder()
  76. .AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue)));
  77. InterfaceConfig = configurationBuilder.Build();
  78. InterfaceSql = InterfaceConfig.GetSection("Interface").GetSection("Sql").Value;
  79. InterfaceSqlKeyColumn = InterfaceConfig.GetSection("Interface").GetSection("SqlKeyColumn").Value;
  80. InterfaceDbType = InterfaceConfig.GetSection("Interface").GetSection("DbType").Value;
  81. InterfaceWebApiUrl = InterfaceConfig.GetSection("Interface").GetSection("WebApiUrl").Value;
  82. InterfaceConnctionStr = InterfaceConfig.GetSection("Interface").GetSection("ConnectionStrings").Value;
  83. var itemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
  84. .GetSection("ItemColumnReferenceId").Value;
  85. if (!string.IsNullOrWhiteSpace(itemColumnReferenceIdStr))
  86. {
  87. ItemColumnReferenceId = new Guid(itemColumnReferenceIdStr);
  88. }
  89. var asbItemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
  90. .GetSection("AsbitemColumnReferenceId").Value;
  91. if (!string.IsNullOrWhiteSpace(asbItemColumnReferenceIdStr))
  92. {
  93. AsbitemColumnReferenceId = new Guid(asbItemColumnReferenceIdStr);
  94. }
  95. var departmentColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
  96. .GetSection("DepartmentColumnReferenceId").Value;
  97. if (!string.IsNullOrWhiteSpace(departmentColumnReferenceIdStr))
  98. {
  99. DepartmentColumnReferenceId = new Guid(departmentColumnReferenceIdStr);
  100. }
  101. var userColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
  102. .GetSection("UserColumnReferenceId").Value;
  103. if (!string.IsNullOrWhiteSpace(userColumnReferenceIdStr))
  104. {
  105. UserColumnReferenceId = new Guid(userColumnReferenceIdStr);
  106. }
  107. }
  108. protected DbConnection CreateInterfaceDbConnect()
  109. {
  110. DbConnection conn;
  111. if (string.IsNullOrWhiteSpace(InterfaceConnctionStr))
  112. {
  113. throw new ArgumentException("数据连接设置中的DbType不能为空");
  114. }
  115. InterfaceDbType = InterfaceDbType.ToLower();
  116. //Logger.LogInformation("数据库类型:" + InterfaceDbType);
  117. if (InterfaceDbType == "sqlserver")
  118. {
  119. //Logger.LogInformation("调用sqlserver:" + InterfaceDbType);
  120. conn = new SqlConnection(InterfaceConnctionStr);
  121. }
  122. else if (InterfaceDbType == "postgres")
  123. {
  124. //Logger.LogInformation("调用postgres:" + InterfaceDbType);
  125. conn = new NpgsqlConnection(InterfaceConnctionStr);
  126. }
  127. else if (InterfaceDbType == "oracle")
  128. {
  129. //Logger.LogInformation("调用oracle:" + InterfaceDbType);
  130. conn = new OracleConnection(InterfaceConnctionStr);
  131. }
  132. else
  133. {
  134. throw new ArgumentException("数据连接设置中的DbType不支持");
  135. }
  136. return conn;
  137. }
  138. public async Task<TOut> CallAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
  139. {
  140. if(string.IsNullOrWhiteSpace(_appBaseAddress))
  141. {
  142. throw new Exception("_appBaseAddress不能为空");
  143. }
  144. string baseAddress = _appBaseAddress;
  145. await CheckLoginAsync();
  146. using (var httpClientHandler = new HttpClientHandler())
  147. {
  148. using (var httpClient = new HttpClient(httpClientHandler))
  149. {
  150. httpClient.BaseAddress = new Uri(baseAddress);
  151. httpClient.DefaultRequestHeaders.Accept.Add(
  152. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  153. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken);
  154. IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
  155. timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  156. var sendData = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, timeFormat);
  157. using (HttpContent httpContent = new StringContent(sendData))
  158. {
  159. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  160. HttpResponseMessage response = null;
  161. if (method == "post")
  162. {
  163. response = await httpClient.PostAsync(url, httpContent);
  164. }
  165. else
  166. {
  167. response = await httpClient.GetAsync(url);
  168. }
  169. string result;
  170. if (!response.IsSuccessStatusCode)
  171. {
  172. result = response.Content.ReadAsStringAsync().Result;
  173. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  174. }
  175. result = await response.Content.ReadAsStringAsync();
  176. var resultDto = JsonConvert.DeserializeObject< WebApiOutDto<TOut>>(result);
  177. if (resultDto.Code == -1)
  178. {
  179. throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message);
  180. }
  181. return resultDto.Data;
  182. }
  183. }
  184. }
  185. }
  186. public virtual async Task DoWorkAsync()
  187. {
  188. }
  189. public virtual Task DoWork()
  190. {
  191. return Task.CompletedTask;
  192. }
  193. public async virtual Task<WebApiOutDto<LoginOutDataDto>> LoginAsync()
  194. {
  195. if(string.IsNullOrWhiteSpace(SelfUser))
  196. {
  197. throw new Exception("SelfUser不能为空");
  198. }
  199. if (string.IsNullOrWhiteSpace(SelfPassword))
  200. {
  201. throw new Exception("SelfPassword不能为空");
  202. }
  203. var relult = await LoginAsync(SelfUser, SelfPassword);
  204. return relult;
  205. }
  206. public async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync(string userId, string password)
  207. {
  208. if (string.IsNullOrWhiteSpace(userId))
  209. {
  210. throw new Exception("用户ID不能为空");
  211. }
  212. if (string.IsNullOrWhiteSpace(password))
  213. {
  214. throw new Exception("密码不能为空");
  215. }
  216. using (var httpClientHandler = new HttpClientHandler())
  217. {
  218. using (var httpClient = new HttpClient(httpClientHandler))
  219. {
  220. httpClient.BaseAddress = new Uri(_appBaseAddress);
  221. httpClient.DefaultRequestHeaders.Accept.Add(
  222. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  223. var url = "api/identity/users/login";
  224. var loginUser = new LoginInputDto()
  225. {
  226. UserName = userId,
  227. Password = password
  228. };
  229. var sendData = JsonConvert.SerializeObject(loginUser);
  230. using (HttpContent httpContent = new StringContent(sendData))
  231. {
  232. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  233. HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
  234. string result;
  235. if (!response.IsSuccessStatusCode)
  236. {
  237. result = response.Content.ReadAsStringAsync().Result;
  238. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  239. }
  240. result = await response.Content.ReadAsStringAsync();
  241. var restultDto = JsonConvert.DeserializeObject<WebApiOutDto<LoginOutDataDto>>(result);
  242. if (restultDto == null)
  243. {
  244. throw new Exception("返回结果是空");
  245. }
  246. if (restultDto.Code != 1)
  247. {
  248. throw new Exception($"登录失败{restultDto.Message}");
  249. }
  250. _accesToken = restultDto.Data.access_token;
  251. return restultDto;
  252. }
  253. }
  254. }
  255. }
  256. private async Task CheckLoginAsync()
  257. {
  258. if (string.IsNullOrWhiteSpace(_accesToken))
  259. {
  260. await LoginAsync();
  261. }
  262. else
  263. {
  264. var handler = new JwtSecurityTokenHandler();
  265. var payload = handler.ReadJwtToken(_accesToken).Payload;
  266. var claims = payload.Claims;
  267. var exp = claims.First(claim => claim.Type == "exp").Value;
  268. if (exp == null)
  269. {
  270. await LoginAsync();
  271. }
  272. else
  273. {
  274. if (long.TryParse(exp, out var expires))
  275. {
  276. var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
  277. if (expireTime <= DateTime.Now)
  278. {
  279. await LoginAsync();
  280. }
  281. }
  282. else
  283. {
  284. await LoginAsync();
  285. }
  286. }
  287. }
  288. }
  289. }
  290. }