package com.house365.ws.util;

import com.google.common.base.Strings;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.util.SpringContextUtil;
import com.house365.ws.cached.RedisUtilsInterface;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 城市工具类
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author yinchangming
 * @version [v1.0.0, 2015年11月10日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class CityUtil {

    public static final String CM_CITYS = "CITYS";
    private static Logger logger = LoggerFactory.getLogger(CityUtil.class);

    public static Map<String, KlfCityEntity> cityMap;
    public static List<KlfCityEntity> cityList;

    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @author yinchangming
     * @version [v1.0.0, 2015年9月10日]
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("unchecked")
    public static List<KlfCityEntity> getCityList() {
        if (cityList != null && cityMap != null && cityList.size() > 10) {
            return cityList;
        }
        //提供人刘逸君
        String urlString = "http://mopen.house365.com/api/?city=nj&client=tf&channl=app&v=6.0.3&api_key=iPhone&method=getCityList";
        StringBuffer buffer = new StringBuffer(urlString);
        List<KlfCityEntity> cityList = new ArrayList<>();
        // 接口地址 获取JSON字符串
        String jsonStr;
        try {

            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
            if (redisUtils.getValByKeyNew(CM_CITYS) == null || Strings.isNullOrEmpty(
                    redisUtils.getValByKeyNew(CM_CITYS)) || "null".equalsIgnoreCase(redisUtils.getValByKeyNew(CM_CITYS))) {
                jsonStr = HttpClientUtil.getJsonData(buffer.toString());
                redisUtils.setValueExpireNew(CM_CITYS, jsonStr.trim(), 1, TimeUnit.DAYS);
            } else {
                jsonStr = redisUtils.getValByKeyNew(CM_CITYS);
            }

            JSONArray jsonObj = JSONArray.fromObject(jsonStr);
            if (cityMap == null) {
                cityMap = new HashMap<>();
            }
            for (int i = 0; i < jsonObj.size(); i++) {
                KlfCityEntity entity = new KlfCityEntity();
                JSONObject jo = jsonObj.getJSONObject(i);
                String key = jo.getString("city_key");
                entity.setCode(key);
                String name = jo.getString("city_name");
                entity.setName(name);
                String py = jo.getString("city_py");
                entity.setPy(py);
                cityList.add(entity);
                cityMap.put(key, entity);
            }
            if (cityList.size() > 1) {
                Collections.sort(cityList, new Comparator() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        String str1 = ((KlfCityEntity) o1).getPy();
                        String str2 = ((KlfCityEntity) o2).getPy();
                        return str1.compareTo(str2);
                    }
                });
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return cityList;
    }

    /**
     * 获取城市map
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @author yinchangming
     * @version [v1.0.0, 2015年11月10日]
     * @since [产品/模块版本](可选)
     */
    public static Map<String, KlfCityEntity> getCityMap() {
        if (cityMap == null) {
            //先获取cityList
            getCityList();
        }
        return cityMap;
    }

    /**
     * 通过cityKey获取城市对象
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param cityKey
     * @return
     * @author yinchangming
     * @version [v1.0.0, 2015年11月10日]
     * @since [产品/模块版本](可选)
     */
    public static KlfCityEntity getCityByCityKey(String cityKey) {
        if (cityMap == null) {
            getCityList();
        }
        KlfCityEntity cityObj = cityMap.get(cityKey);
        return cityObj;
    }
}
