package com.persagy.framework.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.persagy.core.component.JsonObjectMapper;
import com.persagy.core.utils.HttpUtils;
import com.persagy.functions.weather.dto.DayHolidayDTO;


/**
 * Description: 法定休息日，工作日信息服务   
 * Company: Persagy 
 * @author cuixubin 
 * @since: 2019年1月14日: 上午9:25:59
 */
public class HolidaySearchUtil {
	public static final int START_YEAR = 2017;
	private static final String URL_GOSEEK_GET = "http://api.goseek.cn/Tools/holiday?date=";
	private static final Logger logger = Logger.getLogger(HolidaySearchUtil.class);
	
	private static JsonObjectMapper objectMapper = new JsonObjectMapper();
	
	@SuppressWarnings("unchecked")
	public static List<DayHolidayDTO> queryHolidayCodeForOneYear(int year) {
		
		List<DayHolidayDTO> resultList = new ArrayList<DayHolidayDTO>();
		
		int nowYear = DateUtils.getYear(new Date());
		
		int errorNum = 0;
		
		if(year >= START_YEAR && year <= nowYear) {
			
			Date yearStart = null;
			Date yearEnd = null;
			try {
				yearStart = DateUtils.str2Date(year+"-01-01", DateUtils.SDF_DAY);
				yearEnd = DateUtils.getYearOff(yearStart, 1);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			if(yearStart != null && yearEnd != null) {
				Map<String, String> params = new HashMap<String, String>();
				
				Date dayOfYear = yearStart;
				
				while(dayOfYear.before(yearEnd)) {
					// 10次请求出错则停止
					if(errorNum == 10) {
						break;
					}
					
					try {
						// 结果数据结构{"code":10000,"data":0}
						String result = HttpUtils.get(URL_GOSEEK_GET + Integer.parseInt(DateUtils.date2Str(dayOfYear, DateUtils.SDFDAY)), params);
						Map<String, Object> paramObj = objectMapper.readValue(result, Map.class);
						
						if(paramObj.containsKey("code") && paramObj.containsKey("data")) {
							resultList.add(new DayHolidayDTO(dayOfYear, (Integer) paramObj.get("data")));
						}else {
							errorNum ++;
						}
					}catch (Exception e) {
						errorNum ++;
						e.printStackTrace();
					}
					
					dayOfYear = DateUtils.getDayOff(dayOfYear, 1);
				}
				
				if(errorNum >= 10) {
					logger.error("查询法定日信息请求失败，接口：" + URL_GOSEEK_GET + "，年份：" + year);
					resultList.clear();
				}
			}
		}else {
			logger.error("查询法定日年份[" + year + "]不支持,仅支持[" + START_YEAR + "," + nowYear + "]");
		}
		
		return resultList;
	}
	
}
