<?php

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


class Dev_House_model extends MY_Model
{

    function __construct()
    {
       parent::__construct();
       $this->load->model("house_statistic_model");
    }

     /**
     * 验证房源的可刷新次数
     * @param type $uid，房源id  $id
     * @return array
     */
    function yzrefrshnum($uid,$id,$tbl='sell')
    {
		 //获得可刷新次数
        //flag=1代表上传图片刷新， 2代表付费刷新
		$num1 =  $this->get_data(array('form_name' => 'personal_refresh','where'=>array('uid'=>$uid,'rowid'=>$id,'tbl'=>$tbl,'esta'=>1,'flag'=>1),'select'=>array('refresh_num')),'esfbak');

		$num2 =  $this->get_data(array('form_name' => 'personal_refresh','where'=>array('rowid'=>$id,'tbl'=>$tbl,'flag'=>2,'esta'=>1,'begin_time <'=>time(),'end_time >'=>time()),'select'=>array('refresh_num')),'esfbak');
		  if(!empty($num1[0]['refresh_num']) && !empty($num2[0]['refresh_num']))
			{
			 $num = $num1[0]['refresh_num']+$num2[0]['refresh_num'];
			}elseif(!empty($num1[0]['refresh_num']))
			{
			 $num = $num1[0]['refresh_num'];
			}elseif(!empty($num2[0]['refresh_num']))
			{
			 $num = $num2[0]['refresh_num'];
			}
			if(!empty($num))
			{
			 return $num;
			}else{
			 return 0;
			}
    }

         /**
     * 验证房源的可刷新次数
     * @param type $uid，房源id  $id
     * @return array
     */
    function yzrefrsh($uid,$id,$tbl='sell',$flag=1)
    {
     //获得可刷新次数
    $result =  $this->get_data(array('form_name' => 'personal_refresh','where'=>array('uid'=>$uid,'rowid'=>$id,'tbl'=>$tbl,'esta'=>1),'select'=>array('id')),'esfbak');

    
        if(!empty($result))
        {
         return $result;
        }else{
         return 0;
        }
    }


    
     /**
     * 验证房源的可刷新次数
     * @param $telno 手机号,$arr 匹配信息,$tbl 表
     * @return array
     */
    function yzsamehouse($telno , $arr , $tbl = 'sell')
     {
        $total_num = 0;
        if( in_array( $tbl , array('sell','rent') ) && !empty($telno) )
        {
            $sql = "SELECT id FROM $tbl ";
            $where_cond = " WHERE esta = '1' AND infofrom = '1' AND ischarge = '0' AND telno='".$telno."'";

			if(is_array($arr) && !empty($arr))
			{
				foreach($arr as $key=>$value)
				{	
					$value = addslashes(strip_tags($value));
					$where_cond .= " AND ".$key." = '".$value."'";
				}
			}
			//echo '<!--'.$sql . $where_cond.'-->';
			$query = $this->db_esfhousebak->query($sql . $where_cond);
			$result = $query->result_array();

            if( isset($result[0]['id']) )
            {
                $return = 1;
            }else{
                $return = 0;
            }
        }

        return $return;
     }

     /**
     * 添加房源的可刷新次数
     * @param type $uid，房源id  $id,添加刷新次数 $num,城市 $city_name
     * @return array
     */
    function addrefrshnum($uid,$id,$tbl='sell',$num,$city_name,$flag=1)
    {
       
      //验证是否有刷新次数
      $result =  $this->yzrefrsh($uid,$id,$tbl,$flag);
      if($result >0 )
      {
        $this->updaterefrshnum($uid,$id,$num,$tbl,$flag,$city_name);
      }
      else
      { 
        $arr['uid'] = $uid;
        $arr['rowid'] = $id;
        $arr['tbl'] = $tbl;
        $arr['refresh_num'] = $num;
        $arr['cityname'] = $city_name;

        //设置表
        $this->house_model->set_table('personal_refresh');

        //过滤表结构
        $result = $this->house_model->add($arr,'esf');
      }

    }




