<?php if (!defined('BASEPATH'))  exit('No direct script access allowed');


class Test_model extends MY_Model
{

	function __construct()
	{
		parent::__construct();
		$this->memkey = 'usercent'.GB_CITY;
        $this->load->library('session');
        $this->load->model("house_model");
        $this->load->model("block_model");
	}


	/**
	*感兴趣的学区房（model下面的）
	*@param int $uid 
	*@return array
	*/
	public function getLikeSchoolHouse($uid){

		$key = $this->memkey.'get_lise_school_house_'.$uid;
		if($this->input->get('update') == 1)
		{
		  $this->memcached_class->delete($key);
		}
		
		$house = $this->memcached_class->get($key);
		
		if(empty($house))
		{
			$houseNum = 0;
			//获取关注的学校
			$block = array();		
			$school = $this->getCollectSchool($uid,$city=GB_CITY);		
			if(is_array($school)&&!empty($school))
			{
				foreach($school as $value)
				{
					$tempBlock = $this->getSchoolBlock($value);
					if(!empty($tempBlock))
					{
						$block = array_merge($tempBlock,$block); 
					}else{
						$block = $tempBlock;
					}
					 
				}
				$block = array_unique($block);
				if(is_array($block)&&!empty($block))
				{
					$blockStr = implode(",",$block);
					$blockStr = rtrim($blockStr,',');
					$sql = "SELECT id,district,streetid,blockshowname,room,hall,"
										. "buildarea,updatetime,floor,subfloor,totalfloor,fitment,"
										. "forward,buildyear,pic1,address,price FROM sell "
										. "WHERE blockid  IN (".$blockStr.") AND esta = 1 "
										. "ORDER BY creattime DESC LIMIT 0,4 luc";								
					$info = $this->server_sell->query($sql);
					$house = $info['Record'];
					$houseNum = count($house);
				}
			
			}    
			
			if($houseNum < 4)
			{   //根据游览记录
				if(GB_CITY == 'nj')
				{
					$sellinfoBlock = isset($_COOKIE['sellinfo_blockid']) ? $_COOKIE['sellinfo_blockid'] : '';
				}else{
					$sellinfoBlock = isset($_COOKIE['sellinfo_blockid_'.GB_CITY]) ? $_COOKIE['sellinfo_blockid_'.GB_CITY] : ''; 
				}

				//获取cookie记录获取最新创建的房源
				if(!empty($sellinfoBlock))
				{
					$remainNum = 4-$houseNum;               				
					$blockStr = rtrim($sellinfoBlock,',');
					$sql = "SELECT id,district,streetid,blockshowname,room,hall,"
									. "buildarea,updatetime,floor,subfloor,totalfloor,fitment,"
									. "forward,buildyear,pic1,address,price FROM sell "
									. "WHERE blockid  IN (".$blockStr.") AND esta = 1 "
									. "ORDER BY creattime DESC LIMIT 0,$remainNum luc";				
				   
					$info= $this->server_sell->query($sql);
					$tempHouse = $info['Record'];
					if($remainNum==4)
					{
						$house = $tempHouse;
					}else{
						$house = array_merge($tempHouse,$house);
					}
					$houseNum += count($house);

				}
			}
			if($houseNum < 4)
			{
				$remainNum = 4-$houseNum;               				
				$blockStr = "学区";
				$sql = "SELECT id,district,streetid,blockshowname,room,hall,"
								. "buildarea,updatetime,floor,subfloor,totalfloor,fitment,"
								. "forward,buildyear,pic1,address,price FROM sell "
								. "WHERE address  like '%".$blockStr."%' AND esta = 1 "
								. "ORDER BY creattime DESC LIMIT 0,$remainNum luc";
				
				$info = $this->server_sell->query($sql);
				$tempHouse = $info['Record'];
				 
				if($remainNum==4)
				{
					$house = $tempHouse;
				}else{
					$house = array_merge($tempHouse,$house);
				}
				$houseNum += count($house);
			
			}

			$this->memcached_class->add($key, $house,1000);
		}
		return $house;
		
	}




	



	
	/**
	*获取关注的学校（model下面的）
	*@param int $uid 
	*@param string $city 城市
	*@param int $limit 获取学校的个数
	*@return array
	*/
	public function getCollectSchool($uid,$city=GB_CITY,$limit=10)
	{

		$school_array =  $this->get_data(array('form_name' => 'personal_collection','where'=>array('uid'=>$uid,'city_name'=>$city,'collect_id <>'=>0,'kind'=>7),'select'=>array('collect_id'),'order_by'=>'id DESC',),'esfbak');
		if(is_array($school_array) && !empty($school_array))
		{
			 foreach($school_array as $key=>$value)
             {
				 if($key<$limit)//限制获取的个数
			     {					
					 $school[] = $value['collect_id'];
				 }
                    
             }
        }
		return $school;

	}

	
	/**
	*获取学校下面的小区（model下面的）
	*@param int schoolId	
	*@return array
	*/
	public function getSchoolBlock($schoolId)
	{	
		$key = $this->memkey.'get_school_block_arr_'.$schoolId;
		if($this->input->get('update') == 1)
		{
			$this->memcached_class->delete($key);
		}
		$block = $this->memcached_class->get($key);
		if(empty($block) )
		{
			$schoolBlock = $this->get_data(array('form_name' => 'school_block','where'=>array('school_id'=>$schoolId),'select'=>array('block_id')),'esfhousebak');
			if(is_array($schoolBlock) && !empty($schoolBlock))
			{
				 foreach($schoolBlock as $value)
				 {
					 $block[] = $value['block_id'];
				 }
			}
			$this->memcached_class->add($key, $block,3600);
		}
		return $block;
	}  
	



