package com.house365.web.util;

import com.google.common.base.Strings;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.cached.RedisUtilsInterface;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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 {

    private static final Logger logger = LoggerFactory.getLogger("CityUtil");

    public static final String CM_CITYS = "CITYSKEY";
    public static final String CM__NEW_CITYS = "CITYSNEWKEY";
    public static Map<String, KlfCityEntity> cityMap;
    public static List<KlfCityEntity> cityList;
    public static Map<String, KlfCityEntity> newCityMap;
    public static List<KlfCityEntity> newCityList;


    /**
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @author yinchangming
     * @version [v1.0.0, 2015年9月10日]
     * @since [产品/模块版本](可选)
     */
    @SuppressWarnings("unchecked")
    public static List<KlfCityEntity> getCityList() {
        cityMap = new HashMap<>();
        String urlString = "http://mopen.house365.com/api/?city=nj&client=tf&channl=app&v=6.0.3&api_key=iPhone&method=getCityList";

        StringBuilder builder = new StringBuilder(urlString);
        cityList = new ArrayList<>();
        Set<String> citySet = new HashSet<>();
        // 接口地址 获取JSON字符串
        try {
            String jsonStr;
            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(builder.toString());
                redisUtils.setValueExpireNew(CM_CITYS, jsonStr.trim(), TimeUnit.DAYS.toSeconds(1));
            } else {
                jsonStr = redisUtils.getValByKeyNew(CM_CITYS);
            }

            JSONArray jsonObj = JSONArray.fromObject(jsonStr);
            for (int i = 0; i < jsonObj.size(); i++) {
                KlfCityEntity entity = new KlfCityEntity();
                JSONObject jo = jsonObj.getJSONObject(i);
                String key = jo.getString("city_key");
                if (!citySet.contains(key)) {
                    citySet.add(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) {
            e.printStackTrace();
        }

        return cityList;
    }

    /**
     * 根据用户名获取新房城市接口并填充用户城市信息
     *
     * @return
     */
    public static List<KlfCityEntity> getCityListNew(String userName) {
        newCityMap = new HashMap<>(10);
        newCityList = new ArrayList<>();
        Set<String> citySet = new HashSet<>();
        try {
            // 新房接口地址 获取城市列表
            String url = "http://mobileadmin.house365.com/api.php";
            List<NameValuePair> queryParams = new ArrayList<>(10);
            queryParams.add(new BasicNameValuePair("method", "getUserCity"));
            queryParams.add(new BasicNameValuePair("username", userName));
            String data = HttpClientUtil.doGet(url, queryParams);
            JSONObject json = JSONObject.fromObject(data);
            String result = json.get("result").toString();
            if ("1".equals(result)) {
                JSONArray cityArrays = JSONArray.fromObject(json.get("city"));
                for (int i = 0; i < cityArrays.size(); i++) {
                    KlfCityEntity entity = new KlfCityEntity();
                    JSONObject jo = cityArrays.getJSONObject(i);
                    String key = jo.getString("city_key");
                    if (!citySet.contains(key)) {
                        citySet.add(key);
                        entity.setCode(key);
                        String name = jo.getString("city_name");
                        entity.setName(name);
                        entity.setPy("1");
                        newCityList.add(entity);
                        newCityMap.put(key, entity);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询用户城市信息失败", e);
        }
        return newCityList;
    }

    /**
     * 获取城市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;
    }

//    public static KlfCityEntity getCityByCityKeyNew(String cityKey) {
//        if (newCityMap == null) {
//            getCityListNew();
//        }
//        KlfCityEntity cityObj = newCityMap.get(cityKey);
//        return cityObj;
//    }
}
