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

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

import com.persagy.core.service.BaseBusinessService;
import com.persagy.core.service.BusinessService;
import com.persagy.framework.util.ConfigUtil;
import com.persagy.framework.util.DateUtils;
import com.persagy.functions.weather.constant.Const;
import com.persagy.functions.weather.dto.TempStatisticsDTO;
import com.persagy.functions.weather.service.WeatherStatisticsService;

/**
 * Description: 查询历史天气统计信息
 */
@Service("GetTempBuildingStatistics")
@SuppressWarnings({ "rawtypes","unchecked" })
public class GetTempBuildingStatistics extends BaseBusinessService<Map> implements BusinessService {
	
	@Resource
	private WeatherStatisticsService weatherStatisticsService;

	@Override
    public void handle(Map dto, List content) throws Exception {
    	List<String> cityCodeList = (List<String>) dto.get("cityCodeList");
    	String startDateStr = (String) dto.get("startDate");
    	String endDateStr = (String)dto.get("endDate");
    	if(CollectionUtils.isEmpty(cityCodeList) || StringUtils.isEmpty(startDateStr) || StringUtils.isEmpty(endDateStr)) {
    		throw new Exception(Const.ErrorTag.paramMis);
    	}
    	
    	Map<String, String> cityId2code = new HashMap<>();
    	for(String cityCode : cityCodeList) {
    		String location = ConfigUtil.getHourCity(null, cityCode, null);
    		if(null != location) {
    			cityId2code.put(location, cityCode);
    		}
    	}
    	if(cityId2code.isEmpty()) {
    		throw new Exception(Const.ErrorTag.cityUnsupport);
    	}
    	
    	Date startDate = DateUtils.str2Date(startDateStr, DateUtils.SDF_SECOND);
    	Date endDate = DateUtils.str2Date(endDateStr, DateUtils.SDF_SECOND);
    	TempStatisticsDTO statistics = weatherStatisticsService.getTempBuildingStatisticsDTO(new ArrayList<>(cityId2code.keySet()), startDate, endDate);
    	Map<String,Object> resultMap = new HashMap<>();
    	resultMap.put("maxTemp", statistics.getMaxTemp());
    	resultMap.put("minTemp", statistics.getMinTemp());
    	resultMap.put("avgTemp", statistics.getAvgTemp());
    	Map<String, Double> buildingMap = new HashMap<>();
    	Map<String, Double> tempBuildingMap = statistics.getBuildingTempMap();
    	if(null != tempBuildingMap) {
    		for(String cityId : tempBuildingMap.keySet()) {
    			buildingMap.put(cityId2code.get(cityId), tempBuildingMap.get(cityId));
    		}
    	}
    	resultMap.put("buildingTempMap", buildingMap);
    	content.add(resultMap);
    	
    }
}

