package com.house365.ws.util;

import com.google.common.base.Strings;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.SpringContextUtil;
import com.house365.ws.cached.RedisUtilsInterface;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 数据中心房价评估接口
 */
public class DataCenterAssessUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    private static final String URL = MemoryPropertyPlaceholderConfigurer.getContextProperty("dataCenterApi");
    private static final String GET_CITYPRICE_URL = URL + "sell-price/price/get_city_price";
    private static final String GET_ALLDISTRICTPRICE_URL = URL + "sell-price/price/get_all_district_price";
    //四、	房价地图接口 提交：站点名称（如nj） 返回：站点下属所有区域名称、坐标、均价、环比数据
    private static final String GET_ALLDISTRICTPRICE_DETAIL_URL = URL + "sell-price/price/get_all_district_detail";
    private static final String GET_GETDISTRICTPRICE_URL = URL + "sell-price/price/get_district_price";
    private static final String GET_GETDISTRICTALLSTREETPRICE_URL = URL + "sell-price/price/get_district_all_street_price";
    private static final String GET_GETSTREETPRICE_URL = URL + "sell-price/price/get_street_price";
    private static final String GET_WORDSEARCH_URL = URL + "word-search/search";
    private static final String GET_CALCULATEPRICE_URL = URL + "sell-price/price/calculate_price";
    private static final String GET_BLOCKBRICE_URL = URL + "sell-price/price/get_block_price";
    private static final String GET_STREETTOP_URL = URL + "sell-price/price/get_street_top";
    private static final String GET_BLOCK_BYKEYWORD_URL = URL + "sell-price/price/get_block_by_keyword";
    //五、	周边房价搜索
    private static final String GET_BLOCK_BY_DISTANCE = URL + "sell-price/price/get_block_by_distance";

    /**
     * 9.根据城市名、小区id、数量，随机获取二手房房源n条
     */
    private static final String URL_GET_BLOCK_SELL = URL + "sell-price/price/get_block_sell";
    /**
     * 10.根据城市名、小区id、数量，随机获取租房房源n条
     */
    private static final String URL_GET_BLOCK_RENT = URL + "sell-price/price/get_block_rent";
    /**
     * 11.根据城市名、区域、数量n，获取该区域所有小区中环比上涨前n名
     */
    private static final String URL_GET_DISTRICT_I_TOP = URL + "sell-price/price/get_district_i_top";
    /**
     * 12.根据城市名、区域、数量n，获取该区域所有小区中环比下跌前n名
     */
    private static final String URL_GET_DISTRICT_D_TOP = URL + "sell-price/price/get_district_d_top";
    /**
     * 13.根据城市名、关键词，获取可估价的二手房小区列表
     */
    private static final String URL_GET_BLOCK_LIST_FOR_CALCULATE = URL + "sell-price/price/get_block_list_for_calculate";

    /**
     * 1.根据城市名、年月，获取该城市二手房月均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_city_price?city=nj&month=201509&num=2
     *
     * @param city  城市名 nj
     * @param month 年月 201512
     * @param num   自month起向后共取几个月 2
     * @return json city——城市名 month——月份 price——均价 hb——环比
     */
    public static JSONArray getCityPrice(final String city, final String month, final String num) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month)) {
            throw new IllegalServiceParameterException("city or month is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));
        if (!Strings.isNullOrEmpty(num)) {
            pairs.add(new BasicNameValuePair("num", num));
        }

        return getResponse(GET_CITYPRICE_URL, pairs);
    }

    /**
     * 2.根据城市名、月份，获取该城市所有区域的均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_all_district_price?city=nj&month=201509&num=2
     *
     * @param city  城市名 nj
     * @param month 年月 201512
     * @return district——区属 month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getAllDistrictPrice(final String city, final String month) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month)) {
            throw new IllegalServiceParameterException("city or month is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));

        return getResponse(GET_ALLDISTRICTPRICE_URL, pairs);
    }

    /**
     * 四、	房价地图接口
     * http://xxxapi.house365.com/sell-price/price/get_all_district_detail?city=nj
     *
     * @param city 站点名称（如nj）
     * @return 返回：站点下属所有区域名称、坐标、均价、环比数据。
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getAllDistrictPriceDetail(final String city) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city)) {
            throw new IllegalServiceParameterException("city is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        return getResponse(GET_ALLDISTRICTPRICE_DETAIL_URL, pairs);
    }


    /**
     * 3.根据城市名、区域、月份，获取该区域的均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_district_price?city=nj&district=%E6%B5%A6%E5%8F%A3%E5%8C%BA&month=201509&num=2
     *
     * @param city     城市名 nj
     * @param month    年月 201512
     * @param district 区域名称 浦口区
     * @param num      自month起向后共取几个月 2
     * @return district——区属 month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getDistrictPrice(
            final String city, final String month, final String district, final String num
    ) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month) || Strings.isNullOrEmpty(district)) {
            throw new IllegalServiceParameterException("city or month or district is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("district", district));
        //        try {
        //            pairs.add(new BasicNameValuePair("district", URLEncoder.encode(district, "GBK")));
        //        } catch (UnsupportedEncodingException e) {
        //            throw new IllegalServiceParameterException(e.getMessage());
        //        }
        if (!Strings.isNullOrEmpty(num)) {
            pairs.add(new BasicNameValuePair("num", num));
        }

        return getResponse(GET_GETDISTRICTPRICE_URL, pairs);
    }

    /**
     * 4.根据城市名、区域、月份，获取该区域中所有版块的均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_district_all_street_price?city=nj&district=%E5%BB%BA%E9%82%BA%E5%8C%BA&month=201508
     *
     * @param city     城市名 nj
     * @param month    年月 201512
     * @param district 区域名称 建邺区
     * @return streetid——版块ID month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getDistrictAllStreetPrice(final String city, final String month, final String district) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month) || Strings.isNullOrEmpty(district)) {
            throw new IllegalServiceParameterException("city or month or district is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("district", district));

        return getResponse(GET_GETDISTRICTALLSTREETPRICE_URL, pairs);
    }

    /**
     * 5.根据城市名、版块id、月份，获取该版块的均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_street_price?city=nj&streetid=174&month=201508
     *
     * @param city     城市名 nj
     * @param month    年月 201512
     * @param streetId 区域名称 建邺区
     * @param num      自month起取几个月 2
     * @return streetid——版块ID month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getStreetPrice(
            final String city, final String month, final String streetId, final String num
    ) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month) || Strings.isNullOrEmpty(streetId)) {
            throw new IllegalServiceParameterException("city or month or district is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("streetid", streetId));
        if (!Strings.isNullOrEmpty(num)) {
            pairs.add(new BasicNameValuePair("num", num));
        }

        return getResponse(GET_GETSTREETPRICE_URL, pairs);
    }

    /**
     * 6.根据城市名、关键词，获取匹配的新房、二手房小区列表
     * http://xxxapi.house365.com/word-search/search?city=nj&keyword=%E4%B8%87%E7%A7%91%E9%87%91%E5%9F%9F%E8%93%9D%E6%B9%BE
     *
     * @param city    城市名 nj
     * @param keyword 关键词 五台花园
     * @return id——小区或楼盘ID  name——小区或楼盘名 type——类型：1=新房 2=二手房
     * @throws IllegalServiceParameterException
     */
    public static JSONArray wordSearch(final String city, final String keyword) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(keyword)) {
            throw new IllegalServiceParameterException("city or keyword is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("keyword", keyword));

        return getResponse(GET_WORDSEARCH_URL, pairs);
    }

    /**
     * 7.根据城市名、小区id、各项房屋属性，评估房价
     * http://xxxapi.house365.com/sell-price/price/calculate_price?city=nj&blockid=1&forward=南&room=3&buildarea=60
     *
     * @param city       城市名 nj
     * @param blockId    小区id 1
     * @param forward    朝向 南
     * @param room       房间数 2
     * @param buildArea  面积 90.0
     * @param floor      楼层 2
     * @param totalFloor 总楼层 5
     * @return price——总价（万元）averprice——单价（元）
     * @throws IllegalServiceParameterException
     */
    public static JSONObject calculatePrice(
            final String city, final String blockId, final String forward, final String room, final String buildArea,
            final String floor, final String totalFloor
    ) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(blockId) || Strings.isNullOrEmpty(buildArea)) {
            throw new IllegalServiceParameterException("city or keyword is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("blockid", blockId));
        if (!Strings.isNullOrEmpty(forward)) {
            pairs.add(new BasicNameValuePair("forward", forward));
        }
        if (!Strings.isNullOrEmpty(room)) {
            pairs.add(new BasicNameValuePair("room", room));
        }
        pairs.add(new BasicNameValuePair("buildarea", buildArea));
        if (!Strings.isNullOrEmpty(floor)) {
            pairs.add(new BasicNameValuePair("floor", floor));
        }
        if (!Strings.isNullOrEmpty(totalFloor)) {
            pairs.add(new BasicNameValuePair("totalfloor", totalFloor));
        }

        JSONObject jsonObject = new JSONObject();
        try {
            String jsonResult = getResponseStr(GET_CALCULATEPRICE_URL, pairs);

            if (StringUtils.isNotBlank(jsonResult)) {
                jsonObject = JSONObject.fromObject(jsonResult);

                if (jsonObject == null || jsonObject.get("price") == null || jsonObject.get("averprice") == null) {
                    LOGGER.warn("calculatePrice result is empty!!!");
                }

            } else {
                LOGGER.warn("calculatePrice result is empty!!!");
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new IllegalServiceParameterException(e.getMessage());
        }

        return jsonObject;
    }

    /**
     * 8.根据城市名、小区id、月份，获取小区二手房均价、环比数据
     * http://xxxapi.house365.com/sell-price/price/get_block_price?city=nj&blockid=1&month=201508&num=2
     *
     * @param city    城市名 nj
     * @param month   年月 201512
     * @param blockId 区域名称 建邺区
     * @param num     自month起取几个月 2
     * @return blockid——小区id month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONArray getBlockPrice(
            final String city, final String month, final String blockId, final String num
    ) throws IllegalServiceParameterException {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(month) || Strings.isNullOrEmpty(blockId)) {
            throw new IllegalServiceParameterException("city or month or blockid is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("blockid", blockId));
        if (!Strings.isNullOrEmpty(num)) {
            pairs.add(new BasicNameValuePair("num", num));
        }

        return getResponse((String) GET_BLOCKBRICE_URL, (List<NameValuePair>) pairs);
    }

    private static JSONArray getResponse(final String url, List<NameValuePair> pairs) throws IllegalServiceParameterException {
        String response;
        JSONArray jsonArray = new JSONArray();

        try {
            response = getResponseStr(url, pairs);
        } catch (IOException e) {
            throw new IllegalServiceParameterException(e.getMessage());
        }

        try {
            if (!Strings.isNullOrEmpty(response)) {
                //float类型转换时精度丢失，处理为字符串
                Pattern pattern = Pattern.compile("[x-y]\":\\d+\\.{0,1}\\d+[\\,,\\}]");
                Matcher matcher = pattern.matcher(response);
                while (matcher.find()) {
                    String gr = matcher.group();
                    if (gr.contains(",")) {
                        response = response.replaceAll(gr, gr.replaceAll(":", ":\"").replaceAll(",", "") + "\",");
                    } else if (gr.contains("}")) {
                        response = response.replaceAll(gr, gr.replaceAll(":", ":\"").replaceAll("}", "") + "\"}");
                    }
                }

                if (StringUtils.isNotBlank(response)) {
                    jsonArray = JSONArray.fromObject(response.trim());
                    return jsonArray;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return JSONArray.fromObject(response.trim());
        }

        return jsonArray;
    }

    private static StringBuilder getCacheKey(String url, List<NameValuePair> pairs) {
        String urlKey = url.lastIndexOf("/") > -1 ? url.substring(url.lastIndexOf("/") + 1) : "";
        StringBuilder cacheKey = new StringBuilder(Strings.isNullOrEmpty(urlKey) ? "" : urlKey);
        for (NameValuePair pair : pairs) {
            cacheKey.append(Strings.isNullOrEmpty(pair.getName()) ? "" : pair.getName()).append(
                    Strings.isNullOrEmpty(pair.getValue()) ? "" : pair.getValue());
        }
        return cacheKey;
    }

    private static String getResponseStr(String url, List<NameValuePair> pairs) throws IOException {
        String response;
        StringBuilder cacheKey = getCacheKey(url, pairs);
        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

        if (Strings.isNullOrEmpty(cacheKey.toString()) || redisUtils.getValByKeyNew(
                cacheKey.toString()) == null || Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(cacheKey.toString())) || "null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(cacheKey.toString()))) {
            long beginTime = System.currentTimeMillis();
            response = HttpClientUtil.doGet(url, pairs, "");
            if (LOGGER.isInfoEnabled() && System.currentTimeMillis() - beginTime > 3000) {
                LOGGER.info("call dataCenter api : url [{}] , use [{}] ms", url,
                        System.currentTimeMillis() - beginTime);
            }

            redisUtils.setValueExpireNew(cacheKey.toString(), response, 6, TimeUnit.HOURS);
        } else {
            response = redisUtils.getValByKeyNew(cacheKey.toString()).trim();
        }
        return response;
    }

    /**
     * 9.根据城市名、小区id、数量，随机获取二手房房源n条
     *
     * @param city    string  是  城市名 	nj
     * @param blockid int     是  小区id  	1
     * @param num     int		是  房源条数	2
     * @return
     */
    public static JSONObject getBlockSell(String city, String blockid, int num) throws Exception {
        StringBuffer buffer = new StringBuffer(URL_GET_BLOCK_SELL);
        buffer.append("?city=" + city);
        buffer.append("&blockid=" + blockid);
        buffer.append("&num=" + num);

        final String cacheKey = "get_block_sell" + "_" + city + "_" + blockid + "_" + num;
        String response;
        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

        if (redisUtils.getValByKeyNew(cacheKey) == null || Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(cacheKey)) || "null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(cacheKey))) {
            response = HttpClientUtil.getJsonData(buffer.toString());
            redisUtils.setValueExpireNew(cacheKey, response, 6, TimeUnit.HOURS);
        } else {
            response = redisUtils.getValByKeyNew(cacheKey).trim();
        }

        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(response)) {
            jsonObject = JSONObject.fromObject(response);
        }
        return jsonObject;
    }

    /**
     * 10.根据城市名、小区id、数量，随机获取租房房源n条
     *
     * @param city    string  是  城市名 	nj
     * @param blockid int     是  小区id  	1
     * @param num     int		是  房源条数	2
     * @return
     */
    public static JSONObject getBlockRent(String city, String blockid, int num) throws Exception {
        StringBuffer buffer = new StringBuffer(URL_GET_BLOCK_RENT);
        buffer.append("?city=" + city);
        buffer.append("&blockid=" + blockid);
        buffer.append("&num=" + num);


        final String cacheKey = "get_block_rent" + "_" + city + "_" + blockid + "_" + num;
        String response;
        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

        if (redisUtils.getValByKeyNew(cacheKey) == null || Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(cacheKey)) || "null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(cacheKey))) {
            response = HttpClientUtil.getJsonData(buffer.toString());
            redisUtils.setValueExpireNew(cacheKey, response, 6, TimeUnit.HOURS);
        } else {
            response = redisUtils.getValByKeyNew(cacheKey).trim();
        }

        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(response)) {
            jsonObject = JSONObject.fromObject(response);
        }
        return jsonObject;
    }

    /**
     * 11.根据城市名、区域、数量n，获取该区域所有小区中环比上涨前n名
     *
     * @param city     string  是  城市名 	nj
     * @param district String  是  行政区	         建邺区
     * @param month    String  是  月份		201511
     * @param num      int	       是  前n名		2
     * @return
     */
    public static JSONArray getDistrictITop(String city, String district, String month, int num) throws Exception {
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("district", district));
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("num", String.valueOf(num)));

        String jsonResult = getResponseStr(URL_GET_DISTRICT_I_TOP, pairs);
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isNotBlank(jsonResult)) {
            jsonArray = JSONArray.fromObject(jsonResult);
        }
        return jsonArray;
    }

    /**
     * 12.根据城市名、区域、数量n，获取该区域所有小区中环比下跌前n名
     *
     * @param city     string  是  城市名 	nj
     * @param district String  是  行政区	         建邺区
     * @param month    String  是  月份		201511
     * @param num      int		是  前n名		2
     * @return
     */
    public static JSONArray getDistrictDTop(String city, String district, String month, int num) throws Exception {
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("district", district));
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("num", String.valueOf(num)));

        String jsonResult = getResponseStr(URL_GET_DISTRICT_D_TOP, pairs);
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isNotBlank(jsonResult)) {
            jsonArray = JSONArray.fromObject(jsonResult);
        }
        return jsonArray;
    }

    /**
     * 13.根据城市名、关键词，获取可估价的二手房小区列表
     *
     * @param city    string  是  城市名 	nj
     * @param keyword String  是  关键词		五台
     * @return
     */
    public static JSONArray getBlockListForCalculate(String city, String keyword) throws Exception {
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("keyword", keyword));

        String jsonResult = getResponseStr(URL_GET_BLOCK_LIST_FOR_CALCULATE, pairs);
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isNotBlank(jsonResult)) {
            jsonArray = JSONArray.fromObject(jsonResult);
        }
        return jsonArray;
    }

    /**
     * 20.根据城市名、版块id、月份，获取版块 上涨、下跌前N名小区
     * http://xxxapi.house365.com/sell-price/price/get_street_top?city=nj&streetid=174&num=2&month=201511
     *
     * @param city     城市名 nj
     * @param streetId 版块id 147
     * @param month    年月 201512
     * @param num      区域名称 建邺区
     * @return streetid——版块ID month——月份 price——均价 hb——环比
     * @throws IllegalServiceParameterException
     */
    public static JSONObject getStreetTop(
            final String city, final String streetId, final String month, final String num
    ) throws Exception {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(streetId) || Strings.isNullOrEmpty(month)) {
            throw new IllegalServiceParameterException("city or streetId or month is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("month", month));
        pairs.add(new BasicNameValuePair("streetid", streetId));
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("num", num));

        JSONObject jsonObject;
        try {
            String jsonResult = getResponseStr(GET_STREETTOP_URL, pairs);
            if (StringUtils.isNotBlank(jsonResult)) {
                jsonObject = JSONObject.fromObject(jsonResult);
            } else {
                throw new Exception("getStreetTop result is empty!!!");
            }

            if (jsonObject == null) {
                throw new Exception("getStreetTop result is empty!!!");
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new IllegalServiceParameterException(e.getMessage());
        }

        return jsonObject;

    }

    /**
     * 搜索关键词匹配的小区名称、ID、所属板块名称、上月均价、环比
     *
     * @param city
     * @param keyword
     * @return
     * @throws Exception
     */
    public static JSONArray getBlockByKeyword(
            final String city, final String keyword
    ) throws Exception {
        if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(keyword)) {
            throw new IllegalServiceParameterException("city or keyword is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("keyword", keyword));

        JSONArray jsonArray;
        try {
            String jsonResult = getResponseStr(GET_BLOCK_BYKEYWORD_URL, pairs);
            if (StringUtils.isNotBlank(jsonResult)) {
                jsonArray = JSONArray.fromObject(jsonResult);
            } else {
                throw new Exception("getBlockByKeyword result is empty!!!");
            }

            if (jsonArray == null) {
                throw new Exception("getBlockByKeyword result is empty!!!");
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new IllegalServiceParameterException(e.getMessage());
        }

        return jsonArray;
    }

    /**
     * 五、	周边房价搜索
     *
     * @param city  城市拼音首字母
     * @param x     经度
     * @param y     纬度
     * @param range 范围(米)
     * @return
     * @throws Exception
     */
    public static JSONArray getBlockByDistance(final String city, final Double x, final Double y, final Integer range ,final String mapType ) throws Exception {
        if (Strings.isNullOrEmpty(city) || x == null || y == null || range == null) {
            throw new IllegalServiceParameterException("city or other is empty!!! ");
        }
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("city", city));
        pairs.add(new BasicNameValuePair("x", String.valueOf(x)));
        pairs.add(new BasicNameValuePair("y", String.valueOf(y)));
        pairs.add(new BasicNameValuePair("range", String.valueOf(range)));

        pairs.add(new BasicNameValuePair("mapType", String.valueOf(mapType)));

        JSONArray jsonArray;
        try {
            String jsonResult = getResponseStr(GET_BLOCK_BY_DISTANCE, pairs);
            if (StringUtils.isNotBlank(jsonResult)) {
                jsonArray = JSONArray.fromObject(jsonResult);
            } else {
                throw new Exception("getBlockByDistance result is empty!!!");
            }

            if (jsonArray == null) {
                throw new Exception("getBlockByDistance result is empty!!!");
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new IllegalServiceParameterException(e.getMessage());
        }

        return jsonArray;
    }


    public static void main(String[] args) {
        try {

            //            System.out.println(getCityPrice("nj","201512","2"));
            //            System.out.println(getAllDistrictPrice("nj", "201512"));
            //            System.out.println(getDistrictPrice("nj", "201512", "浦口区", "2"));
            //            System.out.println(getDistrictAllStreetPrice("nj", "201512", "建邺区"));
            //            System.out.println(wordSearch("nj", "花园"));
            //            System.out.println(calculatePrice("nj", "1", "南", "3", "90.0"));
            //            System.out.println(getBlockPrice("nj", "201512", "1", "2"));
            //            JSONObject calculate = calculatePrice("nj", "1", "南", "3", "60", "", "");
            //            if (calculate != null && calculate.get("price") != null && calculate.get("averprice") != null) {
            //
            //                System.out.println(calculate);
            //            }

            //            System.out.println(getStreetTop("nj", "174", "201512", "2"));
            //
            //            System.out.println("\n---- 请输入要测试API序号： ----");
            //        	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            //        	try {
            //        		int input = Integer.parseInt(bufferedReader.readLine());
            //        		switch (input) {
            //    			case 9:
            //    	    		// 9.根据城市名、小区id、数量，随机获取二手房房源n条
            //    	    		JSONObject result9 = DataCenterAssessUtil.getBlockSell("nj", "1", 10);
            //    				System.out.println(result9);
            //    				main(args);
            //    				break;
            //
            //    			case 10:
            //    				// 10.根据城市名、小区id、数量，随机获取租房房源n条
            //    	    		JSONObject result10 = DataCenterAssessUtil.getBlockRent("nj", "1", 10);
            //    				System.out.println(result10);
            //    				main(args);
            //    				break;
            //
            //    			case 11:
            //    				// 11.根据城市名、区域、数量n，获取该区域所有小区中环比上涨前n名
            //    				JSONArray result11 = DataCenterAssessUtil.getDistrictITop("nj", "建邺区", "201511", 10);
            //    				System.out.println(result11);
            //    				main(args);
            //    				break;
            //
            //    			case 12:
            //    				// 12.根据城市名、区域、数量n，获取该区域所有小区中环比上涨前n名
            //    				JSONArray result12 = DataCenterAssessUtil.getDistrictDTop("nj", "建邺区", "201511", 10);
            //    				System.out.println(result12);
            //    				main(args);
            //    				break;
            //
            //    			case 13:
            //    				// 13.根据城市名、关键词，获取可估价的二手房小区列表
            //    				JSONArray result13 = DataCenterAssessUtil.getBlockListForCalculate("nj", "五台");
            //    				System.out.println(result13);
            //    				main(args);
            //    				break;
            //
            //    			default:
            //    				break;
            //    			}
            //    		} catch (IOException e1) {
            //    			e1.printStackTrace();
            //    		} catch (Exception e) {
            //    			e.printStackTrace();
            //    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
