package com.persagy.functions.weather.business.v2021;

import java.util.ArrayList;
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.enumeration.SpecialOperator;
import com.persagy.ems.pojo.wz.DisasterWarning;
import com.persagy.framework.construct.RequestProcessor;
import com.persagy.framework.dto.DataQueryParam;
import com.persagy.framework.util.ConfigUtil;
import com.persagy.framework.util.DateUtils;
import com.persagy.functions.weather.constant.Const;
import com.persagy.functions.weather.service.DisasterWarningService;

/**
 * 灾害预警数据
 */
@Service("disaster")
public class QueryDisaster implements RequestProcessor {
	@Resource
	private DisasterWarningService service;

	@Override
	public Object handle(DataQueryParam param) throws Exception {
		List<Map<String, Object>> resultList = new ArrayList<>();
		
		String location = ConfigUtil.getLocationStrict(param.cityName, param.cityCode, param.projectId);
		if (StringUtils.isEmpty(location)) {
			throw new Exception(Const.ErrorTag.cityNotFound);
		}
		
		if(param.timeSpanCheck(366)) {
			Date startDay = param.timeSpan.timeLeft;
			Date endDay = param.timeSpan.timeRight;
			if(param.timeSpan.optLeft == SpecialOperator.$gt) {
				startDay = DateUtils.getDayOff(startDay, 1);
			}
			if(param.timeSpan.optRight == SpecialOperator.$lte) {
				endDay = DateUtils.getDayOff(endDay, 1);
			}
			
			List<DisasterWarning> disasterList = this.service.query(location, null, null, startDay, endDay);
			if (!disasterList.isEmpty()) {
				for (DisasterWarning obj : disasterList) {
					Map<String, Object> item = new HashMap<>();
					item.put("title", obj.getTitle());
					item.put("type", obj.getType());
					item.put("level", obj.getLevel());
					item.put("description", obj.getDescription());
					item.put("pubTime", obj.getPubTime().getTime());
					resultList.add(item);
				}
			}
		}else {
			throw new Exception(Const.ErrorTag.timeToLong);
		}
		
		return resultList;
	}
	
}