<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * zsb
 *
 * 求购匹配类
 *
 * @package         zsb
 * @author          EllisLab Dev Team
 * @copyright      Copyright (c) 2006 - 2014, HOUSE365, Inc.
 * @link            http://nj.sell.house.com
 * @since           Version 1.0
 */

// ------------------------------------------------------------------------

/**
 * Sell_match_base_model CLASS
 *
 * 出售多图管理类
 *
 * @package         zsb
 * @subpackage      Models
 * @category        Models
 * @author          xz
 */
//加载父类
load_m("sell_attr_model");

class Sell_real_base_model extends Sell_attr_model {
    
    /**
     * Real房标识对应值
     * @var const
     */
    const  ISREAL_VALUE = 1;
    
    /**
     * 每日申请次数上限
     * @var const
     */
    const  APPLY_LIMIT = 4;

	 /**
     * 每日申请成功次数
     * @var const
     */
    const  REAL_LIMIT = 2;
    
    /**
     * real房源记录表
     * @var const
     */
    const  REAL_TBL = 'house_real';
    
    /**
     * real房源图片表
     * @var const
     */
    const  REAL_PIC_TBL = 'house_real_pic';
    
    /**
     * real房房产证编号
     * @var private
     */
    private  $_pic_title = '';
    
    /**
     * real房房产证URL地址
     * @var private
     */
    private  $_pic_url = '';
    
    /**
     * real房委托协议图片地址数组
     * @var const
     */
    private  $_real_pics = array();
	
	/**
	 * 缓存标识
	 * @var private
	 */
	private  $_mem_key;
    
    /**
     * 类初始化
     */
    public function __construct() 
    {
        parent::__construct();
		//var_dump($this->dbback);exit();

		$this->_mem_key = GB_CITY.'sell_real_base_model';
    }
    
    
    /**
     * 获取REAL房标签对应值
     *
     * @access	public
     * @param	string $rowid 房源编号
     * @return	void
     */
    public function get_isreal_value()
    {
        return self::ISREAL_VALUE;
    }
    
    /**
     * 获取REAL房标签一天最多设置的次数
     *
     * @access	public
     * @param	string $rowid 房源编号
     * @return	void
     */
    public function get_today_apply_num() 
    {
        return self::APPLY_LIMIT;
    }
    
    /**
     * 设置REAL房房产证编号
     *
     * @access	public
     * @param	string $rowid 房源编号
     * @return	void
     */
    public function set_pic_title( $pic_title )
    {
        $this->_pic_title = strip_tags( $pic_title );
    }
    
    
    /**
     * 获取REAL房房产证编号
     *
     * @access	public
     * @return	string 房产证编号
     */
    public function get_pic_title()
    {
        return $this->_pic_title;
    }
    
    
    /**
     * 设置房产证图片地址
     *
     * @access	public
     * @param	string $pic_url 图片URL
     * @return	void
     */
    public function set_pic_url( $pic_url )
    {
        $this->_pic_url = strip_tags( $pic_url );
    }
    
    
    /**
     * 获取REAL房房产证地址
     *
     * @access	public
     * @return	string REAL房房产证地址
     */
    public function get_pic_url()
    {
        return $this->_pic_url;
    }
    
    
    /**
     * 设置委托协议图片URL数组
     *
     * @access	public
     * @param	array $pic_array 房源图片数组
     * @return	void
     */
    public function set_real_pics( $pic_array )
    {
        $this->_real_pics = $pic_array;
    }
    
    
    /**
     * 获取房源委托协议图片URL数组
     *
     * @access	public
     * @return	array 房源委托协议图片URL数组
     */
    public function get_real_pics()
    {
        return $this->_real_pics ;
    }
    
