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