<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
header("Content-type: text/html; charset=gb2312"); 
/**
 * ajax Class
 *
 * ajax管理
 *
 * @package     zsb
 * @subpackage      Controllers
 * @category        Controllers
 * @author      sun
 */
class Ajax extends MY_Controller {
    /**
    * 解析函数
    *
    * @access public
    * @return void
    */
    public function __construct()
    {   
        parent::__construct();
        if(!$this->input->is_ajax_request())
        {
           // echo '非法请求';
            //die();
        }
        $this->load->model('ajax_model');
		$this->load->helper('common_string');
    }
    
    //@todo
    public function index()
    {
        echo '验证字段';
    }
    
    /**
     * 以小区id编号获取基本信息
     */
    public function find_block_detail()
    {
        $this->load->model('block_model');
        $id = $this->input->get('id');
        $block = $this->block_model->base_info_by_id($id);
        echo $this->ajax_model->array_to_json($block);
    }
    
    /**
     * 小区名称模糊获取小区列表信息
     */
    public function find_like_block_list()
    {
        $this->load->model('block_model');
        $blockname = $this->input->post('blockname');
        $infotype = $this->input->post('infotype');
        $blockname = trim(iconv('UTF-8', 'gbk', rawurldecode($blockname)));
        //物业类型为住宅不能发待审核小区
        if( empty($infotype) || $infotype == 1 ){
            $block_list = $this->block_model->auto_blockname($blockname);
        }else{
            $block_list = $this->block_model->auto_blockname($blockname,20,array(0,1,2));
        }
        echo $this->ajax_model->array_to_json($block_list);
    }
    
    /**
     * 获取区属下的板块列表
     */
    public function find_street_list()
    {
        $this->load->model('street_model');
        $district = $this->input->get('district');
        $district = iconv("utf-8","gb2312", urldecode($district));
        echo $this->street_model->street_html_by_district($district);
    }
    
    /**
     * 添加临时小区
     */
    public function add_temp_block()
    {
        $blockname = iconv("utf-8","gb2312",$this->input->get('tcblockname'));
        $blockaddress = iconv("utf-8","gb2312",$this->input->get('tcaddress'));
        $district = iconv("utf-8","gb2312",$this->input->get('tcdistrict'));
        $streetid = $this->input->get('tcstreetid');
        $this->load->model('block_model');
        $result = $this->block_model->add_temp_block($blockname, $blockaddress, 
                $district, $streetid, $this->user_arr);
        echo $this->ajax_model->array_to_json($result);
    }
    
    /**
     * 判断房源模板是否已经存在
     */
    public function exist_templatename()
    {
        $moudle = $this->input->get('module');
        $templatename = mb_convert_encoding(urldecode(
                $this->input->get('templatename')),"gb2312","utf-8");
        $this->load->model('house_template_model');
        $num = $this->house_template_model->find_count_by_name($templatename, 
                $moudle, $this->user_arr['uid']);
        // 1 已存在相同的模板名 0 没有
        echo $num > 0 ? 1 : 0;
    }
    
    /**
     * 根据房源模板编号获取详细信息
     */
    public function find_module_detail()
    {
        $id = $this->input->get('id');
        $this->load->model('house_template_model');
        $detail = $this->house_template_model->find_by_id($id, $this->user_arr['uid']);
        $this->load->model('block_model');
        $block_detail = $this->block_model->base_info_by_id($detail['block_id']);
        $detail['district'] = $block_detail['district'];
        $detail['street'] = $block_detail['streetname'];
        $detail['address'] = $block_detail['address'];
        $detail['averprice'] = $block_detail['averprice'];
        $detail['esta_block'] = $block_detail['esta_block'];
        $detail['url_block'] = $block_detail['url_block'];
        echo $this->ajax_model->array_to_json($detail);
    }
    
    /**
     * 不同物业类型获取相应的补充信息
     */
    public function find_house_add_ext()
    {
        $data = array();
        $infotype = $this->input->get('infotype');
        $house_id = $this->input->get('house_id');
        $tbl = $this->input->get('tbl');
        $data['infotype'] = $infotype;
        $data['house'] = $this->config->item('house');
        $broker_info =$this->broker_model->get_broker_info();
        $data['real_status'] = $broker_info['real_status'];

        $packageId = $this->user_arr['package_id'];
        $this->load->model('real_house_model');
        $realNumLimit =$this->broker_model->get_realnum_by_packageid($packageId);
        $data['realNumLimit'] = $realNumLimit;  //套餐可发真房源数量
        $data['realHouseNum']= $this->real_house_model->getUidRealHouseNum($this->user_arr['uid']); //经纪人 已发真房源数量

        $data['balance']= $this->real_house_model->getBrokerRealHouseMoney($this->user_arr['uid']);//经纪人账号余额
        if($house_id){
            $this->load->model('sell_model');
            $data['house_detail'] = $this->sell_model->find_by_uid_id($this->user_arr['uid'], $house_id);
        }
        $data['house_detail']['realNumLimit'] =$data['realNumLimit'] ;
        $data['house_detail']['realHouseNum'] =$data['realHouseNum'] ;

        $data['rent_allow_release'] = 1;
        if(GB_CITY == 'nj'){
            $this->load->model('broker_model');
            $rent_allow_release = $this->broker_model->rent_allow_release($infotype);
            $data['rent_allow_release'] = $rent_allow_release;
            $data['rent_allow_release_alert'] = $this->config->item('rent_allow_release');
        }
        echo $this->load->view($tbl . '_add_ext', $data, TRUE);
    }
    
