using Quartz; using OASystem.API.OAMethodLib.QiYeWeChatAPI; using OASystem.Domain.ViewModels.QiYeWeChat; namespace OASystem.API.OAMethodLib.Quartz.Jobs { /// /// 每周五下午4点执行的定时任务 /// public class WeeklyFridayJob : IJob { private readonly ILogger _logger; private readonly SqlSugarClient _sqlSugar; private readonly IQiYeWeChatApiService _qiYeWeChatApiService; private readonly HttpClient _httpClient; public WeeklyFridayJob(ILogger logger, SqlSugarClient sqlSugar , IHttpClientFactory httpClientFactory, IQiYeWeChatApiService qiYeWeChatApiService) { _logger = logger; _sqlSugar = sqlSugar; _httpClient = httpClientFactory.CreateClient(); _qiYeWeChatApiService = qiYeWeChatApiService; } public async Task Execute(IJobExecutionContext context) { var jobName = context.JobDetail.Key.Name; _logger.LogInformation($"开始执行任务 {jobName},时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}"); try { var startDate = DateTime.Today.AddDays(-4); var endDate = DateTime.Today.AddDays(1); string baseUrl = "http://localhost:5256"; var createUserId = 4; var sqSetting = _sqlSugar.Queryable().First(x => x.Id == 1417); if (sqSetting != null) { Dictionary> result = JsonConvert.DeserializeObject>>(sqSetting.Remark); result = new Dictionary> { { 235, new List { 258 } } }; foreach (var item in result.Keys) { var keyUser = await _sqlSugar.Queryable() .FirstAsync(x => x.Id == item); var users = await _sqlSugar.Queryable() .LeftJoin((u, d) => u.DepId == d.Id) .LeftJoin((u, d, jp) => u.JobPostId == jp.Id) .Where((u, d, jp) => u.IsDel == 0 && result[item].Contains(u.Id) && u.Id != item) .Select((u, d, jp) => new { u.Id, u.CnName, DepName = d.DepName ?? "", JobName = jp.JobName ?? "" }) .ToListAsync(); foreach (var user in users) { // 构建API URL string apiUrl = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_AllDepartment"; // 构建查询参数 var queryParams = new Dictionary { { "userId", user.Id.ToString() }, { "start", startDate.ToString("yyyy-MM-dd HH:mm:ss") }, { "end", endDate.ToString("yyyy-MM-dd HH:mm:ss") }, { "createUserId", createUserId.ToString() }, { "isMonthData", "true" } }; // 构建完整URL var queryString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}")); string fullUrl = $"{apiUrl}?{queryString}"; _logger.LogInformation($"正在为用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成绩效数据..."); _logger.LogInformation($"API URL: {fullUrl}"); // 发送HTTP GET请求 var response = await _httpClient.GetAsync(fullUrl); var responseContent = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { // 尝试解析响应结果 try { var resultJson = JsonConvert.DeserializeObject(responseContent); if (resultJson != null && resultJson.Code == 200) { _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成成功"); //生成PDF var url = $"{baseUrl}/api/PersonnelModule/AiPerformanceAnalysis_JobMarketingFileDown"; //构建PDF查询参数 var queryParamsPdf = new Dictionary { { "userId", user.Id.ToString() }, { "start", startDate.ToString("yyyy-MM-dd") }, { "end", endDate.ToString("yyyy-MM-dd") }, }; var queryStringPdf = string.Join("&", queryParamsPdf.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}")); url = $"{url}?{queryStringPdf}"; _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 开始生成PDF:{url}"); var pdfUrl = await _httpClient.PostAsync(url, new StringContent(queryStringPdf)); if (pdfUrl.IsSuccessStatusCode) { _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 开始生成PDF:{pdfUrl.StatusCode}"); var pdfContent = await pdfUrl.Content.ReadAsStringAsync(); _logger.LogInformation($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成PDF成功:{pdfContent}"); var pdfContentJson = JObject.Parse(pdfContent); var pdfUrlString = pdfContentJson["data"]["url"].ToString(); var pdfUrlSeed = new Uri(pdfUrlString); var pdfBytes = await _httpClient.GetByteArrayAsync(pdfUrlSeed); var pdfFile = new FormFile(new MemoryStream(pdfBytes), 0, pdfBytes.Length, "pdf", "pdf"); await _qiYeWeChatApiService.EmailSendAsync(new EmailRequestDto { ToEmails = new List { keyUser.Email }, Subject = $"用户 {user.CnName}(部门:{user.DepName} 日期区间:{startDate.ToString("yyyy-MM-dd")} 至 {endDate.ToString("yyyy-MM-dd")}) 绩效数据", Body = "员工绩效推送,请查看附件。", Files = new[] { pdfFile } }); } else { _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成PDF失败:{pdfUrl.StatusCode}"); _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 生成PDF失败:{pdfUrl.Content.ReadAsStringAsync()}"); } } else { _logger.LogWarning($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成失败:{resultJson?.Msg ?? "未知错误"}"); } } catch (Exception ex) { _logger.LogError(ex, $"解析用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 的API响应失败"); } } else { _logger.LogError($"用户 {user.CnName}(ID:{user.Id}, 部门:{user.DepName}) 绩效数据生成API调用失败,状态码: {response.StatusCode}, 响应内容: {responseContent}"); } // 添加延迟,避免请求过于频繁 await Task.Delay(3000); // 延迟3秒 } } } } catch (Exception ex) { _logger.LogError(ex, $"任务 {jobName} 执行失败"); } } } }