package xiaoqu.home.open.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.model.db2.Holiday;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.db2.HolidayService;

/**
 * <p>
 * 此类用于：抓取节假期信息
 */
@Slf4j
@Component
public class HolidayTask {
	@Resource
	private HolidayService holidayService;
	@Autowired
	RedisService4 redisService4;

	public static void main(String[] args) {
		System.out.println(DateUtil.format(DateUtil.offset(new Date(), DateField.YEAR, 1), "yyyy"));
	}

	@Scheduled(cron = "6 6 6 28 12 ?")
	public void syncHoliday() throws InterruptedException {
		//为了解决部署多个服务增加锁机制
		//进来之后随机休息 几秒钟 最新唤醒的抓取数据并且加锁
		TimeUnit.SECONDS.sleep(RandomUtil.randomLong(10, 100));
		if (redisService4.exists("HolidayLock")) {
			return;
		}
		redisService4.set("HolidayLock", System.nanoTime()+"",1800L);

		log.info("每年12月28凌晨1点定时同步下一年的节假日信息，同步节假日开始时间 = {}", DateUtil.formatDateTime(new Date()));
		ConcurrentLinkedQueue<String> daytList = new  ConcurrentLinkedQueue<String>();
//		String url = "http://timor.tech/api/holiday/year/";
		String url = "http://timor.tech/api/holiday/info/";
		String beginDateString = "-01-01";
		String year = DateUtil.format(DateUtil.offset(new Date(), DateField.YEAR, 1), "yyyy");
		String beginDateTime = year + beginDateString;
		Date beginDate = DateUtil.parse(beginDateTime, "yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(beginDate);
		int numOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
		List<Holiday> listHoliday = new ArrayList<Holiday>();
		for (int i = 0; i < numOfDays; i++) {
			Date temDate = DateUtil.offsetDay(beginDate, i);
			String temDateString = DateUtil.format(temDate, "yyyy-MM-dd");
			String temUrlString = url + temDateString;
			String stringResponseEntity = HttpUtil.get(temUrlString);
			JSONObject jSONObject = JSONObject.parseObject(stringResponseEntity);
			if (jSONObject != null) {
				Integer code = jSONObject.getInteger("code");
				if (code == 0) {
//    				{"code":0,"type":{"type":1,"name":"周日","week":7},"holiday":null}
					JSONObject holidayJson = jSONObject.getJSONObject("type");
					String jsonString = holidayJson.toJSONString();
					log.info(" " + temUrlString);
					log.info("获取节假日数据内容为 jsonString = 【{}】", jsonString);
					Holiday holiday = new Holiday();
					holiday.setType(holidayJson.getInteger("type"));
					holiday.setHolidayName(holidayJson.getString("name"));
					holiday.setHolidayDate(temDateString);
					holiday.setCreateTime(new Date());
					listHoliday.add(holiday);

				} else {
					log.error("调用节假日网站服务出错！"+code+"-"+temUrlString);
					daytList.add(temDateString);
				}

			}
		}
		String temDateString = daytList.poll();
		while (temDateString!=null) {
			String temUrlString = url + temDateString;
			String stringResponseEntity = HttpUtil.get(temUrlString);
			JSONObject jSONObject = JSONObject.parseObject(stringResponseEntity);
			if (jSONObject != null) {
				Integer code = jSONObject.getInteger("code");
				if (code == 0) {
//    				{"code":0,"type":{"type":1,"name":"周日","week":7},"holiday":null}
					JSONObject holidayJson = jSONObject.getJSONObject("type");
					String jsonString = holidayJson.toJSONString();
					log.info(" " + temUrlString);
					log.info("获取节假日数据内容为 jsonString = 【{}】", jsonString);
					Holiday holiday = new Holiday();
					holiday.setType(holidayJson.getInteger("type"));
					holiday.setHolidayName(holidayJson.getString("name"));
					holiday.setHolidayDate(temDateString);
					holiday.setCreateTime(new Date());
					listHoliday.add(holiday);

				} else {
					log.error("调用节假日网站服务出错！"+code+"-"+temUrlString);
					daytList.add(temDateString);
				}
				Thread.sleep(1000);
			}
			temDateString = daytList.poll();
		}
		holidayService.saveBatch(listHoliday);
		log.info("每年12月28凌晨1点定时同步下一年的节假日信息，同步节假日结束时间 = {}", DateUtil.formatDateTime(new Date()));
	}
}
