package com.persagy.functions.weather.business.v2020.history;

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

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.persagy.core.service.BaseBusinessService;
import com.persagy.core.service.BusinessService;
import com.persagy.ems.pojo.wz.DayHisRecord;
import com.persagy.framework.util.ConfigUtil;
import com.persagy.framework.util.DateUtils;
import com.persagy.functions.weather.constant.Const;
import com.persagy.functions.weather.constant.ConstTime;
import com.persagy.functions.weather.service.DayHisRecordService;

@Service("DayHistoryData")
@SuppressWarnings({"unchecked", "rawtypes"})
public class DayHistoryData extends BaseBusinessService<Map> implements BusinessService {
	@Resource
	private DayHisRecordService dayHisRecordService;
	
	@Override
	public void handle(Map dto, List content) throws Exception {

		String cityName = (String) dto.get("cityName");
		String projectId = (String) dto.get("projectId");
		String cityCode = (String) dto.get("cityCode");

		if (StringUtils.isEmpty(projectId) && StringUtils.isEmpty(cityCode) && StringUtils.isEmpty(cityName)) {
			throw new Exception(Const.ErrorTag.paramMis);
		}
		
		String startTime = (String) dto.get("startTime");
		String endTime = (String) dto.get("endTime");
		Date timeFrom = null, timeTo = null;
		try {
			timeFrom = DateUtils.str2Date(startTime, DateUtils.SDF_SECOND);
			timeTo = DateUtils.str2Date(endTime, DateUtils.SDF_SECOND);
		}catch (Exception e) {
		}

		long tspan = timeTo.getTime() - timeFrom.getTime();
		if(null == timeFrom || null == timeTo) {
			throw new Exception(Const.ErrorTag.paramFormat);
		}else if(tspan > (5 * ConstTime.ms_year)) {
			throw new Exception(Const.ErrorTag.timeToLong);
		}
		
		String location = ConfigUtil.getLocation(cityName, cityCode, projectId);
		
		List<DayHisRecord> list = dayHisRecordService.query(location, timeFrom, timeTo);
		if(null != list) {
			for(DayHisRecord obj : list) {
				Map<String, Object> item = new HashMap<>();
				item.put("codeDay", obj.getCode_day());
				item.put("codeNight", obj.getCode_night());
				item.put("dayTime", obj.getDayTime());
				item.put("high", obj.getHigh());
				item.put("humidity", obj.getHumidity());
				item.put("low", obj.getLow());
				item.put("textDay", obj.getText_day());
				item.put("textNight", obj.getText_night());
				item.put("windDirection", obj.getWind_direction());
				item.put("windDirectionDegree", obj.getWind_direction_degree());
				item.put("windScale", obj.getWind_scale());
				item.put("windSpeed", obj.getWind_speed());
				item.put("rainfall", obj.getRainfall());
				item.put("precip", obj.getPrecip());
				content.add(item);
			}
		}
	}
}
