/*
 * Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
 * FileName: NewHouseSelectTag.java
 * Author:   duhui
 * Date:     2015年1月23日 上午10:41:37
 * Description:     
 * History: 
 * <author>      <time>      <version>    <desc>
 * 修改人姓名                          修改时间                        版本号                                 描述
 */
package com.house365.tags;

import com.house365.tags.beans.NewHouseInfo;
import com.house365.tags.beans.NewHouseItem;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 公共标签 新房选择
 *
 * @author duhui
 * @version [v1.0.0, 2015年1月23日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class NewHouseSelectTag extends AbstractNewHouseSelectTag<NewHouseItem> {
    
    /**
     */
    private static final long serialVersionUID = 1L;
    
    /**
     * 城市ID
     */
    public static final String CITY_ID = "cityId";
    
    /**
     * 新房提供的接口地址
     */
    private static final String newHouseUrl = "http://newapi.house365.com/projects/all";
    
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NewHouseSelectTag.class);
    
    @Override
    protected String getDefaultName() {
        return "houseId";
    }

    @Override
    protected List<NewHouseItem> getList() {
        return getAllNewHouseItems();
    }

    @Override
    protected String getOptionLabel(NewHouseItem obj) {
        return obj.getHouseName() + " - " + obj.getHouseId();
    }

    private String getJsonData(String urlString) throws Exception {
        /**
         * 获取接口JSON字符串
         */
        String jsonStr = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                jsonStr += line;
            }
            in.close();
        } catch (Exception e) {
            LOGGER.error("PHP接口异常：获取新房接口数据失败！");
        }
        return jsonStr;
    }

    private List<NewHouseItem> getAllNewHouseItems() {
       
        try {
            // 取得session里城市参数
            HttpSession session = pageContext.getSession();
            String city = (String) session.getAttribute(CITY_ID);
            // 开发方便
            if(null == city || "".equals(city)) {
                city = "wx";
            }
            // 接口地址 获取JSON字符串
            //String jsonStr = getJsonData(newHouseUrl + "?city=" + city);
            //System.out.println(newHouseUrl + "?city=" + city);
            
            String jsonStr = "{\"NewHouse\":[{\"houseId\":\"CN00001001\",\"houseName\":\"林景雅苑\",\"cityId\":\"210000\",\"cityName\":\"南京\",\"areaId\":\"210018\",\"areaName\":\"玄武区\",\"price\":\"1000\"}]}";
            //String jsonStr = "{\"data\":[{\"id\":\"1\",\"prj_id\":\"1\",\"channel\":\"1\",\"itemname\":\"name,\",\"price\":\"6200\",\"price_more\":\"dsdsd\",\"city_id\":\"1\",\"dist_id\":\"2\",\"dist_name\":\"7667\",\"city\":\"nj\"}],\"error\":false,\"status\":200}";
            // 解析JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            NewHouseInfo newHouseInfo = objectMapper.readValue(jsonStr, NewHouseInfo.class);
            return newHouseInfo.getNewHouse();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("PHP接口异常：解析PHP接口提供JSON字符串异常！");
        }
        return null;
    }
    
}
