<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * ZSB
 *
 * 经纪人MODEL类
 *
 * @package         ZSB
 * @author          ESF Dev Team
 * @copyright       Copyright (c) 2006 - 2014, HOUSE365, Inc.
 * @link            http://nj.sell.house.com
 * @since           Version 1.0
 */

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

/**
 * 经纪人类
 *
 * 经纪人类文件功能描述
 *
 * @package         zsb
 * @subpackage      Models
 * @category        Models
 * @author          fisher
 */

load_m("Broker_base_model");

class Broker_test_model extends Broker_base_model {
    
    /**
    * 缓存KEY
    *
    * @access private
    * @var string
    */
    private $_mem_key = 'broker_model';

	/**
    * 用户session信息
    *
    * @access private
    * @var array
    */
    public $user_session = array();
    
    /**
    * Constructor
    */
    public function __construct() 
    {
        parent::__construct();
        
		$this->user_session = $this->load->get_var('user_session');
		if(!$this->user_session || $this->user_session['uid'] <= 0){
			//获取SESSION数据并为父属性赋值
			$this->user_session = $this->get_user_session();
			$this->load->vars(array('user_session'=>$this->user_session));
		}

        $this->set_uid($this->user_session['uid']);
    }
    
    
    /**
     * 检查经纪人登陆
     *
     * @access	public
     * @param	string  $username 经纪人账号
     * @param	string  $password 经纪人密码
     * @return	array   经纪人基础信息
     */
    public function login($username, $password, $needencrypt = TRUE)
    {   
        $password = $needencrypt ? $this->encrypt_broker_pwd($password) : $password;
        //查询字段
        $this->dbback->select("uid");
        //查询条件
        $this->dbback->where("username = '".$username."' and password = '".$password."'");
        //查询
        $arr_data = $this->dbback->get('broker')->row_array();
        
        return isset($arr_data['uid']) ? intval($arr_data['uid']) : 0;
    }
    
    
    /**
     * 检查经纪人是否在线
     *
     * @access	public
     * @param	string  $username 经纪人账号
     * @param	string  $password 经纪人密码
     * @return	array   经纪人基础信息
     */
    public function check_online()
    {   
        $u_session = $this->get_user_session();
        
        //在线用户SESSION数据有值且UID大于0
        return isset($u_session['uid']) && intval($u_session['uid']) > 0 ? TRUE : FALSE;
    }


	//设置第二个memcache缓存 xue add 2015-01-14
	private function set_memcache_session($data){
		$key = $this->getSessionId();
		$this->mc->set($key ,$data, 86400);
	}

	//获取第二个memcache缓存 xue add 2015-01-14
	public function get_memcache_session(){
		$key = $this->getSessionId();
		$cache = $this->mc->get($key);
		return $cache;
	}

	//获取sessionId   xue add 2015-01-14
	private function getSessionId(){
		return $this->session->userdata("session_id");
	}

	//删除第二个memcache缓存
	private function deleteSession(){
		$key = $this->getSessionId();
		$this->mc->delete($key);
	}
    
    
    /**
     * 设置用户SESSION数据
     *
     * @access	public
     * @param	array  $session_data 用户数据
     * @return	void
     */
    public function set_user_session($session_data = array())
    {   
        $app_key = $this->get_appkey();
        
        //把用户SESSION数据存在App key内
        $this->session->set_userdata(array($app_key => $session_data));
		//存第二个session		
		$this->set_memcache_session($session_data);

        /*
		//登陆后记录cookie
		$cookie = array(
               'name'   => 'zsb_login_test',
               'value'  => 1,
               'expire' => 1800,    // 设置有效期            
        );
        $this->input->set_cookie($cookie);*/

    }