    /**
     * 判断房源是否为Real房源
     *
     * @access	public
     * @return	boolean  是否为Real房源
     */
    public function is_real()
    {
        $is_real = FALSE;
        
        $house_info = $this->init_houseinfo();
        
        if( is_array( $house_info ) && !empty( $house_info ) )
        {
            $is_real = self::ISREAL_VALUE == $house_info['isreal'] 
                    ? TRUE : FALSE;
        }
        
        return $is_real;
    }
    
    
    /**
     * 设置Real房源
     *
     * @access  protected
     * @return  boolean  是否设置成功
     */
    public function set_real()
    {   
        $result = FALSE;
        
        $house_info = $this->init_houseinfo();
        $rowid = intval($house_info['id']);
        $uid = intval($house_info['uid']);

        if( $rowid > 0 && $uid > 0)
        {   
            $result_add = 0;
            //加载经纪人信息
            $this->load->model('broker_model');
            $this->broker_model->set_uid($uid);
            $broker_info = $this->broker_model->get_broker_info();
            
            //判断用户是否为REAL房认证用户，如果不是要判断是否上传房产证或者委托书
            if( $broker_info['isreal'] == 1 || ( /**$this->_pic_title != '' && **/ $this->_pic_url != '') 
                    || (is_array($this->_real_pics) && !empty($this->_real_pics)) )
            {
                //添加Real房记录
				if($broker_info['isreal'] == 1)
				{
					$result_add = $this->_add_real_record( $rowid ,$broker_info['truename'] ,$broker_info['username'] , $uid,
                    $house_info['telno'] ,$house_info['price'] ,$house_info['buildarea'] ,$house_info['blockshowname'],1);
				}
				else
				{
					$result_add = $this->_add_real_record( $rowid ,$broker_info['truename'] ,$broker_info['username'] , $uid,
                    $house_info['telno'] ,$house_info['price'] ,$house_info['buildarea'] ,$house_info['blockshowname']);
				}
            }
            else
            {
                return $result;
            }
            
            //判断房源是否已经存在REAL房图片记录，如果有记录就删除
            $cond_where = "rowid = $rowid";
            $pic_num = $this->get_house_real_pic_num($cond_where);

            if( $pic_num > 0 )
            {   
                $this->delete_real_pic ( $rowid );
            }
            
            //通过上传房产证或者买卖契约来更新REAL房状态
            if( /**$this->_pic_title != '' &&**/ $this->_pic_url != '' && $result_add > 0)
            {   
                //添加房产证
                $result_add_pic = $this->_add_pic_rel( $rowid , $this->_pic_title , $this->_pic_url , 1);
                
                if( $result_add_pic )
                {   
                    $update_info = array();
                    $update_info['is_rel'] = 1; 
                    $cond_where = "id = $rowid AND real_esta IN ( 0 , 1 , 4 , 5 )";
                    $this->update_house_real( $update_info , $cond_where);
                }
            }
            else if( is_array($this->_real_pics) && !empty($this->_real_pics) && $result_add > 0 )
            {   
                //添加买卖契约
                $pic_num = count($this->_real_pics);
                for($i = 0 ; $i < $pic_num ; $i ++  )
                {
                    $result_add_pic = $this->_add_pic_rel($rowid , '' , $this->_real_pics[$i] , 2);
                    if( $result_add_pic )
                    {   
                        $update_info = array();
                        $update_info['is_contract'] = 1; 
                        $cond_where = "id = $rowid AND real_esta IN ( 0 , 1 , 4 , 5 )";
                        $this->update_house_real( $update_info , $cond_where);
                    }
                }
            }

            if( $result_add > 0)
            {
                $update_info = array();
            
                //需要设置的房源属性值
                $update_info['isreal'] = self::ISREAL_VALUE;
            
                //设置多图房源
                $result = $this->update_house_atrr_val( $update_info , $rowid );

				//清除REAL房个数缓存
				$this->get_real_num_by_uid($uid , 1);
				$this->apply_real_num_today($uid , 1);
            }
        }
        
        return $result;
    }
    
    
    /**
     * 取消Real房源标签
     *
     * @access  protected
     * @return  boolean  是否取消成功
     */
    public function remove_real()
    {   
        $result = FALSE;
        
        $house_info = $this->init_houseinfo();
        $rowid = intval($house_info['id']);
		$uid = intval($houseinfo['uid']);
        
        if( $rowid > 0 )
        {   
			$update_info = array();

			//需要设置的房源属性值
			$update_info['isreal'] = 0;

			//取消Real房属性
			$result = $this->update_house_atrr_val( $update_info , $rowid );
            
            if( $result === TRUE )
            {   
				//失效REAL房记录
				$result_invalid = $this->_invalid_real_by_rowid($rowid,7);

				//清除REAL房个数缓存
				$this->get_real_num_by_uid($uid , 1);
				$this->apply_real_num_today($uid , 1);
            }
        }
        
        return $result;
    }
    
    
    /**
     * 检测房源是否符合Real房源的标准
     *
     * @access  protected
     * @return  boolean  是否符合Real房源的标准
     */
    public function check_real_standard()
    {   
        //房源信息
        $houseinfo = $this->init_houseinfo();
        $result = array();
        $uid = intval($houseinfo['uid']);
        $this->load->model('broker_model');
        $this->broker_model->set_uid($uid);
        $broker_info = $this->broker_model->get_broker_info();
        
        /*** 经纪人不能再黑名单 ***/
        if( is_array( $broker_info ) && !empty( $broker_info ) )
        {   
            if(isset($broker_info['festa']) && $broker_info['festa'] == 1 )
            {
                //冻结状态
                $result['is_ok'] = 0;
                $result['msg'] = '经纪人在黑名单中，无法设置标签房源';
                return  $result;
            }
        }
        else
        {
            //经纪人信息为空
            $result['is_ok'] = 0;
            $result['msg'] = '经纪人信息为空';
            return  $result;
        }
        
        //REAL房已满
        $real_num = 0;
        //$real_limit = intval($broker_info['real_limit']);
        $real_num = $this->get_real_num_by_uid($uid , 1);

        if( $real_num >= self::REAL_LIMIT)
        {
            $result['is_ok'] = 0;
            $result['msg'] = 'REAL房已满';
            return  $result;
        }
        
        //当日申请次数已满
        $apply_real_num = 0;
        $apply_real_num = $this->apply_real_num_today($uid , 1);
        if( $apply_real_num >= self::APPLY_LIMIT)
        {
            $result['is_ok'] = 0;
            $result['msg'] = '当日Real房申请次数已满';
            return  $result;
        }
        
        /*** 非多图房源不可设为REAL房 ***/
        $this->load->model('sell_star_base_model');
        $isstar_value = $this->sell_star_base_model->get_isstar_value();
        if( $houseinfo['isstar'] != $isstar_value )
        {
            $result['is_ok'] = 0;
            $result['msg'] = '非多图房源不可设为REAL房';
            return  $result;
        }
        
        /** 已设置新房直售 **/
        $this->load->model('sell_nofee_base_model');
        $isstar_value = $this->sell_nofee_base_model->get_nofee_value();
        if($houseinfo['nofee'] == 1)
        {
            //新房房源
            $result['is_ok'] = 0;
            $result['msg'] = '已设置新房直售';
            return  $result; 
        }
        
        //非有效状态
        if( $houseinfo['esta'] != 1 )
        {
            $result['is_ok'] = 0;
            $result['msg'] = '房源非激活状态，无法设置REAL房';
            return  $result;
        }
        
        $result['is_ok'] = 1;
        $result['msg'] = '设置REAL房';
        
        return $result;
    }


