using System.Net.Http.Headers; using System.Reflection; using System.Text; using Dlhis.Middle.Entities; using Dlhis.Middle.Response; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.UnifyResultAndValidation; using Kurisu.AspNetCore.Utils.Extensions; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; using SqlSugar; namespace Dlhis.Middle.Services.Implements; public class DataDownloadService : IDataDownloadService { private readonly IHttpClientFactory _httpClientFactory; private readonly IMemoryCache _memoryCache; private readonly IDbContext _dbContext; private readonly string _hostName; public DataDownloadService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, IConfiguration configuration, IDbContext dbContext) { _httpClientFactory = httpClientFactory; _memoryCache = memoryCache; _dbContext = dbContext; _hostName = configuration.GetSection("HostName").Value; } public async Task DownloadAsync(string factory) where T : class, new() { var token = await AuthAsync(); var httpClient = _httpClientFactory.CreateClient("face"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var requestUrl = QueryHelpers.AddQueryString($"https://{_hostName}/api/common/SysData/download", new Dictionary { ["factory"] = factory, ["tableName"] = typeof(T).GetCustomAttribute()!.TableName }); var response = await httpClient.GetStringAsync(requestUrl); var pack = response.ToObject>>(); await _dbContext.InsertAsync(pack.Data); } /// public async Task TruncateAsync() { await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); await _dbContext.Client.Deleteable().ExecuteCommandAsync(); } private async Task AuthAsync() { var httpClient = _httpClientFactory.CreateClient("face"); if (_memoryCache.TryGetValue("token", out string token)) return token; var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new { ClientId = "e509c2aaa98e300c", ClientSecret = "6184d8979fc48105" }), Encoding.UTF8, "application/json")); var tokenJson = await tokenResponse.Content.ReadAsStringAsync(); var tokenInfo = JsonConvert.DeserializeObject>(tokenJson); token = tokenInfo.Data.AccessToken; _memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires)); return token; } }