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

using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
using Shentun.Peis.PatientRegisters;
using Shentun.Utilities;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Linq.Dynamic.Core.Tokenizer;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.Peis.PlugIns
{
public class PlugInsBase
{
protected IConfiguration? AppConfig;
protected IConfiguration? InterfaceConfig;
protected string? AppConnctionStr;
private string? _appBaseAddress;
private static string? _accesToken;
protected string? SelfUser;
protected string? SelfPassword;
protected string? InterfaceSql;
protected string? InterfaceSqlKeyColumn;
protected string? InterfaceDbType;
protected string? InterfaceConnctionStr;
protected string? InterfaceWebApiUrl;
protected Guid ItemColumnReferenceId;
protected Guid AsbitemColumnReferenceId;
protected Guid DepartmentColumnReferenceId;
protected Guid UserColumnReferenceId;
static PlugInsBase()
{
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
}
public PlugInsBase()
{
Init();
}
public PlugInsBase(string parmValue)
{
Init();
Init(parmValue);
}
public void Init()
{
AppConfig = new ConfigurationBuilder()
.SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
AppConnctionStr = AppConfig.GetSection("ConnectionStrings")
.GetSection("Default").Value;
_appBaseAddress = AppConfig.GetSection("App")
.GetSection("SelfUrl").Value;
SelfUser = AppConfig.GetSection("App")
.GetSection("SelfUser").Value;
SelfPassword = AppConfig.GetSection("App")
.GetSection("SelfPassword").Value;
}
public void Init(string parmValue)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue)));
InterfaceConfig = configurationBuilder.Build();
InterfaceSql = InterfaceConfig.GetSection("Interface").GetSection("Sql").Value;
InterfaceSqlKeyColumn = InterfaceConfig.GetSection("Interface").GetSection("SqlKeyColumn").Value;
InterfaceDbType = InterfaceConfig.GetSection("Interface").GetSection("DbType").Value;
InterfaceWebApiUrl = InterfaceConfig.GetSection("Interface").GetSection("WebApiUrl").Value;
InterfaceConnctionStr = InterfaceConfig.GetSection("Interface").GetSection("ConnectionStrings").Value;
var itemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("ItemColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(itemColumnReferenceIdStr))
{
ItemColumnReferenceId = new Guid(itemColumnReferenceIdStr);
}
var asbItemColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("AsbitemColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(asbItemColumnReferenceIdStr))
{
AsbitemColumnReferenceId = new Guid(asbItemColumnReferenceIdStr);
}
var departmentColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("DepartmentColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(departmentColumnReferenceIdStr))
{
DepartmentColumnReferenceId = new Guid(departmentColumnReferenceIdStr);
}
var userColumnReferenceIdStr = InterfaceConfig.GetSection("Interface")
.GetSection("UserColumnReferenceId").Value;
if (!string.IsNullOrWhiteSpace(userColumnReferenceIdStr))
{
UserColumnReferenceId = new Guid(userColumnReferenceIdStr);
}
}
protected DbConnection CreateInterfaceDbConnect()
{
DbConnection conn;
if (string.IsNullOrWhiteSpace(InterfaceConnctionStr))
{
throw new ArgumentException("数据连接设置中的DbType不能为空");
}
InterfaceDbType = InterfaceDbType.ToLower();
if (InterfaceDbType == "sqlserver")
{
conn = new SqlConnection(InterfaceConnctionStr);
}
else if (InterfaceDbType == "postgres")
{
conn = new NpgsqlConnection(InterfaceConnctionStr);
}
else if (InterfaceDbType == "oracle")
{
conn = new OracleConnection(InterfaceConnctionStr);
}
else
{
throw new ArgumentException("数据连接设置中的DbType不支持");
}
return conn;
}
public async Task<TOut> CallAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
{
if(string.IsNullOrWhiteSpace(_appBaseAddress))
{
throw new Exception("_appBaseAddress不能为空");
}
string baseAddress = _appBaseAddress;
await CheckLoginAsync();
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(baseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken);
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
var sendData = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, timeFormat);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = null;
if (method == "post")
{
response = await httpClient.PostAsync(url, httpContent);
}
else
{
response = await httpClient.GetAsync(url);
}
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
dynamic resultDto = JsonConvert.DeserializeObject(result);
if (resultDto != null)
{
if (resultDto.code == "-1")
{
throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.message);
}
JObject jsonObject = JObject.Parse(result);
var returnStr = jsonObject["data"].ToString();
if (string.IsNullOrWhiteSpace(returnStr) || returnStr == "null")
{
return default(TOut);
}
var returnValue = JsonConvert.DeserializeObject<TOut>(returnStr);
return returnValue;
}
return resultDto;
}
}
}
}
public virtual async Task DoWorkAsync()
{
}
public virtual Task DoWork()
{
return Task.CompletedTask;
}
public async virtual Task<LoginOutDto> LoginAsync()
{
if(string.IsNullOrWhiteSpace(SelfUser))
{
throw new Exception("SelfUser不能为空");
}
if (string.IsNullOrWhiteSpace(SelfPassword))
{
throw new Exception("SelfPassword不能为空");
}
var relult = await LoginAsync(SelfUser, SelfPassword);
return relult;
}
public async Task<LoginOutDto> LoginAsync(string userId, string password)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new Exception("用户ID不能为空");
}
if (string.IsNullOrWhiteSpace(password))
{
throw new Exception("密码不能为空");
}
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(_appBaseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
var url = "api/identity/users/login";
var loginUser = new LoginInputDto()
{
UserName = userId,
Password = password
};
var sendData = JsonConvert.SerializeObject(loginUser);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
var restultDto = JsonConvert.DeserializeObject<LoginOutDto>(result);
if (restultDto == null)
{
throw new Exception("返回结果是空");
}
if (restultDto.Code != "1")
{
throw new Exception($"登录失败{restultDto.Message}");
}
_accesToken = restultDto.Data.access_token;
return restultDto;
}
}
}
}
private async Task CheckLoginAsync()
{
if (string.IsNullOrWhiteSpace(_accesToken))
{
await LoginAsync();
}
else
{
var handler = new JwtSecurityTokenHandler();
var payload = handler.ReadJwtToken(_accesToken).Payload;
var claims = payload.Claims;
var exp = claims.First(claim => claim.Type == "exp").Value;
if (exp == null)
{
await LoginAsync();
}
else
{
if (long.TryParse(exp, out var expires))
{
var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
if (expireTime <= DateTime.Now)
{
await LoginAsync();
}
}
else
{
await LoginAsync();
}
}
}
}
}
}