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

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.CollectionUtils;
import org.springframework.util.StringUtils;

import com.persagy.core.service.BaseBusinessService;
import com.persagy.core.service.BusinessService;
import com.persagy.ems.pojo.wz.DisasterWarning;
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("DisasterWarningQuery")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class DisasterWarningQuery extends BaseBusinessService<Map> implements BusinessService {

	@Resource
	private DisasterWarningService service;

	@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");
		String type = (String) dto.get("type");
		String level = (String) dto.get("level");

		String cityId = ConfigUtil.getLocationStrict(cityName, cityCode, projectId);
		if (StringUtils.isEmpty(cityId)) {
			throw new Exception(Const.ErrorTag.cityNotFound);
		}
		Date dateStart = startTime == null ? DateUtils.getHourOff(new Date(), -24)
				: DateUtils.str2Date(startTime, "yyyy-MM-dd HH:mm:ss");
		Date dateEnd = endTime == null ? new Date() : DateUtils.str2Date(endTime, "yyyy-MM-dd HH:mm:ss");
		if (DateUtils.getYear(dateStart) != DateUtils.getYear(dateEnd)) {
			throw new Exception(Const.ErrorTag.timeToLong);
		}
		List<DisasterWarning> disasterList = this.service.query(cityId, type, level, dateStart, dateEnd);
		if (!CollectionUtils.isEmpty(disasterList)) {
			for (DisasterWarning obj : disasterList) {
				Map<String, String> item = new HashMap<>();
				item.put("cityId", obj.getCityId());
				item.put("name", obj.getName());
				item.put("path", obj.getPath());
				item.put("title", obj.getTitle());
				item.put("type", obj.getType());
				item.put("level", obj.getLevel());
				item.put("description", obj.getDescription());
				item.put("pubTime", DateUtils.date2Str(obj.getPubTime(), "yyyy-MM-dd HH:mm:ss"));
				item.put("insertTime", DateUtils.date2Str(obj.getInsertTime(), "yyyy-MM-dd HH:mm:ss"));
				content.add(item);
			}
		}
	}
}