	  /**
     * 检测房源是否符合Real房源的标准(列表页专用)
     *
     * @access  protected
     * @return  boolean  是否符合Real房源的标准
     */
    public function check_real_standard_list($real_num,$real_today_num)
    {   
        //房源信息
        $houseinfo = $this->init_houseinfo();
        $result = array();
        $uid = intval($houseinfo['uid']);
        $this->load->model('broker_model');
        $this->broker_model->set_uid($uid);
        $broker_info = $this->broker_model->get_broker_info();
        
        /*** 经纪人不能再黑名单 ***/
        if( is_array( $broker_info ) && !empty( $broker_info ) )
        {   
            if(isset($broker_info['festa']) && $broker_info['festa'] == 1 )
            {
                //冻结状态
                $result['is_ok'] = 0;
                $result['msg'] = '经纪人在黑名单中，无法设置标签房源';
                return  $result;
            }
        }
        else
        {
            //经纪人信息为空
            $result['is_ok'] = 0;
            $result['msg'] = '经纪人信息为空';
            return  $result;
        }
        
        //REAL房已满
        $real_num = 0;
        //$real_limit = intval($broker_info['real_limit']);
        $real_num = $real_num;

        if( $real_num >= self::REAL_LIMIT)
        {
            $result['is_ok'] = 0;
            $result['msg'] = 'REAL房已满';
            return  $result;
        }
        
        //当日申请次数已满
        $apply_real_num = 0;
        $apply_real_num = $real_today_num;
        if( $apply_real_num >= self::APPLY_LIMIT)
        {
            $result['is_ok'] = 0;
            $result['msg'] = '当日Real房申请次数已满';
            return  $result;
        }
        
        /*** 非多图房源不可设为REAL房 ***/
        $this->load->model('sell_star_base_model');
        $isstar_value = $this->sell_star_base_model->get_isstar_value();
        if( $houseinfo['isstar'] != $isstar_value )
        {
            $result['is_ok'] = 0;
            $result['msg'] = '非多图房源不可设为REAL房';
            return  $result;
        }
        
        /** 已设置新房直售 **/
        $this->load->model('sell_nofee_base_model');
        $isstar_value = $this->sell_nofee_base_model->get_nofee_value();
        if($houseinfo['nofee'] == 1)
        {
            //新房房源
            $result['is_ok'] = 0;
            $result['msg'] = '已设置新房直售';
            return  $result; 
        }
        
        //非有效状态
        if( $houseinfo['esta'] != 1 )
        {
            $result['is_ok'] = 0;
            $result['msg'] = '房源非激活状态，无法设置REAL房';
            return  $result;
        }
        
        $result['is_ok'] = 1;
        $result['msg'] = '设置REAL房';
        
        return $result;
    }
    
    
    