    /**
     * 获取小区图库
     */
    public function find_block_img()
    {

        $blockname = iconv('UTF-8','GBK',urldecode($this->input->get('blockname')));

        $room = intval($this->input->get('room'));
        $hall = intval($this->input->get('hall'));
        $page = intval($this->input->get('page'));
        $page = intval($page)?intval($page):1;
        $perpage = 10;
        $offset =($page-1)*$perpage;
        $num = 0;
        $this->load->model('block_model');

        if(!($room == 0 && $hall == 0))
        {

            //推荐图片只显示365图库上线以后入库的图片
            $this->block_model->set_select_fields(array('bi.id','bi.bi_img'));
            $imgs = $this->block_model->find_room_img($blockname, $room, $hall, $perpage, $offset);

            $num = $this->block_model->find_room_img_count($blockname, $room, $hall);
            $sort = 9;//户型图 0
        }
        else
        {

            //推荐图片只显示365图库上线以后入库的图片
            $this->block_model->set_select_fields(array('bi.id','bi.bi_img'));
            $imgs = $this->block_model->find_outdoor_img($blockname, $perpage, $offset);
            $num = $this->block_model->find_outdoor_img_count($blockname);
            $sort = 10;//外景图 1
        }
        $pages = ceil($num/$perpage);  //计算总页数
        if($num > 0)
        {
            $ss = '';
            foreach($imgs as $img)
			{
                //$img['big_img'] = str_replace("/thumb","",$img['bi_img']);
                $img['big_img'] = pic_thumbTobig($img['bi_img']);
                $ss .= '<div class="item"><div class="itemInner">
                        <div class="pic"><img alt="" id="' . $img['id'] .'" src="'
                        . $img['bi_img'] . '" width="130" height="100" num="' . $img['id'] 
                        . '" /></div><div class="btn" title="选中"></div><a href="' 
                        . $img['big_img'] . '" target="_balnk" title="查看大图" class="bigPicLin">查看大图</a>
                    </div>
                </div>';
            }
            $pagenavi = zsb_pagenavi_ajax($page,$pages, 'getBlockImg');
            if(!($room == 0 && $hall == 0))
            {
                $ss .= '<input type="hidden" name="pic_num1" value="' . $num 
                        . '" id="pic_num1"></div>';
            }
            else
            {
                $ss .= '<input type="hidden" name="pic_num" value="' . $num 
                        . '" id="pic_num"></div>';
            }
            if($pagenavi){
                $ss .= "<div class='picPreviewPag clear'>";
                $ss .= $pagenavi;
                $ss .= "</div>";
            }
            echo $ss;
        }
    }
    
    //房源特色
    public function find_housefeature() 
    {
        $tbl = $this->input->get('tbl');
        $infotype = $this->input->get('infotype');
        $this->load->model('house_feature');
        $arr = $this->house_feature->find_feature($tbl, $infotype);
        $ss = '';
		if(is_array($arr) && !empty($arr))
	    {
			foreach($arr as $k => $val)
			{
                $ss .= '<p num="' . $k . '" class="addTagInner radius4">'
                . $val . '</p>';
			}
		}
        echo $ss;
    }

	 //房源特色
    public function find_infotype_rent() 
    {
        $infotype = $this->input->get('infotype');
		if(empty($infotype))
		{
			$infotype=1;
		}
        echo $infotype;
    }

	//房源特色
    public function find_housefeature_test() 
    {
        $tbl = $this->input->get('tbl');
        $infotype = $this->input->get('infotype');
        $this->load->model('house_feature_test');
        $arr = $this->house_feature_test->find_feature($tbl, $infotype);
        $ss = '';
		if(is_array($arr) && !empty($arr))
	    {
			foreach($arr as $k => $val)
			{
                $ss .= '<p num="' . $k . '" class="addTagInner radius4">'
                . $val . '</p>';
			}
		}
        echo $ss;
    }
    
