using Azure.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Identity.Client; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Shentun.Utilities; using Shentun.WebPeis.AppointPatientRegisters; using Shentun.WebPeis.PatientRegisters; using Shentun.WebPeis.PlugIns; using Shentun.WebPeis.QueueRegisters; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Shentun.WebPeis.Plugins { public class AppQueueRegisterPlugIns { protected IConfiguration? AppConfig; private string? _appBaseAddress; private static string? _accesToken; private string? _appUser; private string? _appPassword; private string? _appQueueRegisterUrl; private string? _appIsPeisRegisterUrl; private string? _appUpdateAppointPatientAsbitemStatusUrl; public AppQueueRegisterPlugIns() { Init(); } public void Init() { AppConfig = new ConfigurationBuilder() .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); _appBaseAddress = AppConfig.GetSection("Peis") .GetSection("PeisBaseUrl").Value; _appUser = AppConfig.GetSection("Peis") .GetSection("AppUser").Value; _appPassword = AppConfig.GetSection("Peis") .GetSection("AppPassWord").Value; _appQueueRegisterUrl = AppConfig.GetSection("Peis") .GetSection("AppQueueRegisterUrl").Value; _appIsPeisRegisterUrl = AppConfig.GetSection("Peis") .GetSection("AppIsPeisRegisterUrl").Value; _appUpdateAppointPatientAsbitemStatusUrl= AppConfig.GetSection("Peis") .GetSection("AppUpdateAppointPatientAsbitemStatusUrl").Value; } /// /// 小程序获取当前排队信息 /// /// /// public async Task GetAppQueueRegisterByIdNoAsync(IdNoInputDto input) { var appQueueRegisterByPersonIdDtos = await CallAppServiceAsync(_appQueueRegisterUrl, input); return appQueueRegisterByPersonIdDtos; } /// /// 获取预约记录是否在体检系统登记,用于判断是否能退款 /// /// /// public async Task GetAppointPatientRegisterIsPeisRegisterAsync(AppointPatientRegisterIdInputDto input) { bool isPeisRegister = await CallAppServiceAsync(_appIsPeisRegisterUrl, input); return isPeisRegister; } /// /// 小程序退款成功后,更新体检系统项目收费状态 /// /// /// public async Task UpdateAppointPatientAsbitemStatusAsync(UpdateAppointPatientAsbitemStatusInputDto input) { await CallAppServiceAsync(_appUpdateAppointPatientAsbitemStatusUrl, input); } public async Task CallAppServiceAsync(string url, TInput data, string method = "post") { 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, 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(); var resultDto = JsonConvert.DeserializeObject>(result); if (resultDto != null) { if (resultDto.Code == -1) { throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message); } return resultDto.Data; } return resultDto.Data; } } } } 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(); } } } } public async Task> LoginAsync() { if (string.IsNullOrWhiteSpace(_appUser)) { throw new Exception("SelfUser不能为空"); } if (string.IsNullOrWhiteSpace(_appPassword)) { throw new Exception("SelfPassword不能为空"); } var relult = await LoginAsync(_appUser, _appPassword); return relult; } public async Task> 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>(result); if (restultDto == null) { throw new Exception("返回结果是空"); } if (restultDto.Code != 1) { throw new Exception($"登录失败{restultDto.Message}"); } _accesToken = restultDto.Data.access_token; return restultDto; } } } } } }