package com.persagy.functions.weather.service.impl;

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

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.persagy.core.enumeration.SpecialOperator;
import com.persagy.core.mvc.service.CoreService;
import com.persagy.ems.pojo.wz.DisasterWarning;
import com.persagy.framework.util.DateUtils;
import com.persagy.functions.weather.service.DisasterWarningService;

@Service("disasterWarningService")
public class DisasterWarningServiceImpl implements DisasterWarningService {
	@Resource(name = "coreService")
	private CoreService coreService;

	@Override
	public List<DisasterWarning> query(String cityId, String type, String level, Date startTime, Date endTime)
			throws Exception {
		List<DisasterWarning> list = new ArrayList<DisasterWarning>();
		if (DateUtils.getYear(startTime) != DateUtils.getYear(endTime)) {
			Date midTime = DateUtils.getShortDate(startTime, 5);
			midTime = DateUtils.getYearOff(midTime, 1);
			
			while(startTime.before(endTime)) {
				DisasterWarning queryA = new DisasterWarning();
				queryA.setCityId(cityId);
				queryA.setType(type);
				queryA.setLevel(level);
				queryA.setBuildingForContainer(DateUtils.getYear(startTime) + "");
				queryA.setSpecialOperation("pubTime", SpecialOperator.$gte, startTime);
				queryA.setSpecialOperation("pubTime", SpecialOperator.$lt, midTime);
				List<DisasterWarning> listA = this.coreService.query(queryA);
				if ((listA != null) && (!listA.isEmpty())) {
					list.addAll(listA);
				}
				
				startTime = midTime;
				midTime = DateUtils.getYearOff(midTime, 1);
				if(midTime.after(endTime)) {
					midTime = endTime;
				}
			}
		} else {
			DisasterWarning queryObj = new DisasterWarning();
			queryObj.setCityId(cityId);
			queryObj.setType(type);
			queryObj.setBuildingForContainer(DateUtils.getYear(startTime) + "");
			queryObj.setSpecialOperation("pubTime", SpecialOperator.$gte, startTime);
			queryObj.setSpecialOperation("pubTime", SpecialOperator.$lt, endTime);

			list = this.coreService.query(queryObj);
		}
		return list;
	}

	@Override
	public void save(List<DisasterWarning> list) throws Exception {
		for (DisasterWarning obj : list) {
			obj.setBuildingForContainer(DateUtils.getYear(obj.getPubTime()) + "");
		}
		this.coreService.save(list);
	}

}