    /**
     * 根据条件查到Real房记录条数(add 2014/9/10)
     *
     * @access  protected
     * @param   string $cond_where 查询条件
	 * @param   int $force_db 0、从库查询 1、强制走主库查询 
     * @return  boolean  是否符合Real房源的标准
     */
    public function get_real_num_by_cond($cond_where , $force_db = 0)
    {
        $real_num = 0;
       
        if( $cond_where != '')
        {	
			$mem_key = $this->_mem_key.'_get_real_num_by_cond_'.$cond_where.'_'.$force_db;
			if( $force_db == 1 )
            {
                $this->mc->delete($mem_key);
            }
			$cache = $this->mc->get($mem_key);

            if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
            {
                $real_num = $cache['data'];
            }
            else
            {	
				if($force_db == 1)
				{
					$this->db->where($cond_where);
					$real_num = $this->db->count_all_results(self::REAL_TBL);
				}
				else
				{
					$this->dbback->where($cond_where);
					$real_num = $this->dbback->count_all_results(self::REAL_TBL);	
				}

				$this->mc->add($mem_key, array('is_ok'=>1,'data'=>$real_num), 30);
			}
        }
        
        return $real_num;
    }
    
    
    /**
     * 根据UID查询待审核和通过的审核的REAL房个数
     *
     * @access  public
     * @param   int  $uid 经纪人编号
     * @param   int  $update_cache 清除缓存标识
     * @return  boolean  待审核和通过的审核的REAL房个数
     */
    public function get_real_num_by_uid($uid, $update_cache = 0)
    {   
        $real_num = 0;

        if( $uid > 0 )
        {
            $mem_key = $this->_mem_key.'_get_real_num_by_uid_'.$uid;
            if( $update_cache == 1 )
            {
                $this->mc->delete($mem_key);
            }
            $cache = $this->mc->get($mem_key);

            if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
            {
                $real_num = $cache['data'];
            }
            else
            {
                $cond_where = "uid = '".$uid."' AND real_esta IN (0,1)";
                $real_num = $this->get_real_num_by_cond($cond_where , 1);
                $this->mc->add($mem_key, array('is_ok'=>1,'data'=>$real_num), 30);
            }
        }
        
        return $real_num;
    }
    
    
    /**
     * 当日REAL房申请次数
     *
     * @access  public
     * @param   int  $uid 经纪人编号
     * @param   int  $update_cache 清除缓存标识
     * @return  boolean  当日REAL房申请次数
     */
    public function apply_real_num_today( $uid , $update_cache = 0)
    {   
        $today_apply_num = 0;

        if( $uid > 0 )
        {	
            $starttime = strtotime(date('Y-m-d 00:00:00'));
            $endtime = strtotime(date('Y-m-d 23:59:59'));

            $mem_key = $this->_mem_key.'_apply_real_num_today_'.$uid.'_'.$starttime.'_'.$endtime;
            if( $update_cache == 1 )
            {
                $this->mc->delete($mem_key);
            }
            $cache = $this->mc->get($mem_key);

            if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
            {
                $today_apply_num = $cache['data'];
            }
            else
            {
                $cond_where = "uid ='".$uid."' AND createtime >= '".$starttime."' AND createtime <= '".$endtime."' ";
                $today_apply_num = $this->get_real_num_by_cond( $cond_where , 1);

                $this->mc->add($mem_key, array('is_ok'=>1,'data'=>$today_apply_num),  300);
            }
        }
        
        return $today_apply_num;
    }
    