	 /**
	 * 根据学校id获取本学区最新房源信息
	 * @param int $school
	 * @return array
	 */
	public function getSchoolLastestHouse($school)
	{
		$key = $this->memkey.'get_school_house_lastest_'.$school;
		if($this->input->get('update') == 1)
		 {
		  $this->memcached_class->delete($key);
		 }
		$housedetail = $this->memcached_class->get($key);
		if(empty($housedetail) )
		{
		  $block = $this->getSchoolBlock($school);
		  $selldetail = array();
		  if(is_array($block)&&!empty($block))
		  {
			  $blockStr = implode(",",$block);
		      $blockStr = rtrim($blockStr,',');		  
		      $sql = "select id,district,streetid,blockshowname,room,hall,buildarea,updatetime,forward,fitment,subfloor,floor,totalfloor,buildyear from sell where blockid in (".$blockStr.") order by updatetime desc  limit 0,1 luc";
		      $selldetail = $this->server_sell->query($sql);
		  }	
          if(!empty($selldetail))
          {
			  $housedetail = $selldetail['Record'][0];
			  $housedetail['time'] = time_tran($housedetail['UPDATETIME']);
			  $streetname = $this->block_model->getstreetname($housedetail['STREETID']);
			  $housedetail['streetname'] = $streetname['streetname'];
          }else{
            $housedetail=array();
          }
		  $this->memcached_class->add($key, $housedetail,60);
		}

		return $housedetail;
	}



	
	/**
	 * 获取关注学区信息
	 * @param int $kind 关注类别
	 * @param int $uid 用户id
	 * @param int $offset
	 * @param int $pagesize
	 * @return array
	 */
	public function getCollectSchoolList($kind,$uid,$offset,$pagesize)
	{	
		global $school_type,$school_pap,$school_rank;
		$collectSchool = $this->getcollect($kind,$uid,$offset,$pagesize);//修改user_model
        if(is_array($collectSchool)&&!empty($collectSchool))
		{
			foreach($collectSchool as $key=>$value){
				//$value['collect_id'];//学校id	
				$collectValue = unserialize($value['collect_value']);
				$collectSchool[$key]['feature'] = $this->getSchoolFeature($collectValue['features']);
				$blockArr = $this->getSchoolBlock($value['collect_id']);
				$collectSchool[$key]['blockNum'] = count($blockArr);
                $collectSchool[$key]['sellNum'] = $this->getSchoolHouseNum($value['collect_id'],$blockArr,'sell');
				$collectSchool[$key]['rentNum'] = $this->getSchoolHouseNum($value['collect_id'],$blockArr,'rent');
				$collectSchool[$key]['lastestHouse'] = $this->getSchoolLastestHouse($value['collect_id']);//最新房源
				$collectSchool[$key]['price'] = $this->block_model->getBlockPrice($value['collect_value'],$blockArr);//改调用block_model下的
				$collectSchool[$key]['schoolName'] = $collectValue['schoolname'];
				$collectSchool[$key]['address'] = $collectValue['address'];
				$collectSchool[$key]['streetname'] = $collectValue['streetname']['streetname'];
				$collectSchool[$key]['district'] = $collectValue['district'];
				$collectSchool[$key]['schoolType'] = $school_type[$collectValue['school_type']];
				$collectSchool[$key]['schoolPap'] = $school_pap[$collectValue['ispublic']];//性质
				$collectSchool[$key]['schoolRank'] = $school_rank[$collectValue['rank']];//级别
				$collectSchool[$key]['coverphoto'] = $collectValue['coverphoto'];

			}
		}

		return $collectSchool;
		
	}


	


   
   /**
	 * 获取房源数量
	 * @param int $school 学校id
	 * @param array $blockArr 小区数组
	 * @param string $type 二手房或租房 	
	 * @return array
	 */
   public function getSchoolHouseNum($school,$blockArr,$type='sell')
   {
	   $key = $this->memkey.'get_school_house_num_'.$type."_".$school;
	   if($this->input->get('update') == 1)
	   {
		  $this->memcached_class->delete($key);
	   }
	   $houseNum = $this->memcached_class->get($key);
       if(empty($houseNum))
	   {
		   if(is_array($blockArr)&&!empty($blockArr))
	       {
			  $blockStr = implode(",",$blockArr);
			  $blockStr = rtrim($blockStr,',');		  
			  $sql = "select id,district,streetid,blockshowname,room,hall,buildarea,updatetime,forward,fitment,subfloor,floor,totalfloor,buildyear from ".$type." where blockid in (".$blockStr.") order by updatetime desc  limit 0,1 luc";
			  if($type=='sell')
			  {
				  $detail = $this->server_sell->query($sql);
			  }elseif($type=='rent'){
			      $detail = $this->server_rent->query($sql);
			  }
			  
			  $houseNum = $detail['TOTAL'];
			  $this->memcached_class->add($key, $houseNum,3600);
	      }	

	   }
	   return $houseNum;	   

   }



   //处理学校特色
   public function getSchoolFeature($features)
   {
	   global $school_features;	
	   if(isset($features))
       {	     
		   $match_num = 0;
		   $school_feature = array();
		   //#2#,#9#
		   $match_num = preg_match_all('/[0-9]+/',$features,$school_feature);
		   $node['features'] = $match_num > 0 ? $school_feature[0] : array();		
		   foreach($school_feature[0] as $key=>$value)
		   {	
				$s_shchool_feature[] .= $school_features[$value];
		   }
	    }
		return $s_shchool_feature;
   }
	



}