using Dlhis.ScheduledTask.Comparers; using Dlhis.ScheduledTask.Entities; using Kurisu.SqlSugar.Services; using Mapster; using Newtonsoft.Json; using System.Net.Http.Headers; using System.Text; namespace Dlhis.ScheduledTask.Job { /// /// 职位同步定时任务 /// public class SyncPositionJob { private List lastUpdatedPositionList = new List(); private readonly IDbContext _dbContext; public SyncPositionJob(IDbContext dbContext) { _dbContext = dbContext; } public async Task SyncPositionInfo() { HttpClient httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(10); var credentials = string.Format("{0}:{1}", "EHS_USER", "y3R1hd2h*RICAC"); var headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue); string url = "http://sappidap.jinkosolar.cn:51000/RESTAdapter/Rest/EHR_POSITION/"; string requestBody = "{\"I_DATE\":\"2022-05-26\",\"I_DATE_TO\":\"2022-05-29\",\"I_LANGU\":\"1\",\"I_ALLINFO\":\"X\"}"; StringContent content = new StringContent(requestBody, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); var postResult = JsonConvert.DeserializeObject(responseContent); if (postResult.T_POST != null && postResult.T_POST.item.Count > 0) { var modifiedOrgList = GetModifiedPosition(postResult.T_POST.item); // 步骤 4:使用 SQLSugar 将新数据同步到数据库 SaveOrg(modifiedOrgList); } } else { Console.WriteLine($"HTTP请求失败,状态码:{response.StatusCode}"); } } private List GetModifiedPosition(List spaList) { if (lastUpdatedPositionList.Count <= 0) { return spaList; } var needRemove = spaList.Intersect(lastUpdatedPositionList, new ZHRS_POSTComparer()); return spaList.Except(needRemove, new ZHRS_POSTComparer()).ToList(); } private async void SaveOrg(List modifiedPostList) { if (modifiedPostList == null || modifiedPostList.Count == 0) return; foreach (var item in modifiedPostList) { var existingPosts = await _dbContext.Queryable().Where(x =>x.ZJOBID == item.ZJOBID).FirstAsync(); if (existingPosts != null) { var entity = item.Adapt(existingPosts); await _dbContext.UpdateAsync(entity); } else { var entity = item.Adapt(); await _dbContext.InsertAsync(entity); } } } } }