    /**
     * 添加REAL房记录
     *
     * @access  public
     * @param   int  $uid 经纪人编号
     * @return  boolean  操作是否成功
     */
    private function _add_real_record( $rowid ,$truename ,$username , $uid ,
            $telno ,$price , $buildarea ,$blockshowname,$real_esta = 0)
    {
        $result = 0;
        $time = time();

        $data_info = array();
        $data_info['tbl'] = 'sell';
        $data_info['rowid'] = $rowid;
        $data_info['truename'] = $truename;
        $data_info['username'] = $username;
        $data_info['uid'] = $uid;
        $data_info['telno'] = $telno;
        $data_info['price'] = $price;
        $data_info['buildarea'] = $buildarea;
        $data_info['blockname'] = $blockshowname;
		$data_info['real_esta'] = intval($real_esta);
        $data_info['createtime'] = $time;
        
        $this->db->insert( self::REAL_TBL , $data_info );
        //echo $this->db->last_query();
        $result = ( $this->db->affected_rows() == 1 ) ? $this->db->insert_id() : 0;
        
        return $result;
    }
    
    
    /**
     * 添加房产证记录
     *
     * @access  private
     * @param   int  $rowid 房源编号
     * @param   int  $pic_title 房产证编号
     * @param   int  $pic_url 房产证图片地址
     * @param   int  $kind 图片类型 1-房产证 2、买卖契约
     * @return  int  添加是否成功，成功返回插入ID，失败返回 0 
     */
    private function _add_pic_rel( $rowid , $pic_title , $pic_url , $kind)
    {
        $data_info = array();
        $data_info['tbl'] = 'sell';
        $data_info['rowid'] = $rowid;
        $data_info['kind'] = $kind;
        $data_info['pic_url'] = $pic_url;
        $data_info['pic_title'] = $pic_title;
        $data_info['createtime'] = time();
        $this->db->insert( self::REAL_PIC_TBL , $data_info );
        $result = ( $this->db->affected_rows() == 1 ) ? $this->db->insert_id() : 0;
        
        return $result;
    }
    
    
    /**
     * 失效Real房信息
     * @param int $rowid 房源编号
     * @param int $real_esta 失效状态
     */
    function _invalid_real_by_rowid( $rowid , $real_esta )
    {   
        $result = FALSE;
        
        if( $rowid > 0 )
        {   
            $update_data = array();
            $update_data['real_esta'] = intval($real_esta);
            $update_data['is_rel'] = 0;
            $update_data['is_contract'] = 0;

            $cond_where = "rowid = '".$rowid."' AND tbl = 'sell'";
            $this->db->where($cond_where);
            $this->db->update( self::REAL_TBL, $update_data);
            
            $result = $this->db->affected_rows() > 0 ? TRUE : FALSE;
        }

        return $result;
    }
    
    
    /**
     * 更新REAL房信息
     *
     * @access  private
     * @param   array  $update_info 房源编号
     * @param   string  $cond_where 房产证编号
     * @return  int  更新影响的行数
     */
    public function update_house_real( $update_info , $cond_where )
    {
        $result = 0;

        if(is_array($update_info) && !empty($update_info) && $cond_where != '')
        {   
            $this->db->where($cond_where);
            $this->db->update(self::REAL_TBL, $update_info);
            $result =  $this->db->affected_rows();
        }

        return $result;
    }
    
    
    /**
     * 获取REAL房图片个数
     *
     * @access  private
     * @param   string  $cond_where 查询条件
     * @return  int  图片数量
     */
    public function get_house_real_pic_num ( $cond_where )
    {
        $real_num = 0;
       
        if( $cond_where != '')
        {
            $this->dbback->where($cond_where);
            $real_num = $this->dbback->count_all_results(self::REAL_TBL);
        }
        
        return $real_num;
    }
    
    
    /**
     * 删除REAL房
     *
     * @access  private
     * @param   int  $rowid 房源编号
     * @return  boolean  删除是否成功
     */
    public function delete_real_pic ( $rowid )
    {
        $result = FALSE;
       
        if( $rowid > 0 )
        {   
            $cond_where = "id = $rowid";
            $this->db->where($cond_where);
            $this->db->delete(self::REAL_PIC_TBL);
            
            if ( $this->db->affected_rows() > 0)
            {
                $result = TRUE;
            }
        }
        
        return $result;
    }
}
/* End of file sell_real_base_model.php */
/* Location: ./applications/models/sell_real_base_model.php */