    /**
    * 刷新房源更新时间
    * @param type $telno 手机号码 $validcode 验证码
    * @return string
    */
    function updatehouse($id,$tbl,$up)
    {

        if( $id > 0)
        {
            $arr = array( 'id' => $id );
            $this->set_table($tbl);
            $result = $this->save($arr,$up,'esfhouse');
			if($tbl=='rent')
			{

				$housedetail =  $this->get_data(array('form_name' => $tbl,'where'=>array('id'=>$id,'infofrom'=>'1'),'select'=>array('telno','infotype')),'esfhousebak');
				$telno =$housedetail[0]['telno'];
				$infotype =$housedetail[0]['infotype'];
				if($infotype==1)
				{
					$ip    =get_ip();


					if(isset($up) && $up['esta']==2)
					{

						$arr = array( 'rowid' => $id );
						$this->set_table('rent_of_zhizu');
						$this->save($arr,array('status'=>2),'esfhouse');
						//echo "http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=2";die;
						get_api("http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=2");
						if(GB_CITY=='nj')
						{
						$value_url ="http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=2";
						//记录日志
						$msg = "************************************************ \n";
						$msg .= date('Y-m-d H:i:s').var_export($value_url,true)." \n";
						$log = dirname(__FILE__)."/log/house_update_record_".$_SERVER['REMOTE_ADDR'].'.log';
						file_put_contents($log,$msg,FILE_APPEND );
						}
					}
					else
					{
						get_api("http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=1");

						if(GB_CITY=='nj')
						{
						$value_url ="http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=1";
						//记录日志
						$msg = "************************************************ \n";
						$msg .= date('Y-m-d H:i:s').var_export($value_url,true)." \n";
						$log = dirname(__FILE__)."/log/house_update_record_".$_SERVER['REMOTE_ADDR'].'.log';
						file_put_contents($log,$msg,FILE_APPEND );
						}
					}

				}
			}
        }
        return $result;
    }
	