    /**
    * 获取根据房源编号获取经纪人某条房二手房房源的信息
    * 
    * @access private
    * @param  int $uid 经纪人账号
    * @param  int $rowid 房源编号
    * @param  array $select_fields 需要查询的字段
    * @return array 房源信息数组
    */
    private function _get_sellinfo_by_id( $uid , $rowid ,$select_fields = array())
    {   
        $sellinfo = array();
        
        //经纪人账号编号
        $uid = intval( $uid );
        
        //房源编号
        $rowid = intval( $rowid );

        //加载出售model类
        $this->load->model('sell_model');
        
        //设置查询字段
        if( is_array( $select_fields ) && !empty( $select_fields ) )
        {
            $this->sell_model->set_select_fields( $select_fields );
        }
        
        //查询房源信息
        $sellinfo = $this->sell_model->find_by_uid_id( $uid , $rowid );
        
        return  $sellinfo;
    }
    
	
    /**
    * 获取根据房源编号获取经纪人某条房租房房源的信息
    * 
    * @access private
    * @param  int $uid 经纪人账号
    * @param  int $rowid 房源编号
    * @param  array $select_fields 需要查询的字段
    * @return array 房源信息数组
    */
    private function _get_rentinfo_by_id( $uid , $rowid , $select_fields = array())
    {   
        $rentinfo = array();
        
        //经纪人账号编号
        $uid = intval( $uid );
        
        //房源编号
        $rowid = intval( $rowid );
        
        //加载出售model类
        $this->load->model('rent_model');
        
        //设置查询字段
        if(is_array($select_fields) && !empty($select_fields))
        {
            $this->rent_model->set_select_fields($select_fields);
        }
        
        //查询房源信息
        $rentinfo = $this->rent_model->find_by_uid_id( $uid , $rowid );
        
        return  $rentinfo;
    }
    
    
   /**
    * 根据根据求购信息编号获取符合条件的房源
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    public function get_houselist_by_wantid()
    {   
        $page = $this->input->get('page');
        $want_id = $this->input->get('want_id');
       
        //获取求购信息
        $demand_info = array();
        $this->load->model('buy_demand_model');
        
        //设置查询字段
        $select_field = array('id','street','street1','street2','buildarea1'
                    ,'buildarea2','price1','price2','buildyear1','buildyear1');
        $this->buy_demand_model->set_search_fields($select_field);
        
        //获取求购信息
        $this->buy_demand_model->set_id($want_id);
        $demand_info = $this->buy_demand_model->get_info_by_id();
        
        //根据需求信息，查询该经纪人符合条件的房源
        if(is_array($demand_info) && !empty($demand_info))
        {   
            //经纪人编号
            $uid = $this->user_arr['uid'];
            $cond_where = "uid = '".$uid."' AND esta = 1 AND infofrom = '5' ";
            
            $street_ids = '';
            if( isset ($demand_info['street']) && $demand_info['street'] > 0 )
            {
                $street_ids .= $demand_info['street'];
            }

            if( isset ($demand_info['street1']) && $demand_info['street1'] > 0 )
            {
                $street_ids .= ','.$demand_info['street1'];
            }

            if( isset ($demand_info['street2']) && $demand_info['street2'] > 0 )
            {
                $street_ids .= ','.$demand_info['street2'];
            }
            $cond_where .= " AND streetid IN(".$street_ids.")";
            
            
            //面积帅选条件
            if( isset ($demand_info['buildarea1']) && isset ($demand_info['buildarea2']) 
                && $demand_info['buildarea1'] >= 0 && $demand_info['buildarea2'] > 0 )
            {
                $cond_where .= " AND buildarea >= ".$demand_info['buildarea1']." "
                        . "AND buildarea <= ".$demand_info['buildarea2'] ;
            }

            //价格筛选条件
            if( isset ($demand_info['price1']) && isset ($demand_info['price2']) 
                && $demand_info['price1'] >= 0 && $demand_info['price2'] > 0 )
            {
                $cond_where .= " AND price >= ".$demand_info['price1']." AND price <= ".$demand_info['price2'] ;
            }

            //建筑年代帅选条件
            if( isset ($demand_info['buildyear1']) && isset ($demand_info['buildyear2']) 
                && $demand_info['buildyear1'] >= 0 && $demand_info['buildyear2'] > 0 )
            {
                $cond_where .= " AND buildyear >= ".$demand_info['buildyear1']." AND buildyear <= ".$demand_info['buildyear2'] ;
            }
            
            
            //加载二手房模型类
            $this->load->model('sell_model');

            //设置查询字段
            $house_fields = array( 'id' , 'infotype' , 'address' , 'buildarea' 
                          , 'price' , 'buildyear');
            $this->sell_model->set_select_fields( $house_fields );
            
            //查询总数
            $num_rows = $this->sell_model->find_count_by( $cond_where );
            
            $perpage_num = 4;
            $num_rows = intval( $num_rows );
            $total_page = ceil( $num_rows / $perpage_num );

            if( $page != '' && $page > $total_page )
            {
                $page = $total_page;
            }

            if( $page == '' ||  $page == 0 )
            {
                $page = 1;
            }
            $offset = ( $page - 1 ) * $perpage_num;

            //查询房源信息
            $sellinfo = $this->sell_model->find_all_by( $cond_where , $offset , $perpage_num );
        }
        
        if( is_array ($sellinfo) && !empty($sellinfo) )
        {   
            $house = $this->config->item('house');
            $this->load->helper('common_string');
            foreach($sellinfo as $key => $value )
            {   
                $sellinfo[$key]['infotype_str'] = isset($house['infotype'][$sellinfo[$key]['infotype']]) 
                        ? $house['infotype'][$sellinfo[$key]['infotype']] : '未知';
                
                $sellinfo[$key]['buildarea'] = strip_end_0( $sellinfo[$key]['buildarea'] );
                $sellinfo[$key]['price'] = strip_end_0($sellinfo[$key]['price']);
                
            }
            $data_info['total_page'] = $total_page;
            $data_info['house_info'] = $sellinfo;
        }
        else
        {
            $data_info['total_page'] = 0;
            $data_info['house_info'] = array();
        }
        
        echo $this->ajax_model->array_to_json($data_info);
    }
    
    
    /**
    * 根据根据求租信息编号获取符合条件的房源
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    public function get_renthouselist_by_wantid()
    {   
        $page = $this->input->get('page');
        $want_id = $this->input->get('want_id');
       
        //获取求租信息
        $demand_info = array();
        $this->load->model('rent_demand_model');
        
        //设置查询字段
        $select_field = array('id','street','street1','street2','buildarea1'
                    ,'buildarea2','price1','price2','renttype');
        $this->rent_demand_model->set_search_fields($select_field);
        
        //获取求租信息
        $this->rent_demand_model->set_id($want_id);
        $demand_info = $this->rent_demand_model->get_info_by_id();
        
        //根据需求信息，查询该经纪人符合条件的房源
        if(is_array($demand_info) && !empty($demand_info))
        {   
            //经纪人编号
            $uid = $this->user_arr['uid'];
            $cond_where = "uid = '".$uid."' AND esta = 1 AND infofrom = '5' ";
            
            $street_ids = '';
            if( isset ($demand_info['street']) && $demand_info['street'] > 0 )
            {
                $street_ids .= $demand_info['street'];
            }

            if( isset ($demand_info['street1']) && $demand_info['street1'] > 0 )
            {
                $street_ids .= ','.$demand_info['street1'];
            }

            if( isset ($demand_info['street2']) && $demand_info['street2'] > 0 )
            {
                $street_ids .= ','.$demand_info['street2'];
            }
            $cond_where .= " AND streetid IN(".$street_ids.")";
            
            
            //面积帅选条件
            if( isset ($demand_info['buildarea1']) && isset ($demand_info['buildarea2']) 
                && $demand_info['buildarea1'] >= 0 && $demand_info['buildarea2'] > 0 )
            {
                $cond_where .= " AND buildarea >= ".$demand_info['buildarea1']." "
                        . "AND buildarea <= ".$demand_info['buildarea2'] ;
            }

            //价格筛选条件
            if( isset ($demand_info['price1']) && isset ($demand_info['price2']) 
                && $demand_info['price1'] >= 0 && $demand_info['price2'] > 0 )
            {
                $cond_where .= " AND price >= ".$demand_info['price1']." AND price <= ".$demand_info['price2'] ;
            }

            //租赁方式
            /*if( isset ($demand_info['renttype']) && isset ($demand_info['renttype']))
              {
                $cond_where .= " AND renttype = '".$demand_info['renttype']."'" ;
               }*/
            
            
            //加载二手房模型类
            $this->load->model('rent_model');