    /**
     * 重置用户SESSION数据
     *
     * @access	public
     * @return	void
     */
    public function reset_user_session()
    {   
        $app_key = $this->get_appkey();

        $session_data = $this->get_user_session();

        //把用户SESSION数据存在App key内
        $this->session->set_userdata(array($app_key => $session_data));
    }
    
    
    /**
     * 设置用户SESSION数据
     *
     * @access	public
     * @param	void
     * @return	void
     */
    public function logout()
    {   
        $app_key = $this->get_appkey();

        //清空SESSION数据
        $this->session->unset_userdata($app_key);
		//清第二个缓存
		$this->deleteSession();

        //清除身份
        $cookie = array(
               'name'   => 'broker_id',
               'value'  => 0,
               'expire' => 1800,    // 设置一天的有效期            
        );
        $this->input->set_cookie($cookie);
    }
    
    
    /**
     * 设置用户SESSION数据
     *
     * @access	public
     * @return	array   用户SESSION数据
     */
    public function get_user_session()
    {   
		//如果之前已经取过数据，自己返回
		if($this->user_session['uid'] > 0){
			return $this->user_session;
		}

        $app_key = $this->get_appkey();
		$userdata = $this->session->userdata($app_key);



		if($userdata['uid'] <= 0){
			//从备用缓存中取
			$user_arr = $this->get_memcache_session();

			//再次把session存入memcache中
			//把用户SESSION数据存在App key内
			$this->session->set_userdata(array($app_key => $user_arr));

            //把用户SESSION数据存在全局变量内
			$this->load->vars(array('user_session'=>$user_arr));
			$this->user_session = $user_arr;
		 

		   /*
			$num = $this->mc->get('getLostNum_memcache_057');
			$this->mc->set('getLostNum_memcache_057',$num+1,86400);

			if($user_arr['uid']<=0){
				$num2 = $this->mc->get('getLostNum_memcache_type2_098');
				$this->mc->set('getLostNum_memcache_type2_098',$num2+1,86400);
			}


			if($this->input->cookie("zsb_login_test") == 1 ){

				$num3 = $this->mc->get('getLostNum_memcache_8989');
				$this->mc->set('getLostNum_memcache_8989',$num3+1,86400);

				if($user_arr['uid']<=0){
					$num5 = $this->mc->get('getLostNum_memcache_type2_05656');
					$this->mc->set('getLostNum_memcache_type2_05656',$num5+1,86400);
				}
			
			}*/
	
		
		}else{
			$user_arr = $userdata;
		}

		return $user_arr;
    }
    
    
    /**
     * 获取APP KEY
     *
     * @access	public
     * @return	string   APPKEY
     */
    public function get_appkey()
    {
        return USER_SESSION_KEY;
    }
    
    
    /**
     * 获取经纪人所属区属
     *
     * @access	public
     * @return	string   区属
     */
    public function get_broker_district()
    {   
        $user_info = $this->get_user_session();
        $arr_data = array();
        
        //已挂靠门店的经纪人
        if('A2467' != $user_info['agentcode'] && '' != $user_info['agentcode'])
        {
            //查询字段
            $this->dbback->select('dist');
            //查询条件
            $this->dbback->where("agentcode = '".$user_info['agentcode']."'");
            //查询
            $arr_data = $this->dbback->get('agency')->row_array();
        }
        
        //门店未设定区属或未独立经纪人
        if(empty($arr_data) OR 'A2467' == $user_info['agentcode'] OR '' == $user_info['agentcode'])
        {
            //查询字段
            $this->dbback->select('dist');
            //查询条件
            $this->dbback->where("uid = '".$user_info['uid']."'");
            //查询
            $arr_data = $this->dbback->get('broker')->row_array();
        }
        
        return $arr_data['dist'];
    }
    
    
    /**
     * 检查经纪人登陆
     * @access	public
     * @param	array   $data 日志数据
     * @param	string  $tbl 日志表名
     * @return	array   经纪人基础信息
     */
    public function get_broker_company()
    {   
        $user_arr = $this->get_user_session();
        
        $arr_data = array();
        
        if( '' != $user_arr['agentcode'])
        {   
            $this->load->model('agency_model');
            $select_field = array("agentshortname");
            $this->agency_model->set_select_fields($select_field);
            $arr_data = $this->agency_model->get_company_info_by_code($user_arr['agentcode']);
        }
        
        return $arr_data;
    }
    

    
    /**
     * 获取经纪人客户经理
     * @param string $master 客户经理帐号
     * @return string
     */
    public function get_account_manager($master)
    {
        $mem_key = $this->_mem_key.'_get_account_manager_'.$master;
        //$this->mc->delete($mem_key);
        $cache = $this->mc->get($mem_key);
        
        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $arr_data = $cache['data'];
        }
        else
        {
            //查询字段
            $this->db->select("truename,telno");
            //查询条件
            $this->db->where("authname = '".$master."'");
            //print_r($this->dbback);
            //查询
            $arr_data = $this->db->get('home_auth')->row_array();
            $this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$arr_data) ,  86400);
        }
        
        return $arr_data;
    }
    
    
    /*
     * 短信找密码次数
     * @access public 
     * @param string $telno 电话号码
     * @return int 次数
     */
    public function get_findpwd_count($telno)
    {
        $count_num = 0;
        
        $daytime = strtotime(date('Y-m-d'));
        $cond_where = "mobile = '".$telno."' AND tbl='broker' AND dateline > $daytime ";
        $this->dbback->where($cond_where);
        $count_num = $this->dbback->from('info_sms')->count_all_results();
        
        return $count_num;
    }
    
    
    /**
     * get_lastst_sms
     * 查找最近短信记录
     * @access  public
     * @param string $telno 电话号码
     * @return array 最新一条记录数组
     */
    public function get_lastst_sms($telno)
    {
        //查询字段
        $this->dbback->select('id,rowid,validcode,mobile,dateline');
        $cond_where = "mobile = '".$telno."' and valid_flag='1' order by id desc ";
        $this->dbback->where( $cond_where );
        $arr_data = $this->dbback->get('info_sms')->row_array();
        
        return $arr_data;
    }
    
    
    /**
     * 验证码是否过期
     * @access public
     * @param string $dateline 时间戳
     * @return Boolean 是否过期
     */
    public function is_expire_code($dateline){
        $timelimit = time() - 1800;
        $result = $dateline > $timelimit ? TRUE : FALSE;
        return $result;
    }
    
    
    /**
     * update_broker_pwd
     * 更新经纪人默认密码
     * @access public
     * @param string $brokerid
     * return void
     */
    public function update_broker_pwd($brokerid){
        $newpwd = md5('111111');
	$this->db->where('uid',$brokerid);	
	$this->db->update("broker", array("password"=>$newpwd));
    }
    
    
    /**
     * 更新验证码标志位
     * @access public
     * @param int smsid
     * @return void
     */
    public function update_sms_flag($smsid)
    {
        $this->db->where('id',$smsid);	
	$this->db->update("info_sms", array("valid_flag"=>0));
    }
    
    
    /**
     * 获取经纪人的有效房源量
     * @param string $type 参数类型，默认获取出售和出租之和
     * type = sell 出售有效量 rent = rent 出租有效量
     * @return int
     */
    public function valid_house_num($type = '')
    {
        $user_arr = $this->get_user_session();
        $valid_num = 0;
        
        if ($type == 'sell' || $type == '')
        {
            $this->load->model('sell_model');
            $sell_valid = $this->sell_model->valid_house_num($user_arr['uid']);
            $valid_num += $sell_valid;
        }
        
        if ($type == 'rent' || $type == '')
        {
            $this->load->model('rent_model');
            $rent_valid = $this->rent_model->valid_house_num($user_arr['uid']);
            $valid_num += $rent_valid;
        }
        
        return $valid_num;
    }
    
    
    /**
     * 获取经纪人的有效房源量
     * @param string $type 参数类型，默认获取出售和出租之和
     * type = sell 出售有效量 rent = rent 出租有效量
     * @return int
     */
    public function stock_house_num($type = '')
    {
        $user_arr = $this->get_user_session();
        $stock_num = 0;
        if ($type == 'sell' || $type == '')
        {
            $this->load->model('sell_model');
            $sell_stock = $this->sell_model->stock_house_num($user_arr['uid']);
            $stock_num += $sell_stock;
        }
        
        if ($type == 'rent' || $type == '')
        {
            $this->load->model('rent_model');
            $rent_stock = $this->rent_model->stock_house_num($user_arr['uid']);
            $stock_num += $rent_stock;
        }
        
        return $stock_num;
    }
    
    
    /**
     * 认证查询
     * @param string $type 认证类型 参数类型:headcard 头像认证, 
     *                      idcard 身份认证 ，buscard 名片认证，occup 职业认证 
     * @param int $uid 用户id
     * @return array
     */
    public function get_certificate_info($type,$uid)
    {
        switch ($type)
        {
            case 'headcard' : 
                $cond_kind = "kind='p_1'";
                break;
            case 'idcard' : 
                $cond_kind = "kind='p_2'";
                break;
            case 'buscard' : 
                $cond_kind = "kind='p_3'";
                break;
            case 'occup' : 
                $cond_kind = "kind in('p_4_1','p_4_2')";
                break;            
        }
        
       $cond_where = "uid = '".$uid."' and $cond_kind";
       $this->db->where($cond_where);
       $this->db->order_by('id','desc');
       $data_arr = $this->db->select('valid_flag,pic1')->get('broker_certificate')->row_array();
       return $data_arr;        
    }
    
    
    /**
     * 认证审核
     * @param int $uid
     * @param string $type 认证类型
     * @param int $current_stats 当前状态
     * @param int $check_stats 审核后状态
     * @param string $reason 原因
     * @return void
     */
    public function check_certificate($uid,$type,$current_stats=0,$check_stats=1,$reason='')
    {
        $where_cond['uid'] = $uid;
        $where_cond['valid_flag'] = $current_stats;
        $where_cond['kind'] = $type;
        $this->db->where($where_cond);
        $updata_data['valid_flag'] = $check_stats;
        $updata_data['reason'] = $reason;
        $this->db->update('broker_certificate',$updata_data);        
    }
    
    
    /**
     * 上传认证审核添加
     * @param int $uid 用户id
     * @param string  $type 上传类型
     * @param string $picurl 图片地址
     * @return void
     */
    public function add_certificate($uid,$type,$picurl)
    {
        $insert_data = array();
        
        $insert_data['uid'] = $uid;
        $insert_data['kind'] = $type;
        $insert_data['valid_flag'] = 0;
        $insert_data['indate'] = date('Y-m-d H:i');
        $insert_data['pic1'] = $picurl;
        
        $this->db->insert('broker_certificate',$insert_data);
        $insert_id = $this->db->insert_id();
        
	return $insert_id;
    }
    
    
    /**
     * 个人资料当天更换手机号码的次数
     * @param int $uid 用户ID
     * @return int 次数
     */
    public function change_phone_num($uid)
    {
        $starttime  = strtotime(date('Y-m-d',time())."00:00:00");
	$endtime   = strtotime(date('Y-m-d',time())."23:59:59");
        
        $where_cond['uid'] = $uid;
        $where_cond['valid_flag'] = 0;
        $where_cond['dateline >'] = $starttime;
        $where_cond['dateline <'] = $endtime;
        
        $this->dbback->where($where_cond);
        $this->dbback->from('broker_certifycode');
        $num = $this->dbback->count_all_results();
        
        return $num;
    }
    
    
    /**
     * 个人资料获取验证码次数
     * get_certifycode_num
     * @param int $uid 用户id
     * @return int 次数
     */
    public function get_certifycode_num($uid)
    {
        $starttime  = strtotime(date('Y-m-d',time())."00:00:00");
	$endtime   = strtotime(date('Y-m-d',time())."23:59:59");
        
        $where_cond['uid'] = $uid;        
        $where_cond['dateline >'] = $starttime;
        $where_cond['dateline <'] = $endtime;
        
        $this->dbback->where($where_cond);
        $this->dbback->from('broker_certifycode');
        $num = $this->dbback->count_all_results();
        
        return $num;
    }
    
    
    /**
     * 查看60S内是否已经获取验证码
     * @param int $uid 用户id
     * @param int $mobile 手机号
     * @return int 次数
     */
    public function is_get_certifycode($mobile)
    {
        $nowtime = time() - 59;         
        $where_cond['mobile'] = $mobile;
        $where_cond['dateline >='] = $nowtime;
        
        $this->dbback->where($where_cond);
        $this->dbback->from('broker_certifycode');
        $num = $this->dbback->count_all_results();
        
        return $num;
    }
    
    
    /**
     * 插入经纪人验证记录
     * @param int $uid 用户id
     * @param int $mobile 手机号
     * @param int $certifycode 验证码
     * @return void
     */
    public function add_certifycode($uid,$mobile,$certifycode)
    {      
        $insert_data = array();
        
        $insert_data['uid'] = $uid;
        $insert_data['validcode'] = $certifycode;
        $insert_data['mobile']	= $mobile;
        $insert_data['type'] = "user_mod";
        $insert_data['intime']	= date("Y-m-d H:i:s",time());
        $insert_data['dateline'] = time();
        
        $this->db->insert('broker_certifycode',$insert_data);	
        
        return $this->db->insert_id();
    }
    
    
    /**
     * 查出3分钟内修改手机的验证码
     * @param int $uid 用户id
     * @param int $mobile 用户手机号
     * @return array
     */
    public function get_certifycode($uid,$mobile)
    {
        $tbl ='broker_certifycode';
        $timelimit = time() - 180;
        
        $where_cond ['uid'] = $uid;
        $where_cond ['mobile'] = $mobile;
        $where_cond ['valid_flag'] = 1;
        $where_cond ['dateline >'] = $timelimit;
        
        $this->dbback->where($where_cond);
        $data_arr = $this->dbback->select('id,validcode,mobile')->order_by('id','desc')->get($tbl)->row_array();
        
        return $data_arr;
    }
    
    
    /**
     * 验证成功后修改状态
     * @param int $id
     * @return void
     */
    public function update_certifycode($id)
    {
        $tbl ='broker_certifycode';
        
        $this->db->where('id',$id);
        $update_arr['valid_flag']= 0;
        $update_arr['dateline'] = time();
        
        $this->db->update($tbl,$update_arr);
    }
    
    
    /**
     * 经纪人是否当天生日
     */
    public function is_brithday()
    {
        $u_session = $this->get_user_session();
        $birthday = date('md', time());
        
        //查询条件
        $this->dbback->where("uid = ".$u_session['uid']." and valid_flag =1  AND  substring( idno, 11, 4 ) = $birthday");
        //查询
        $count_num = $this->dbback->from('broker')->count_all_results(); 
        
        return  $count_num > 0 ? TRUE :FALSE;           
    }


	 /*
     * 获取需要屏蔽的公司code
     *  prohibit_company
     * return array
     */
    public function prohibit_company($pcompany_code){
        $mem_key = $this->_mem_key.'_get_prohibit_company_'.$pcompany_code;
        $cache = $this->mc->get($mem_key);
        
        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $temp_agent = $cache['data'];
        }
        else
        {
            $this->dbback->select('agentcode');
            $cond_where = "parentcode = '".$pcompany_code."'";
            $this->dbback->where( $cond_where );
            $arr_data = $this->dbback->get('agency')->result_array();    
            if(is_array($arr_data)&&!empty($arr_data)){
                foreach ($arr_data as $value){
                   $temp_agent[] =  $value['agentcode'];
                }
            }
            
            $this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$temp_agent) ,  86400);
        }
        return $temp_agent;        
    }
    
    /**
     *是否屏蔽 
     */
    public function is_prohibit($agent_code,$parent_code='A2313'){      
        $prohibit_arr = $this->prohibit_company($parent_code);       
        $is_prohibit = in_array($agent_code, $prohibit_arr) ? TRUE : FALSE;
        return $is_prohibit;        
    }
    
	/**
	 *经纪人头像状态
	 */
	public function statusHeadPic($uid)
	{
		$mem_key = $this->_mem_key.'_get_status_head_pic_'.$uid;
        $cache = $this->mc->get($mem_key);
		if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
			
            $status = $cache['data'];
        }
        else
        {
			
			$this->dbback->select('id');
			$cond_where = "uid = '$uid' && kind ='p_1' && valid_flag='1'";
			$this->dbback->where( $cond_where );
			$arr_data = $this->dbback->get('broker_certificate')->result_array(); 
			if(is_array($arr_data) && !empty($arr_data))
			{
				$status =1;
			}
			else
			{
				$status =0;
			}
			$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$status) ,  86400);
		}
		
		return $status;
	
	}
    
}
/* End of file Broker_model.php */
/* Location: ./zsb/model/Broker_model.php */