	/**
    * 再发布房源
    * @param type $telno 手机号码 $validcode 验证码
    * @return string
    */
    function republishhouse($id,$tbl,$up,$conf_city)
    {
        if( $id > 0)
        {

				// 2017-3-28 添加再发布匹配小区图片 功能 --- start ----->
			$housedetail_pic_info =  $this->get_data(array('form_name' => $tbl,'where'=>array('id'=>$id,'infofrom'=>'1'),'select'=>array('pic1','blockid','telno')),'esfhousebak');
			
			if(empty($housedetail_pic_info['0']['pic1']))
			{
				$blockid    =$housedetail_pic_info['0']['blockid'];
				$pic_url_lm = $this->get_block_pic_by_type($blockid , 52);
				
				if( $pic_url_lm != '')
				{
					$filename = $pic_url_lm;
				}
				else
				{
					$filename = $this->get_block_pic_by_type( $blockid , 0);
				}
				
				if( $filename != '')
				{
					$title = '';
					$sort  = 1;
					$blockid = $blockid;
					$createtime = time();
					$upload_name = get_upload_tblname($tbl,$id);
					
					$sql = "INSERT INTO $upload_name(`tbl`,`rowid`,`position`,`filename`,`title` ,`blockid`,`sort`,`createtime`,`isfrom`) VALUES('$tbl',$id,'pic1','$filename','$title','$blockid','$sort','$createtime','1')";

					//echo $sql;die;
					$this->db_esfhouse->query($sql);
					$sql = "UPDATE $tbl SET pic1 = '".$filename."',lucupdatetime=lucupdatetime+1 WHERE id = '".$id."' ";
					//echo $sql;die;
					$this->db_esfhouse->query($sql);
					
				}
				
			}
			
			// 2017-3-28 添加再发布匹配小区图片 功能 --- end ----->
            $arr = array( 'id' => $id );
            $this->set_table($tbl);
            $result = $this->save($arr,$up,'esfhouse');

			if($conf_city=='nj' || $conf_city=='wh' || $conf_city=='hf' || $conf_city=='wx')
			{
				if($tbl=='sell')
				{
					$tbl_tmp =0;
				}
				else
				{
					$tbl_tmp =1;
				}
				$again_date =date('Y-m-d');
				$again_info =$this->get_data(array('form_name' => 'house_again_publish_stat','where'=>array('ctime'=>$again_date,'source'=>'0','type'=>$tbl_tmp),'select'=>array('id','num')),'esfhousebak');
			    if(!empty($again_info[0]['num']))
			    {
					$this->db_esfhouse->query("update house_again_publish_stat set num=num+1  where ctime='$again_date' and source=0 and type=$tbl_tmp");
			    }
			    else
			    {
					$this->db_esfhouse->query("insert into house_again_publish_stat (num,type,source,ctime) values ('1','$tbl_tmp','0','$again_date')");
			    }

                ############# 2018-9-5 再发布 添加再审核 ###########
                $ctime_now  =time();
                $telno    =$housedetail_pic_info['0']['telno'];

                $this->db_esfhouse->query("insert into house_again_check  (rowid,tbl,telno,ctime) values ($id,'$tbl',$telno,'$ctime_now')");
                ############# 2018-9-5 再发布 添加再审核 ###########


				############# 2016-7-26 再发布删除 sell_delete_app_person start ###########
				$this->db_esfhouse->query("DELETE FROM sell_delete_app_person WHERE tbl='$tbl' AND rowid = $id");
				############# 2016-7-26 再发布删除 sell_delete_app_person end ###########


				############2016-12-21 再发布传数据给直租######################
				if($tbl=='rent')
				{

					$housedetail =  $this->get_data(array('form_name' => $tbl,'where'=>array('id'=>$id,'infofrom'=>'1'),'select'=>array('telno')),'esfhousebak');
					$telno =$housedetail[0]['telno'];
					$ip    =get_ip();


					if(isset($up) && $up['esta']==1)
					{
						$arr = array( 'rowid' => $id );
						$this->set_table('rent_of_zhizu');
						$this->save($arr,array('status'=>0),'esfhouse');
						get_api("http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=0");
					}
					
				}
				$value_url ="http://mtapi.house365.com/?method=zhizu.rentRefreshHouse&city=".GB_CITY."&id=".$id."&telno=".$telno."&fromzhizu=2&ip=".$ip."&sell_status=0";
				//记录日志
				$msg = "************************************************ \n";
				$msg .= date('Y-m-d H:i:s').var_export($value_url,true)." \n";
				$log = dirname(__FILE__)."/log/house_republish_record_".$_SERVER['REMOTE_ADDR'].'.log';
				file_put_contents($log,$msg,FILE_APPEND );
				############2016-12-21 再发布传数据给直租######################


			}
        }
		//再发布更新已经激活的同样条件的房源
		$housedetail =  $this->get_data(array('form_name' => $tbl,'where'=>array('id'=>$id,'infofrom'=>'1'),'select'=>array('blockshowname','buildarea','price','floor','telno')),'esfhousebak');

       if(!empty($housedetail[0]['telno']))
        {
        //更新此条件下其他房源
        $this->db_esfhouse->query("update $tbl set esta=-5,note='系统打为重复' where telno='".$housedetail[0]['telno']."' AND esta = '1' AND infofrom = '1' AND ischarge!='1' AND id!=$id AND blockshowname='".$housedetail[0]['blockshowname']."' AND buildarea='".$housedetail[0]['buildarea']."' AND floor='".$housedetail[0]['floor']."' AND updatetime>'".strtotime(date('Y-m-d'))."'");       

        $this->db_esfhouse->query("update $tbl set esta=2,note='系统打为失效' where telno='".$housedetail[0]['telno']."' AND esta = '1' AND infofrom = '1' AND ischarge!='1' AND id!=$id AND blockshowname='".$housedetail[0]['blockshowname']."' AND buildarea='".$housedetail[0]['buildarea']."' AND floor='".$housedetail[0]['floor']."' AND updatetime<'".strtotime(date('Y-m-d'))."'"); 
        }

        return $result;
    }