            //设置查询字段
            $house_fields = array( 'id' , 'infotype' , 'address' , 'buildarea' 
                          , 'price' , 'renttype');
            $this->rent_model->set_select_fields( $house_fields );
            
            //查询总数
            $num_rows = $this->rent_model->find_count_by( $cond_where );
            
            $perpage_num = 4;
            $num_rows = intval( $num_rows );
            $total_page = ceil( $num_rows / $perpage_num );

            if( $page != '' && $page > $total_page )
            {
                $page = $total_page;
            }

            if( $page == '' ||  $page == 0 )
            {
                $page = 1;
            }
            $offset = ( $page - 1 ) * $perpage_num;

            //查询房源信息
            $sellinfo = $this->rent_model->find_all_by( $cond_where , $offset , $perpage_num );
        }
        
        if( is_array ($sellinfo) && !empty($sellinfo) )
        {   
            $house = $this->config->item('house');
            $this->load->helper('common_string');
            foreach($sellinfo as $key => $value )
            {   
                $sellinfo[$key]['infotype_str'] = isset($house['infotype'][$sellinfo[$key]['infotype']]) 
                        ? $house['infotype'][$sellinfo[$key]['infotype']] : '未知';
                
                $sellinfo[$key]['buildarea'] = strip_end_0( $sellinfo[$key]['buildarea'] );
                $sellinfo[$key]['price'] = strip_end_0($sellinfo[$key]['price']);
                
            }
            $data_info['total_page'] = $total_page;
            $data_info['house_info'] = $sellinfo;
        }
        else
        {
            $data_info['total_page'] = 0;
            $data_info['house_info'] = array();
        }
        
        echo $this->ajax_model->array_to_json($data_info);
    }
    
    
    /**
    * 根据求购信息编号，获取经纪人匹配房源的详情信息
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    public function get_sell_details_matched( )
    {   
        $rowid_arr = array();
        
        //求购信息编号
        $wantid = $this->input->get('wantid');
        
        //经纪人编号
        $uid = $this->user_arr['uid'];
        
       //经纪人匹配该条求购信息的房源编号
       $this->load->model('buy_match_model');
       
       $this->buy_match_model->set_want_id($wantid);
       $this->buy_match_model->set_match_uid($uid);
       $matched_info = $this->buy_match_model->get_rowid_by_matchuid( 5 );

       $sellinfo = array();
       if( is_array ($matched_info) && !empty($matched_info) 
           && isset($matched_info['match_id']) &&  $matched_info['match_id'] > 0)
       {   
           $rowid = $matched_info['match_id'];
           $select_fields = array( 'id' , 'address' , 'infotype' 
                            , 'streetid' , 'buildarea' , 'price' , 'buildyear' );
           $sellinfo = $this->_get_sellinfo_by_id( $uid , $rowid , $select_fields);
       }

       if( is_array( $sellinfo ) && !empty( $sellinfo ) )
       {    
           $this->load->helper('common_url_helper');
           $house = $this->config->item('house');
           $sellinfo['info_url'] = get_sellinfo_url($sellinfo['id']);
           $sellinfo['infotype'] = isset($house['infotype'][$sellinfo['infotype']]) 
                            ? $house['infotype'][$sellinfo['infotype']] : '';
       }
       else 
       {
           $sellinfo['id'] = 0; 
       }
       
       echo $this->ajax_model->array_to_json($sellinfo);
    }
    
    
    /**
    * 根据求租信息编号，获取经纪人匹配房源的详情信息
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    public function get_rent_details_matched( )
    {   
        $rowid_arr = array();
        
        //求购信息编号
        $wantid = $this->input->get('wantid');
        
        //经纪人编号
        $uid = $this->user_arr['uid'];
        
       //经纪人匹配该条求购信息的房源编号
       $this->load->model('rent_match_model');
       
       $this->rent_match_model->set_want_id($wantid);
       $this->rent_match_model->set_match_uid($uid);
       $matched_info = $this->rent_match_model->get_rowid_by_matchuid( 5 );

       $rentinfo = array();
       if( is_array ($matched_info) && !empty($matched_info) 
           && isset($matched_info['match_id']) &&  $matched_info['match_id'] > 0)
       {   
           $rowid = $matched_info['match_id'];
           $select_fields = array( 'id' , 'address' , 'infotype' 
                            , 'streetid' , 'buildarea' , 'price' , 'renttype' );
           $rentinfo = $this->_get_rentinfo_by_id( $uid , $rowid , $select_fields);
       }

       if( is_array( $rentinfo ) && !empty( $rentinfo ) )
       {    
           $this->load->helper('common_url_helper');
           $house = $this->config->item('house');
           $rentinfo['info_url'] = get_rentinfo_url($rentinfo['id']);
           $rentinfo['infotype'] = isset($house['infotype'][$rentinfo['infotype']]) 
                            ? $house['infotype'][$rentinfo['infotype']] : '';
       }
       else 
       {
           $rentinfo['id'] = 0; 
       }
       
       echo $this->ajax_model->array_to_json($rentinfo);
    }
    
    
    /**
    * 通过选中的房源来匹配求购信息
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    function match_buy_demand_by_rowid()
    {
        //求购信息编号
        $want_id = $this->input->get('want_id');
        
        //待匹配的经纪人房源ID
        $match_id = $this->input->get('rowid');
        
        //匹配经纪人账号编号
        $match_uid = $this->user_arr['uid'];
        
        $msg_result = 'error';
        $start_time = strtotime(date('Y-m-d'));
        $now_time = intval (date( 'His' , time())); //当前时间点

        //求购信息匹配条件
        $fields_arr = array('uid','infotype','street','street1','street2','address'
                    ,'buildyear1','buildyear2', 'buildarea1','buildarea2'
                    ,'price1','price2','creattime');

        //房源信息条件
        $house_fields_arr = array('infotype','streetid','buildarea','price','buildyear');

        $subject = '您的求购信息有新的匹配房源';
         $msg = '您发起的求购信息“%s”有新的房源匹配成功，'
                . '<a href="http://www.house365.com/center/want/buylist" target="_blank">点击查看</a>';
        
        //开始匹配
        if( $match_id > 0 && $match_uid > 0 && $want_id > 0 )
        {   
            //查询求购信息
            $requirement_info = array();
            $this->load->model('buy_demand_model');
            //根据需求编号获取需求信息
            $this->buy_demand_model->set_id($want_id);
            $this->buy_demand_model->set_search_fields($fields_arr);
            $requirement_info = $this->buy_demand_model->get_info_by_id();
            
            //判断需求是否存在
            if( !is_array($requirement_info) || empty($requirement_info))
            {
                $msg_result = 'demand_no_exisit';
                echo $msg_result;
                exit;
            }
            
            $want_uid = $requirement_info['uid'];
            
            //匹配类
            $match_info = array();
            $this->load->model('buy_match_model');
            //根据需求编号获取已匹配信息
            $this->buy_match_model->set_want_id( $want_id );
            $matched_num = $this->buy_match_model->get_count_by_wantid( 5 );
            
            if( $matched_num > 0)
            {
                $match_info = $this->buy_match_model->get_list_by_wantid( 5 , 0 , $matched_num );
            }
            
            //求购信息总共已匹配数量
            $total_match_num = count( $match_info );
            
            //求购信息今日已匹配数量
            $today_match_num = 0;
            
            //求购信息账号已匹配数量
            $my_match_num = 0;

            //求购信息发布的时间点
            $publish_time = intval(date('His' , $requirement_info['creattime']));

            //每个求购信息的下期匹配时间点和本期匹配开始节点
            if( $now_time < $publish_time )
            {
                $start_time_str = date( 'Y-m-d' , time() - 86400 ).''
                        . ' '.date('H:i:s' , $requirement_info['creattime']);
            }
            else
            {
                $start_time_str = date( 'Y-m-d' , time() ).''
                        . ' '.date('H:i:s' ,$requirement_info['creattime']);
            }

            //本轮开始时间节点
            $start_time = strtotime( $start_time_str );

            //匹配情况
            for( $i = 0 ; $i < $total_match_num ; $i++ )
            {
                //今日已匹配个数
                if( $match_info[$i]['creattime'] >= $start_time )
                {
                    $today_match_num ++;
                }

                //我已匹配个数
                if( $match_info[$i]['match_uid'] == $match_uid )
                {
                    $my_match_num ++;
                }
            }

            //总量限制
            if( $total_match_num >= 200)
            {
                $msg_result = 'total_limit_error';
                echo $msg_result;
                exit;
            }

            //今日总量限制
            if( $today_match_num >= 20)
            {
                $msg_result = 'day_limit_error';
                echo $msg_result;
                exit;
            }

            //重复匹配验证
            if( $my_match_num >= 1)
            {
                $msg_result = 'my_limit_error';
                echo $msg_result;
                exit;
            }

            /*匹配房源信息是否符合验证求购信息条件*/
            $house_fields_str = '';
            foreach( $house_fields_arr as $key => $value)
            {
                $house_fields_str .= $house_fields_str != '' ? ','.$value : $value;
            }

            //准备匹配的房源信息
            $match_info = $this->_get_sellinfo_by_id( $match_uid , $match_id , $house_fields_arr);
            
            //房源类型验证
            $infotype = $match_info['infotype'];
            if( $infotype != $requirement_info['infotype'] )
            {
                if( $requirement_info['infotype'] != 6 && $infotype != 5  )
                {
                    $msg_result = 'infotype_error';
                    echo $msg_result;
                    exit;
                }
            }

            //匹配街道编号
            $street_id = intval($match_info['streetid']);
            $require_street[0] = intval( $requirement_info['street'] );
            $require_street[1] = intval( $requirement_info['street1'] );
            $require_street[2] = intval( $requirement_info['street2'] );
            
            if( $street_id == 0 || !in_array($street_id , $require_street))
            {
                $msg_result = 'street_error';
                echo $msg_result;
                exit;
            }

            //匹配buildarea
            $buildarea = intval($match_info['buildarea']);
            if( $buildarea < $requirement_info['buildarea1'] 
                    || $buildarea > $requirement_info['buildarea2'] )
            {
                $msg_result = 'buildarea_error';
                echo $msg_result;
                exit;
            }

            //匹配buildyear
            $buildyear = intval( $match_info['buildyear'] );
            if( in_array(array('buildyear1','buildyear2'), $fields_arr ) 
                    && ($buildyear < $requirement_info['buildyear1'] 
                    || $buildyear > $requirement_info['buildyear2']) )
            {
                $msg_result = 'buildyear_error';
                echo $msg_result;
                exit;
            }

            //匹配price
            $price = intval($match_info['price']);
            if( $price < $requirement_info['price1'] || $price > $requirement_info['price2'] )
            {
                $msg_result = 'price_error';
                echo $msg_result;
                exit;
            }

            $tt = array();
            $tt['match_id'] = $match_id;
            $tt['match_uid'] = $match_uid;
            $tt['want_id']  = $want_id;
            $tt['want_uid'] = $want_uid;
            $tt['infofrom'] = 5; //中介
            $tt['esta']     = 0; //匹配状态
            $tt['isread']   = 0; //是否已经查看
            $tt['creattime'] = time();
            
            //房豆处理(匹配房源扣除房豆)
            $arrBroker = $arrBroker = array(
                'id' => $match_uid,
                'groupid' => $this->user_arr['package_id'],
            );
            
            $gbc  = new GrowthBrokerCredit($arrBroker); 
            $inCreditStatus = $gbc->reduce('matchBuy');

            //操作结果
            if( is_array($inCreditStatus) && $inCreditStatus['status'] == 1 )
            {   
                //添加匹配信息
                $result = $this->buy_match_model->add_match_info($tt);

                if( $result )
                {   
                    //修改求租房源新匹配个数
                    $update_arr = array('matched_num' => '`matched_num` + 1');
                    $up_result = $this->buy_demand_model->update_info_by_id( $update_arr , FALSE);

                    //发送站内信
                    if( $up_result === TRUE)
                    {
                        $subject = urlencode($subject);
                        $msg = urlencode(sprintf($msg,$requirement_info['address']));
                        $ulr = 'http://www.house365.com/center';
                        $param = '/esf_center_api/api_sendmessage?uid='.$want_uid.''
                                . '&msg='.$msg.'&subject='.$subject.'&city=nj';
                        curl_get_contents( $ulr . $param );
                    }
  
                    $msg_result = 'sucess';
                }
                else
                {
                    $msg_result = 'insert_error';
                }
            }
            else
            {
                $msg_result = 'credit_not_enough_error';
            }
        }
        else
        {
            $msg_result = 'info_error';
        }

        echo $msg_result;
        exit;
    }
    
    
   /**
    * 通过选中的房源来匹配求租信息
    * 
    * @access pubic
    * @return json 房源信息数组
    */
    function match_rent_demand_by_rowid()
    {
        //求租信息编号
        $want_id = $this->input->get('want_id');
        
        //待匹配的经纪人房源ID
        $match_id = $this->input->get('rowid');
        
        //匹配经纪人账号编号
        $match_uid = $this->user_arr['uid'];
        
        $msg_result = 'error';
        $start_time = strtotime(date('Y-m-d'));
        $now_time = intval (date( 'His' , time())); //当前时间点

        //求租信息匹配条件
        $fields_arr = array('uid','infotype','street','street1','street2','address',
                        'buildarea1','buildarea2','price1','price2','renttype','creattime');

        //房源信息条件
        $house_fields_arr = array('infotype','streetid','buildarea','price','renttype');

        $subject = '您的求租信息有新的匹配房源';
         $msg = '您发起的求租信息“%s”有新的房源匹配成功，'
                . '<a href="http://www.house365.com/center/want/rentlist" target="_blank">点击查看</a>';
        
        //开始匹配
        if( $match_id > 0 && $match_uid > 0 && $want_id > 0 )
        {   
            //查询求租信息
            $requirement_info = array();
            $this->load->model('rent_demand_model');
            //根据需求编号获取需求信息
            $this->rent_demand_model->set_id($want_id);
            $this->rent_demand_model->set_search_fields($fields_arr);
            $requirement_info = $this->rent_demand_model->get_info_by_id();
            
            //判断需求是否存在
            if( !is_array($requirement_info) || empty($requirement_info))
            {
                $msg_result = 'demand_no_exisit';
                echo $msg_result;
                exit;
            }
            
            $want_uid = $requirement_info['uid'];
            
            //匹配类
            $match_info = array();
            $this->load->model('rent_match_model');
            //根据需求编号获取已匹配信息
            $this->rent_match_model->set_want_id( $want_id );
            $matched_num = $this->rent_match_model->get_count_by_wantid( 5 );
            
            if( $matched_num > 0)
            {
                $match_info = $this->rent_match_model->get_list_by_wantid( 5 , 0 , $matched_num );
            }
            
            //求租信息总共已匹配数量
            $total_match_num = count( $match_info );
            
            //求租信息今日已匹配数量
            $today_match_num = 0;
            
            //求租信息账号已匹配数量
            $my_match_num = 0;

            //求租信息发布的时间点
            $publish_time = intval(date('His' , $requirement_info['creattime']));

            //每个求租信息的下期匹配时间点和本期匹配开始节点
            if( $now_time < $publish_time )
            {
                $start_time_str = date( 'Y-m-d' , time() - 86400 ).''
                        . ' '.date('H:i:s' , $requirement_info['creattime']);
            }
            else
            {
                $start_time_str = date( 'Y-m-d' , time() ).''
                        . ' '.date('H:i:s' ,$requirement_info['creattime']);
            }

            //本轮开始时间节点
            $start_time = strtotime( $start_time_str );

            //匹配情况
            for( $i = 0 ; $i < $total_match_num ; $i++ )
            {
                //今日已匹配个数
                if( $match_info[$i]['creattime'] >= $start_time )
                {
                    $today_match_num ++;
                }

                //我已匹配个数
                if( $match_info[$i]['match_uid'] == $match_uid )
                {
                    $my_match_num ++;
                }
            }

            //总量限制
            if( $total_match_num >= 200)
            {
                $msg_result = 'total_limit_error';
                echo $msg_result;
                exit;
            }

            //今日总量限制
            if( $today_match_num >= 20)
            {
                $msg_result = 'day_limit_error';
                echo $msg_result;
                exit;
            }

            //重复匹配验证
            if( $my_match_num >= 1)
            {
                $msg_result = 'my_limit_error';
                echo $msg_result;
                exit;
            }

            /*匹配房源信息是否符合验证求租信息条件*/
            $house_fields_str = '';
            foreach( $house_fields_arr as $key => $value)
            {
                $house_fields_str .= $house_fields_str != '' ? ','.$value : $value;
            }

            //准备匹配的房源信息
            $match_info = $this->_get_rentinfo_by_id( $match_uid , $match_id , $house_fields_arr);
            
            //房源类型验证
            $infotype = $match_info['infotype'];
            if( $infotype != $requirement_info['infotype'] )
            {
                if( $requirement_info['infotype'] != 6 && $infotype != 5  )
                {
                    $msg_result = 'infotype_error';
                    echo $msg_result;
                    exit;
                }
            }

            //匹配街道编号
            $street_id = intval($match_info['streetid']);
            $require_street[0] = intval( $requirement_info['street'] );
            $require_street[1] = intval( $requirement_info['street1'] );
            $require_street[2] = intval( $requirement_info['street2'] );
            
            if( $street_id == 0 || !in_array($street_id , $require_street))
            {
                $msg_result = 'street_error';
                echo $msg_result;
                exit;
            }

            //匹配buildarea
            $buildarea = intval($match_info['buildarea']);
            if( $buildarea < $requirement_info['buildarea1'] 
                    || $buildarea > $requirement_info['buildarea2'] )
            {
                $msg_result = 'buildarea_error';
                echo $msg_result;
                exit;
            }

            //匹配price
            $price = intval($match_info['price']);
            if( $price < $requirement_info['price1'] || $price > $requirement_info['price2'] )
            {
                $msg_result = 'price_error';
                echo $msg_result;
                exit;
            }
            
            //匹配renttype
            $renttype = $match_info['renttype'];
            if( in_array( 'renttype' , $fields_arr ) && $renttype != $requirement_info['renttype'] )
            {
                if( $renttype != '日租' && $requirement_info['renttype'] != '短租公寓' )
                {
                    $msg_result = 'renttype_error';
                    echo $msg_result;
                    exit;
                }
            }

            $tt = array();
            $tt['match_id'] = $match_id;
            $tt['match_uid'] = $match_uid;
            $tt['want_id']  = $want_id;
            $tt['want_uid'] = $want_uid;
            $tt['infofrom'] = 5; //中介
            $tt['esta']     = 0; //匹配状态
            $tt['isread']   = 0; //是否已经查看
            $tt['creattime'] = time();
            
            //房豆处理(匹配房源扣除房豆)
            $arrBroker = $arrBroker = array(
                'id' => $match_uid,
                'groupid' => $this->user_arr['package_id'],
            );
            
            $gbc  = new GrowthBrokerCredit($arrBroker); 
            $inCreditStatus = $gbc->reduce('matchRent');

            //操作结果
            if( is_array($inCreditStatus) && $inCreditStatus['status'] == 1 )
            {   
                //添加匹配信息
                $result = $this->rent_match_model->add_match_info($tt);

                if( $result )
                {   
                    //修改求租房源新匹配个数
                    $update_arr = array('matched_num' => '`matched_num` + 1');
                    $up_result = $this->rent_demand_model->update_info_by_id( $update_arr , FALSE);

                    //发送站内信
                    if( $up_result === TRUE)
                    {
                        $subject = urlencode($subject);
                        $msg = urlencode(sprintf($msg , $requirement_info['address']));
                        $ulr = 'http://www.house365.com/center';
                        $param = '/esf_center_api/api_sendmessage?uid='.$want_uid.''
                                . '&msg='.$msg.'&subject='.$subject.'&city=nj';
                        curl_get_contents( $ulr . $param );
                    }
  
                    $msg_result = 'sucess';
                }
                else
                {
                    $msg_result = 'insert_error';
                }
            }
            else
            {
                $msg_result = 'credit_not_enough_error';
            }
        }
        else
        {
            $msg_result = 'info_error';
        }

        echo $msg_result;
        exit;
    }
    
    
    /**
     * 找回密码
     * @access public
     * @return int
     */
    public function find_pasword(){
        $telno = $this->input->get('mobilePhone',TRUE); 
        $username = $this->input->get('loginAccount',TRUE);      
        $this->load->model('broker_model');
        $data_arr = $this->broker_model->get_info_by_username($username); 
        if(!empty($data_arr)&&$data_arr['telno']){
            if($data_arr['telno']==$telno){
                //查询今天短信找密码用几次
                $count_num = $this->broker_model->get_findpwd_count($telno);
                if($count_num<3){
                    $validcode = random(6);
                    $data = array('tbl'=>'broker','rowid'=>$data_arr['uid'],'validcode'=>$validcode,'mobile'=>$telno,'dateline'=>time());
                    $smsid = $this->broker_model->insert_info_sms($data);
                    if($smsid){
                        $msg   = '尊敬的365网友，您的验证码为'.$validcode.',正确输入此验证码可初始化您的密码';
                        send_sms($telno, $msg,'sx',$validcode);
                        $session_data = array('vaildmoblie'=>$telno,'vaildbrokerid'=>$data_arr['uid']);
                        $this->session->set_userdata($session_data);
                        $message_text = 4; //成功      
                    }
                                          
                }else{
                    $message_text = 3;//发送信息超过3次
                }         
            }else{
                $message_text = 2; //资料中手机号码和输入的不符           
            }
        }else{
            $message_text = 1; //资料为空或资料中无手机号码
        }
        echo $message_text;
        exit();
    }
    
    /**
     * 再次获取找回密码验证码
     * @access public
     * @return int
     */
    public function revalidcode(){
        $telno = $this->input->get('telno'); 
        $brokerid = $this->input->get('brokerid');        
        $this->load->model('broker_model');
        if($telno&&$brokerid){            
            //查询今天短信找密码用几次
            $count_num = $this->broker_model->get_findpwd_count($telno);
            if($count_num<3){
                $validcode = random(6);
                $data = array('tbl'=>'broker','rowid'=>$brokerid,'validcode'=>$validcode,'mobile'=>$telno,'dateline'=>time());
                $smsid = $this->broker_model->insert_info_sms($data);
                if($smsid){
                    $msg   = '尊敬的365网友，您的验证码为'.$validcode.',正确输入此验证码可初始化您的密码';
                    send_sms($telno, $msg,'sx',$validcode);
                    $result = 2;                     
                }                 
            }else{
                $result = 1;               
            }
        }else{
           $result = 3;
        }
        echo $result;
        exit;
    }
    
    /**
     * 验证找回密码验证码
     * vaild_find_pwd
     */
    public function vaild_find_pwd(){
         $vaildcode = $this->input->get('code',TRUE);    
         $brokerid = $this->input->get('brokerid',TRUE);
         $telno = $this->input->get('telno',TRUE);       
         //加载broker模型类
         $this->load->model('broker_model'); 
         $message_flag = 0;
         $lastst_sms = $this->broker_model->get_lastst_sms($telno);
         if(!empty($lastst_sms)&&$lastst_sms['validcode']==$vaildcode){
             $is_expire = $this->broker_model->is_expire_code($lastst_sms['dateline']);
             if(!$is_expire){
                 $message_flag = 2; 
             }else{
                 // 调用用户中心更新密码
                 $ucRes = $this->broker_model->updateUcPwd($lastst_sms['rowid'], '111111');
                 if ($ucRes['result'] != 1) {
                     $message_flag = 1;
                 } else {
                     $this->broker_model->update_broker_pwd($lastst_sms['rowid']);
                     $this->broker_model->update_sms_flag($lastst_sms['id']);
                     $message_flag = 3;
                 }
             }
         }else{
             $message_flag = 1;                           
         }         
        echo $message_flag;
        exit;
    }
    
    
    
    /**
     * 获取头部系统信息数量
     * get_remind_message
     * @param $uid
     * @return array
     */
    public function get_remind_message($uid){
        if($uid != $this->user_arr['uid']){
            echo "login";
	    exit;
        }       
        $this->load->model('message_model');
        $data = $this->message_model->get_message_no_read($this->user_arr['uid']);
        echo json_encode($data);
        exit;
    }

    public function banwords() {
         $address = urldecode($this->input->get('address',TRUE));    
         $remark = urldecode($this->input->get('remark',TRUE));
         $this->load->helper('common_house_helper');
         $filename = STATIC_SOURCE_URL . '/common/banwords/banwords.txt';
         $result = array('status' => 1);
         if (publish_banwordCheck($address, $filename)) {
             $result['status'] = 2;
         } else if (publish_banwordCheck($remark, $filename)) {
            $result['status'] = 3;
         }
         echo $this->ajax_model->array_to_json($result);
    }

	public function check_sensitive_word()
	{
		$keyword = '';

		if(!empty($_POST['keyword']))
		{
			$keyword =  iconv('utf-8','gbk',urldecode($_POST['keyword']));
		}
		
		$this->load->model('ajax_model');
		$sensitive_word = $this->ajax_model->check_sensitive_word($keyword);
		
		$result = true;
		if(!empty($sensitive_word))
		{
			$result = iconv('gbk','utf-8',$sensitive_word);
		}
		
		exit(json_encode($result));
	}
	
	/**
	 * 获取小区不同面积的均价
	 *
	 * @param unknown_type $block_id
	 */
	public function find_block_area_prices($block_id){
	    $data = bm('block')->block_area_prices($block_id,'nj');
        echo json_encode($data);die();
	}
}
