package com.zhizhao.fire.backend.task;
import com.alibaba.fastjson2.JSONObject;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhizhao.fire.backend.util.DateUtil;
import com.zhizhao.fire.backend.util.IdUtils;
import com.zhizhao.fire.common.dao.HolidaysAndWeekendsRepository;
import com.zhizhao.fire.common.model.HolidaysAndWeekends;
import com.zhizhao.fire.common.vo.CalendarTypeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
@Configuration //读取配置
@EnableScheduling // 2.开启定时任务
@Slf4j
public class RefreshCalendarTask {
private static final int MAX_RETRIES = 3; // 最大重试次数
private static final long RETRY_DELAY = 1000; // 重试延迟时间(毫秒)
@Autowired
private HolidaysAndWeekendsRepository holidaysAndWeekendsRepository;
@Scheduled(cron = "0 1 1 28 12 ?")
// @Scheduled(cron = "0 */1 * * * *") // 每小时的整点执行一次
public void syncHoliday() {
try {
log.info("每年12月28凌晨1点定时同步下一年的节假日信息,同步节假日开始时间 = {}", DateUtil.format(new Date()));
// 获取当前年份
int currentYear = Year.now().getValue();
// 计算下一年
// int nextYear = currentYear + 1;
int nextYear=2024;
Map jjr = getJjr(nextYear);
Object type = jjr.get("type");
List<CalendarTypeVo> convert = convert(type);
convert.stream().map(a -> {
HolidaysAndWeekends holidaysAndWeekends = new HolidaysAndWeekends();
holidaysAndWeekends.setId(IdUtils.fastSimpleUUID());
holidaysAndWeekends.setType(a.getType());
holidaysAndWeekends.setDescription(a.getDescription());
holidaysAndWeekends.setDateTime(a.getDateTime());
// holidaysAndWeekendsRepository.save(holidaysAndWeekends);
return null;
}).collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
log.info("同步节假日超时 e.printStackTrace():" + e);
}
}
// 数据转换函数
public List<CalendarTypeVo> convert(Object type) {
Map<String, Map<String, Object>> typeData = null;
if (type instanceof Map) {
try {
typeData = (Map<String, Map<String, Object>>) type;
} catch (ClassCastException e) {
System.out.println("类型转换失败: " + e.getMessage());
}
}
// 日期格式化工具
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<CalendarTypeVo> calendarTypeVoList = new ArrayList<>();
for (Map.Entry<String, Map<String, Object>> entry : typeData.entrySet()) {
String dateStr = entry.getKey();
Map<String, Object> typeInfo = entry.getValue();
CalendarTypeVo vo = new CalendarTypeVo();
try {
vo.setDateTime(sdf.parse(dateStr));
} catch (ParseException e) {
e.printStackTrace();
}
vo.setType((Integer) typeInfo.get("type"));
vo.setDescription((String) typeInfo.get("name"));
calendarTypeVoList.add(vo);
}
return calendarTypeVoList;
}
/**
* 获取节假日
*
* @param year
* @return
*/
// private Map getJjr(int year) {
// String url = String.format("http://timor.tech/api/holiday/year/%d?type=Y", year);
// OkHttpClient client = new OkHttpClient();
// Response response;
// //解密数据
// String rsa = null;
// Request request = new Request.Builder()
// .url(url)
// .get()
// .addHeader("Content-Type", "application/x-www-form-urlencoded")
// .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
// .build();
// try {
// client.setConnectTimeout(10, TimeUnit.SECONDS);
// client.setReadTimeout(10,TimeUnit.SECONDS);
// response = client.newCall(request).execute();
// rsa = response.body().string();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return JSONObject.parseObject(rsa, Map.class);
// }
public Map<String, Object> getJjr(int year) {
String url = String.format("http://timor.tech/api/holiday/year/%d?type=Y", year);
String responseString = makeRequestWithRetry(url, MAX_RETRIES);
if (responseString != null) {
return JSONObject.parseObject(responseString, Map.class);
} else {
return null; // 或者返回一个空的 Map,取决于你的需求
}
}
private String makeRequestWithRetry(String url, int maxRetries) {
int attempt = 0;
OkHttpClient client = new OkHttpClient();
while (attempt < maxRetries) {
try {
Request request = new Request.Builder()
.url(url)
.get()
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
System.out.println("Request failed with code: " + response.code());
}
} catch (IOException e) {
System.out.println("Request failed on attempt " + (attempt + 1));
e.printStackTrace();
}
attempt++;
if (attempt < maxRetries) {
try {
Thread.sleep(RETRY_DELAY);
} catch (InterruptedException ie) {
ie.printStackTrace();
Thread.currentThread().interrupt(); // 保持中断状态
}
}
}
return null;
}
}