	function get_block_pic_by_type($blockid , $bi_type)
	{
		$where_cond = "WHERE bi_blockid = '".$blockid."'";
		if( $bi_type > 0 )
		{
			$where_cond .= " AND bi_type = '".$bi_type."' limit 1";
		}
		else
		{
			$where_cond .= " AND bi_type IN (51,52,53) limit 1";
		}

		$sql = "SELECT bi_img as pic FROM block_img ".$where_cond .$order_cond;
		
		$query = $this->db_esfhousebak->query($sql);
		$result = $query->result_array();
		
		return $result[0]['pic'];
		
	}

     /**
     * 更新可用刷新次数
     * @param type $telno 手机号码 $validcode 验证码 $num刷新次数 $tbl 表
     * @return string
     */
    function updaterefrshnum($uid,$id,$num,$tbl='sell',$flag=1,$city = '')
    {
		if(!empty($city))
		{
			$query = $this->db_esf->query("UPDATE `personal_refresh` SET `refresh_num` = '$num' WHERE `rowid` =  '$id'  AND `uid` =  '$uid' AND `tbl` =  '$tbl' AND `flag` =  '$flag' AND `cityname`='$city'");

			if(!$query)
			{
				file_put_contents('test.log',"edit：会员id=".$uid." 房源id=".$id." 刷新次数=".$num." 城市=".$city."  房源类型tbl=".$tbl." 标记flag=".$flag." 记录时间=".date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
			}
		}
		else
		{
			$query = $this->db_esf->query("UPDATE `personal_refresh` SET `refresh_num` = '$num' WHERE `rowid` =  '$id'  AND `uid` =  '$uid' AND `tbl` =  '$tbl' AND `flag` =  '$flag'");
		}
        

        return 1;
    }

     /**
     * 根据用户id获取房源数量
     * @param type $uid
     * @return array
     */
    function gethousenumbyuid( $uid , $tbl='sell' , $esta=0)
    {
        if($esta == 1)
        {
          $housenum =  $this->get_data(array('form_name' => $tbl,'where'=>array('uid'=>$uid,'esta'=>'1','infofrom'=>'1'),'select'=>array('count(id) as num')),'esfhousebak');
        }else{

          $housenum =  $this->get_data(array('form_name' => $tbl,'where'=>array('uid'=>$uid,'esta !='=>'4','infofrom'=>'1'),'select'=>array('count(id) as num')),'esfhousebak');
        }
		//print_r($housenum);
        return $housenum[0]['num'];
    }

    /**
    * 根据用户id获取房源信息
    * @param type $uid
    * @return array
    */
    function gethousebyuid($uid,$tbl='sell',$select,$offset=0,$pagesize=0)
    {
		$this->load->model("pic_model");
        $housearray =  $this->get_data(array('form_name' => $tbl,'where'=>array('uid'=>$uid,'infofrom'=>'1','esta !='=>4),'select'=>$select,'order_by'=>'creattime desc','limit'=>$offset,'offset'=>$pagesize),'esfhousebak');
        //echo $this->db->last_query();

        $day_now = date('Y-m-d');
        if(GB_CITY=='nj'){
			//获取数组的个数，再把图片的数量插入数组中
			$housearray_number =count($housearray);
			for($i=0;$i<$housearray_number;$i++)
			{
				$sell_house_id =$housearray[$i]['id'];
				$this->load->helper('function');
				
				$uploadtbl = get_upload_tblname($tbl,$sell_house_id);
				$pic_number = $this->pic_model->getPicNum($tbl,$sell_house_id,$uploadtbl);
				$housearray[$i]['pic_num'] =$pic_number;
				$housearray[$i]['city_name']=GB_CITY;

				//计算当前房源是否参与推广，以及参与推广套餐 最后的
                //被删除或者审核中的 则不计算，直接跳过

                if($tbl == 'sell'){
                    $house_type = 1;
                }else{
                    $house_type = 2;
                }

                $now_time = time();
                $promote = $this->db_esfhousebak->from('personal_house_promote')->where(array('house_id'=>$sell_house_id,'house_type'=>$house_type,'status'=>1))->where('start_time <=',$now_time)->where('end_time >=',$now_time)->order_by('end_time','desc')->limit(1)->get()->row_array();


                $housearray[$i]['between_day'] ='';
                $housearray[$i]['$between_hour']='';
                $housearray[$i]['between']='';

                if($promote && $promote['order_id']){

                    $package_type = $promote['package_type'];

                    $order = $this->db_esfhousebak->from('personal_house_orders')->where(array('id'=>$promote['order_id'],'pay_status'=>1))->where('pay_time <>','')->get()->row_array();


                    //$pay_time = $order['pay_time'];

                    //$hours = date('H:i:s',$pay_time);
                    if($order){
                        //$endT = date('Y-m-d H:i:s',strtotime('-1 day',$promote['end_time']));
                        //$endT = $endtime.' '.$hours;
                        $day_overdue = $promote['end_time'];
                        if($day_overdue >time() ){
                            $between_time = $day_overdue-time();//相差的 秒数
                            $between_day = floor($between_time/24/3600);//相差天数

                            $h = ($between_time%(3600*24))/3600;
                            $between_hour = floor($h);
                            $housearray[$i]['between_day'] = $between_day;
                            $housearray[$i]['between_hour']= $between_hour;

                            if($between_day<1 ){
                                if($between_hour<1){
                                    $housearray[$i]['between']  = '剩余不足1小时';
                                }else{
                                    $housearray[$i]['between']  = '剩余'.$between_hour.'小时';
                                }
                            }else{
                                if($between_hour>1){
                                    $housearray[$i]['between']='剩余'.$between_day.'天'.$between_hour.'小时';
                                }else{
                                    $housearray[$i]['between']='剩余'.$between_day.'天';
                                }
                            }
                        }

                    }



                }
			}
		}


        return $housearray;
    }

    /**
    * 根据所传数组获取房源信息
    * @param type $where
    * @return array
    */
    function gethousebywhere($where,$tbl='sell',$select,$offset=0,$pagesize=0)
    {
        $housearray =  $this->get_data(array('form_name' => $tbl,'where'=>$where,'select'=>$select,'order_by'=>'updatetime desc','limit'=>$offset,'offset'=>$pagesize),'esfhousebak');
        return $housearray;
    }

    /**
     * 获取房源联系人手机号
     * @param $house_id
     */
    function getHouseTel($house_id,$tbl='sell_ext'){
        $telarray =  $this->get_data(array('form_name' => $tbl,'where'=>array('house_id'=>$house_id),'select'=>array('telno')),'esfhousebak');
        return empty($telarray) ? '' : $telarray[0]['telno'];
    }


	/**
    * 根据所传数组获取房源信息
    * @param type $where
    * @return array
    */
    function get_house_num_by_where($where,$tbl='sell')
    {	
        $house_info =  $this->get_data(array('form_name' => $tbl,'where'=>$where,'select'=>array('count(id) as num')),'esfhousebak');
		$house_num = isset($house_info[0]['num']) ? $house_info[0]['num'] : 0; 
        return $house_num;
    }


    /**
    * 更改房源的uid
    * @param type $uid
    * @return array
    */
    function updatehouseuid( $uid , $newuid , $tbl = 'sell')
    {
        $uid    = intval($uid);
        $newuid = intval($newuid);

        if( $uid > 0 && $newuid > 0 && in_array( $tbl , array('sell','rent') ) )
        {
            $sql = "UPDATE $tbl SET uid = '$newuid' WHERE uid = '$uid' AND infofrom = '1'";
            $this->db_esfhouse->query($sql);
            $msg = 1;
        }
        else
        {
            $msg = 0;
        }

        return  $msg;
    }


    /**
    * 添加个人房源匹配求购求租信息
    * @param string $want_type  求购求租类型(buy/rentwant)
    * @param int $want_id   求购求租信息编号
    * @param int $want_uid  求购求租人账号
    * @param int $match_id  匹配房源编号
    * @param int $uid   匹配人账号编号
    * @return array 添加结果
    */
    public function add_match_info( $want_type , $want_id , $want_uid , $match_id , $uid )
    {
        if( in_array( $want_type, array('buy','rentwanted') ) )
        {
            if( $want_type == 'buy')
            {
                $tbl_want = 'buy';
                $tbl_match = 'buy_match';
            }
            else if( $want_type == 'rentwanted' )
            {
                $tbl_want = 'rentwanted';
                $tbl_match = 'rentwanted_match';
            }

            //提交的日志数据
            $data   = array(
                'match_id'  => $match_id,
                'match_uid' => $uid,
                'want_id'   => $want_id,
                'want_uid'  => $want_uid,
                'infofrom'  => 1, //个人
                'esta'      => 0, //匹配状态
                'isread'    => 0, //是否已经查看
                'creattime' => time()
            );

            //是否已经添加过匹配
            $is_matched = $this->_check_is_matched( $tbl_match , $want_id , $want_uid , $match_id , $uid);

            if( !$is_matched )
            {
                $today_num_matched = $this->_get_matched_num_today( $tbl_match , $want_id , 1 );

                //每天10条匹配信息
                if( $today_num_matched <= 10)
                {
                    $this->set_table( $tbl_match );//插入数据
                    $insert_id  = $this->add( $data , 'esfhouse' );

                    if( $insert_id > 0 )
                    {
                        //修改求租房源新匹配个数
                        $sql = " UPDATE $tbl_want SET matched_num = matched_num + 1 WHERE id = ".$want_id;
                        $query = $this->db_esfhouse->query($sql);

                        $result['is_ok'] = 1;
                        $result['insert_id'] = $insert_id;
                        $result['msg'] = '匹配房源信息插入成功';
                    }
                    else
                    {
                        $result['is_ok'] = 0;
                        $result['msg'] = '匹配房源信息插入失败';
                    }
                }
                else
                {
                    $result['is_ok'] = 2;
                    $result['msg'] = '今日个人匹配已达到上限';
                }
            }
            else
            {
                $result['is_ok'] = 3;
                $result['msg'] = '匹配信息已经存在';
            }
        }

        return $result;
    }


    /**
    * 判断某条求购求租的匹配信息是否已经存在
    * @param string $tbl_match  房源匹配表(buy/rentwant)
    * @param int $want_id   求购求租信息编号
    * @param int $want_uid  求购求租用户编号
    * @param int $match_id  匹配房源编号
    * @param int $match_uid 匹配人账号编号
    * @param int $infofrom  匹配房源来源
    * @return boolean       是否已经添加(true-已匹配/false)
    */
    private function _check_is_matched( $tbl_match , $want_id , $want_uid , $match_id , $match_uid , $infofrom = 1)
    {
        $is_matched = false;

        if( $tbl_match != '')
        {
            $where_cond = "want_id = '".$want_id."' AND match_id = '".$match_id."'
                     AND want_uid = '".$want_uid."' AND match_uid = '".$match_uid."' AND infofrom = '".$infofrom."' ";

            $this->db_esfhouse->where( $where_cond );
            $this->db_esfhouse->from($tbl_match);
            $total_num  = $this->db_esfhouse->count_all_results();
            //echo $this->db_esfhousebak->last_query();

            if( $total_num  > 0 )
            {
               $is_matched = true;
            }
        }

        return $is_matched;
    }


    /**
    * 获得某条求购求租房源已匹配的个数
    * @param string $tbl_match  房源匹配表(buy/rentwanted)
    * @param int $want_id   求购求租信息编号
    * @param int $infofrom  匹配房源来源
    * @return boolean       是否已经添加(true-已匹配/false)
    */
    private function _get_matched_num_today( $tbl_match , $want_id , $infofrom = '')
    {
        $total_num  = 0;

        if( $tbl_match != '')
        {
            $where_cond = "want_id = '".$want_id."' ";

            if( intval($infofrom) > 0 )
            {
                $where_cond .= " AND infofrom = '".$infofrom."' ";
            }

            //$where_cond .= " AND esta = 0 ";

            $this->db_esfhouse->where( $where_cond );
            $this->db_esfhouse->from( $tbl_match );
            $total_num  = $this->db_esfhouse->count_all_results();
            //echo $this->db_esfhousebak->last_query();
        }

        return $total_num;
    }


    /**
    * 获取昨日新增个人有效房源
    * @param string $tbl  房源表('sell','rent')
    * @return int   新发布个数
    */
    function get_personal_house_num_yesterday($tbl)
    {
        $total_num = 0;
        if( in_array( $tbl , array('sell','rent') ) )
        {
            $yesterday = date('Y-m-d' , strtotime('-1 day'));
            $yesterday_time  = strtotime($yesterday);
            $yesterday_time_end = $yesterday_time + 86400;

            $sql = "SELECT id FROM $tbl";
            $where_cond = " WHERE esta = '1' AND infofrom = '1' AND creattime >= '".$yesterday_time."'
                            AND creattime <= '".$yesterday_time_end."' luc";

            if( $tbl == 'sell')
            {
                $total_info = $this->server_sell->query( $sql . $where_cond);
            }
            else if( $tbl == 'rent')
            {
                $total_info = $this->server_rent->query( $sql . $where_cond);
            }

            if( isset($total_info['TOTAL']) )
            {
                $total_num = intval($total_info['TOTAL']);
            }
        }

        return $total_num;
    }


    /**
    * 获取昨日新增个人有效房源
    * @param string $tbl  房源表('sell','rent')
    * @param string $offset 偏移量
    * @param string $limit  每次显示个数
    * @param string $order  排序
    * @return array 新发布房源数组
    */
    function get_personal_house_yesterday( $tbl , $offset , $limit , $order = 'desc' )
    {
        $houseinfo = array();

        if( in_array( $tbl , array('sell','rent') ) )
        {
            $yesterday = date('Y-m-d' , strtotime('-1 day'));
            $yesterday_time  = strtotime($yesterday);
            $yesterday_time_end = $yesterday_time + 86400;

            $where_cond = " WHERE esta = '1' AND infofrom = '1' AND creattime >= '".$yesterday_time."'
                            AND creattime <= '".$yesterday_time_end."' ";
            $order_cond =  " ORDER BY creattime " . $order ;
            $limit_cond =  " LIMIT ". $offset .",". $limit;

            if( $tbl == 'sell')
            {
                $sql = "SELECT id,uid,infotype,streetid,buildarea,price,buildyear FROM $tbl";
                $record_info = $this->server_sell->query( $sql . $where_cond . $order_cond . $limit_cond .' luc');
            }
            else if( $tbl == 'rent')
            {
                $sql = "SELECT id,uid,infotype,streetid,buildarea,price,renttype FROM $tbl";
                $record_info = $this->server_rent->query( $sql . $where_cond . $order_cond . $limit_cond .' luc');
            }

            if( isset($record_info['TOTAL']) && isset($record_info['Record']) )
            {
                $houseinfo = $record_info['Record'];
            }
        }

        return $houseinfo;
    }


    /**
    * 获取房源符合哪些求购信息
    * @param string $infotype  房源信息
    * @param string $streetid  板块
    * @param string $buildarea 建筑面积
    * @param string $price 价格
    * @param string $buildyear 建筑年代
    * @return array 符合条件的个人求购房源
    */
    function get_buy_want_by_house ( $infotype , $streetid , $buildarea , $price , $buildyear , $order ='asc')
    {
        $tbl_want = 'buy';
        $nowtime = time();

        if( $tbl_want != '')
        {
           $where_cond = "esta = '1' AND allow_match = '1' AND expiretime > '".$nowtime."' AND
                    infofrom IN ('0','1') AND infotype = '".$infotype."' AND( street = '".$streetid."' OR  street1 = '".$streetid."' OR street2 = '".$streetid."' ) AND   buildarea1*0.9 <= '".$buildarea."' AND buildarea2 >= '".$buildarea."' AND price1*0.9 <= '".$price."' AND price2 >= '".$price."' AND buildyear1 <= '".$buildyear."' AND buildyear2 >= '".$buildyear."'";

            $this->db_esfhousebak->select('id , uid ,address');
            $this->db_esfhousebak->where($where_cond);
            $this->db_esfhousebak->order_by( 'creattime' , $order );
            $arr_data = $this->db_esfhousebak->get($tbl_want)->result_array();
        }

        return $arr_data;
    }


    /**
    * 获取房源符合哪些求租信息
    * @param string $infotype  房源信息
    * @param string $streetid  板块
    * @param string $buildarea 建筑面积
    * @param string $price 价格
    * @param string $renttype 建筑年代
    * @return array 符合条件的个人求购房源
    */
    function get_rent_want_by_house( $infotype , $streetid , $buildarea , $price , $renttype , $order ='asc')
    {
        $tbl_want = 'rentwanted';
        $nowtime = time();

        if( $tbl_want != '')
        {
           $where_cond = "esta = '1' AND allow_match = '1' AND expiretime > '".$nowtime."' AND
                    infofrom IN ('0','1') AND infotype = '".$infotype."' AND( street = '".$streetid."' OR street1 = '".$streetid."' OR street2 = '".$streetid."' ) AND buildarea1*0.9 <= '".$buildarea."' AND buildarea2 >= '".$buildarea."' AND price1*0.9 <= '".$price."' AND price2 >= '".$price."' AND renttype = '".$renttype."' ";

            $this->db_esfhousebak->select('id , uid , address');
            $this->db_esfhousebak->where($where_cond);
            $this->db_esfhousebak->order_by( 'creattime' , $order );
            $arr_data = $this->db_esfhousebak->get($tbl_want)->result_array();
        }
        return $arr_data;
    }

    /**
    * 失效过期的求购/求租房源
    * @param void
    * @return array 符合条件的个人求购房源
    */
    function invalid_buy_rentwanted_info( $tbl )
    {
       $now_time = time();

       if( isset ( $tbl ) && in_array( $tbl , array('buy' , 'rentwanted')) )
       {
            $sql = "UPDATE $tbl SET esta = 2 WHERE expiretime <= '".$now_time."' AND esta IN (0,1)";
            $result = $this->db_esfhouse->query($sql);
       }

       if( $result )
       {
            $result['is_ok'] = 1;
            $result['msg'] = '更新完成';
       }
       else
       {
            $result['is_ok'] = 0;
            $result['msg'] = '更新失败';
       }

       return $result;
    }


    /**
     * 更新房源为收费，并更新房源过期时间
     * @param string $tbl
     * @param string $id
     * @return mixed
     */
    function updateHouseCharge( $tbl = '1', $id = '0' )
    {
        $tbl = intval($tbl);
        $id = intval($id);
        $tableArray = array( 1 => 'sell' , 2 => 'rent');
        $tableName = $tableArray[$tbl];
        $addTime = 30 * 24 * 60 * 60;
        $sql = "UPDATE $tableName SET ischarge = '1',expiretime = expiretime + $addTime , lucupdatetime=". time() ." WHERE id = $id";
        $result = $this->db_esfhouse->query($sql);
        return $result;
    }

	/**
	 * 更新房源为收费，并更新房源过期时间 - 租房个人房源
	 * @param $id
	 * @param $days
	 */
	function updatePersonalHouseCharge($id,$days){
		$id = intval($id);
		$days = intval($days);
		if(!$id || !$days) return false;

		$housedetail =  $this->get_data(array('form_name' => 'rent','where'=>array('id'=>$id,'infofrom'=>'1'),'select'=>array('expiretime')),'esfhouse');
		if(!$housedetail) return false;
		$housedetail = $housedetail[0];

		$expiretime = 0;

		$expiretime_ = time() + $days * 24 * 60 * 60;
		if($expiretime_ > $housedetail['expiretime']){
			$expiretime = $expiretime_;
		}

		$edit = array('ischarge'=>'1','lucupdatetime'=>time());
		if($expiretime > 0){
			$edit['expiretime'] = $expiretime;
		}
		$this->set_table('rent');
		$result = $this->save(array('id'=>$id),$edit,'esfhouse');
		return $result;
	}

	/**
	 * 房源详情
	 * @param $house_id
	 * @param array $fields
	 * @return array
	 */
	function getHouse($house_id,$fields=array()){
		$fields = $fields ? $fields : array('infofrom');
		$housedetail = $this->get_data(array('form_name' => 'rent', 'where' => array('id' => $house_id), 'select' => $fields), 'esfhouse');
		return empty($housedetail) ? array() : $housedetail[0];
	}

}