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

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

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.persagy.core.mvc.service.CoreService;
import com.persagy.core.service.BaseBusinessService;
import com.persagy.core.service.BusinessService;
import com.persagy.ems.pojo.wz.CityLocation;
import com.persagy.framework.util.WServiceUtil;
import com.persagy.functions.weather.constant.Const;

@Service("WeatherCheckService")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class WeatherCheckService extends BaseBusinessService<Map> implements BusinessService {
	@Resource(name = "coreService")
	private CoreService coreService;
	
	public static Map<String, JSONObject> cityCache = new HashMap<>();
	
	@Override
	public void handle(Map dto, List content) throws Exception {
		String name = (String) dto.get("name");
		if (name == null) {
			throw new Exception(Const.ErrorTag.paramMis);
		}
		
		if(cityCache.isEmpty()) {
			List<CityLocation> list = coreService.query(new CityLocation());
			if(null != list) {
				for(CityLocation obj : list) {
					cityCache.put(obj.getName(), JSONObject.parseObject(obj.getInfo()));
				}
			}
		}
		
		if(cityCache.containsKey(name)) {
			content.add(cityCache.get(name));
		}else {
			Map<String, Object> result = WServiceUtil.getLocation(name);
			if(!result.isEmpty() && result.containsKey("name")) {
				content.add(result);
				JSONObject jsonObj = new JSONObject(result);
				cityCache.put(name, jsonObj);
				
				CityLocation saveItem = new CityLocation();
				saveItem.setName(name);
				saveItem.setInfo(jsonObj.toString());
				coreService.save(saveItem);
			}
		}
	}
}
