<?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_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->_mem_key = GB_CITY . '_broker_model';
		$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,accid,telno,truename,smallphoto");
        //查询条件
		/*
		if(strtolower(mb_detect_encoding($username)) == 'utf-8'){
			$username =iconv("UTF-8", "GBK//IGNORE", $username); 
		}
		*/
		// $username =iconv("UTF-8", "GBK//IGNORE", $username); 
		$username =iconv(mb_detect_encoding($username), "GBK//IGNORE", $username); 
        $this->dbback->where("username = '".$username."' and password = '".$password."'");
        //查询
        $arr_data = $this->dbback->get('broker')->row_array();
        $this->yunxinLogin($username);
        return isset($arr_data['uid']) ? intval($arr_data['uid']) : 0;
    }


    public function yunxinLogin($username){

        $username = urldecode($username);
        $this->dbback->select("uid,accid,telno,truename,smallphoto");
        $this->dbback->where("username = '".$username."'");
        //查询
        $arr_data = $this->dbback->get('broker')->row_array();

        if($arr_data){
            $host = $_SERVER['HTTP_HOST'];
            preg_match('/(.*).zsb.house365.com/',$host,$pa);

            $city = 'nj';
            if(!empty($pa[1])){
                $city = $pa[1];
            }

            $uid = $arr_data['uid'];
            $telno = $arr_data['telno'];
            $accUrl = "http://newrent.house365.com/api/zsb-app/get-acc-info-by-uid?uid={$arr_data['uid']}&city={$city}";
            $accRes = file_get_contents($accUrl);

            if($accRes){
                $accRes = json_decode($accRes,true);
                if(isset($accRes['result']) && $accRes['result'] == '1'){
                    $login_info['data']['accid'] = $accRes['data']['accid'];
                    $login_info['data']['acc_token'] = $accRes['data']['token'];
                }else{
                    $truename = $arr_data['truename'];
                    $truename = iconv('gbk', "UTF-8//IGNORE", $truename);

                    $post_data = array(
                        "city" => $city,
                        "uid" => $uid,
                        "phone" => $telno,
                        "username" => $truename,
                        "avatar" => $arr_data['smallphoto']
                    );

                    $re_url = 'http://newrent.house365.com/api/zsb-app/register-acc-id';
                    $data = $this->request_post_($re_url,$post_data);
                    if($data){
                        $data = json_decode($data, true);

                        if(isset($data['result']) && $data['result'] == '1'){
                            $login_info['data']['accid'] = $data['data']['accid'];
                            $login_info['data']['acc_token'] = $data['data']['token'];
                        }
                    }
                }
            }
        }
    }

    function request_post_($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }



	/**
     * 检查经纪人登陆(后台专用)
     *
     * @access	public
     * @param	string  $username 经纪人账号
     * @param	string  $password 经纪人密码
     * @return	array   经纪人基础信息
     */
    public function loginAdmin($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);*/

    }



	 /**
     * 用户登录时随机生成postkey,postvalue
     *
     * @access	public     
     * @return	void
     */
    public function set_rand_post()
    {   
        $app_key1 = "post_key";        
        $app_key2 = "post_value"; 		
        $this->session->set_userdata(array($app_key1 => getRandChar(10)));
		$this->session->set_userdata(array($app_key2 => rand(100000,999999)));      

    }

    /**
    * 获取用户登录时随机生成postkey,postvalue
    *
    * @access	public     
    * @return	void
    */
	public function get_rand_post()
	{
		$app_key1 = "post_key";        
        $app_key2 = "post_value"; 	
		$post_key = $this->session->userdata($app_key1);
		$post_value = $this->session->userdata($app_key2);
		return array('post_key'=>$post_key,'post_value'=>$post_value);
	}

    /**
     * 重置用户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();
		
		//获取用户信息
		$userdata = $this->session->userdata($app_key);

        //清空SESSION数据
        $this->session->unset_userdata($app_key);
		//清第二个缓存
		$this->deleteSession();
        unset($_SESSION['zsb_user_weak_password']);

        //清除身份
        $cookie = array(
               'name'   => 'broker_id',
               'value'  => 0,
               'expire' => 1800,    // 设置一天的有效期            
        );
        $this->input->set_cookie($cookie);

		 //清除违规行为弹窗
        $violationValCookie = array(
               'name'   => 'violationVal_'.$userdata['uid'],
               'value'  => '',
               'expire' => time()-1,    // 设置一天的有效期            
        );
        $this->input->set_cookie($violationValCookie);
    }
    
    
    /**
     * 设置用户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");
            //查询条件
            if(GB_CITY == 'nj')
            {
                $this->db->where("authname = '".$master."'");
            }
            else
            {
                $this->db->where("truename = '".$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;

			/*$this->dbback->select("id,is360,esta");
			$this->dbback->where("uid ='".$user_arr['uid']."' AND esta in(1,5) AND infofrom='5'");
			$sellInfo = $this->dbback->get('sell')->result_array();
			
			if(!empty($sellInfo))
			{
				foreach($sellInfo as $key => $item)
				{
					$valid_num += 1;

					if($item['esta'] == '1' && $item['is360'] == '2')
					{
						$valid_num += 1;
					}
				}
			}*/
        }
        
        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;
            case 'express_card' :
                $cond_kind = "kind = 'p_5'";
                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,$cardnum='')
    {
        $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;
        if($cardnum){
            $insert_data['card_number'] = $cardnum;
        }
        $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_2_'.$uid;
		//$this->mc->delete($mem_key);
        $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;
	
	}

	 /*
     * 根据UID查找经纪人信息
     * @access public 
     * @param string $telno 电话号码
     * @return int 次数
     */
    public function get_broker_info_by_uid($uid)
    {

        if(GB_CITY=='wh')
	    {
			$this->db->select('usetime,starlevel,freeze_num,upgrade_time,mistake_time,writes_date,package_id,real_status');
	    }
		else
		{
		    if(GB_CITY == 'nj'){
                $this->db->select('usetime,starlevel,freeze_num,upgrade_time,mistake_time,real_status,package_id');
            }else{
                $this->db->select('usetime,starlevel,freeze_num,upgrade_time,mistake_time,package_id,real_status');
            }
		}
       $cond_where = "uid = '".$uid."'";
       $this->db->where( $cond_where );
	    $arr_data = $this->db->get('broker')->result_array();

	   //print_r($arr_data);die;


	   $starlevel =$arr_data['0']['starlevel'];

	    if($arr_data['0']['upgrade_time']==0)
		{
			if(GB_CITY=='wh')
			{
				$arr_data['0']['upgrade_time'] =$arr_data['0']['writes_date'];
			}
			else
			{
				$arr_data['0']['upgrade_time'] =strtotime($arr_data['0']['usetime']);
			}
			
		}

	    if($arr_data['0']['mistake_time']>$arr_data['0']['upgrade_time'])
	    {
			$nearest =$arr_data['0']['mistake_time'];
			//var_dump($arr_data);exit;
	    }
	    else
	    {
			$nearest =$arr_data['0']['upgrade_time'];
	    }
		//echo $starlevel;
		if($starlevel==1)
		{
			$upgrade_cycle =7;
		}
		elseif($starlevel==2)
		{
			$upgrade_cycle =28;
		}
		elseif($starlevel==3)
		{
			$upgrade_cycle =60;
		}
		elseif($starlevel==4)
		{
			if(GB_CITY=='nj' || GB_CITY=='hf')
			{
				$upgrade_cycle =60;
			}
			else
			{
				$upgrade_cycle =180;
			}
		}
		$distance_today =time()-$nearest;
		$distance_today =$distance_today/3600/24;
		$next_update_day =$upgrade_cycle - floor($distance_today);
		//var_dump($nearest);exit;
		$distance_month =floor($next_update_day/30);
		$distance_days  =$next_update_day%30;
		//echo $distance_days;die;
		$arr_data['0']['next_update_day'] =$next_update_day;
		$arr_data['0']['distance_month'] =$distance_month;
		$arr_data['0']['distance_days'] =$distance_days;
	    $arr_data['0']['package_id'] =$arr_data['0']['package_id'];
	    $arr_data['0']['real_status'] =$arr_data['0']['real_status'];
		//print_r($arr_data);die;
	    return $arr_data;
    }



    /*
    * 根据Packageid查找真房源套数
    * @access public
    * @param string
    * @return int 次数
    */
    public function get_realnum_by_packageid($packageid)
    {

        $this->dbback->select('real_house_num_limit');
        $cond_where = "package_id = '".$packageid."'";
        $this->dbback->where( $cond_where );//print_r($this->db);die('okkk');
        $arr_data = $this->dbback->get('broker_package')->result_array();
        if(!empty($arr_data))
        {
            return  $arr_data['0']['real_house_num_limit'];
        }else
        {
            return 0;
        }

    }



    /*
     * 根据UID查找引导页设置
     * @access public 
     * @return int 次数
     */
	public function get_broker_remind_set_by_uid($uid)
	{

		$mem_key = $this->_mem_key.'_get_broker_remind_set_by_uid_6'.$uid;
        $cache = $this->mc->get($mem_key);
		//$this->mc->delete($mem_key);
		if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $status = $cache['data'];
        }
        else
        {
			$this->db->select('id');
			$cond_where = "uid = '$uid'";
			$this->db->where( $cond_where );
			$arr_data = $this->db->get('broker_remind_set_360')->result_array(); 
			//print_r($arr_data);
			if(is_array($arr_data) && !empty($arr_data))
			{
				$status =1;
				$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$status) ,  86400);
			}
			else
			{
				$status =0;
			}
			
			
		}
		
		return $status;
	}


	public function check_broker_refresh_num($uid,$package_id)
	{
		
		$mem_key = $this->_mem_key.'_check_broker_refresh_num_6'.$uid;
        $cache = $this->mc->get($mem_key);
		//$this->mc->delete($mem_key);
		if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $status = $cache['data'];
        }
        else
        {
			$this->db->select('refresh');
			$cond_where = "uid = '$uid'";
			$this->db->where( $cond_where );
			$arr_data = $this->db->get('broker')->result_array(); 
			$broker_refresh =$arr_data['0']['refresh'];

			$this->db->select('package_refresh_num');
			$cond_where = "package_id = '$package_id'";
			$this->db->where( $cond_where );
			$arr_data = $this->db->get('broker_package')->result_array(); 
			$broker_package_refresh_num =$arr_data['0']['package_refresh_num'];
			if($broker_refresh !=$broker_package_refresh_num)
			{
				$this->db->where('uid',$uid);       
				$this->db->update('broker',array('refresh' => $broker_package_refresh_num));
			
			}
			//print_r($arr_data);die;
			if(is_array($arr_data) && !empty($arr_data))
			{
				$status =1;
				$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$status) ,  86400);
			}
			else
			{
				$status =0;
			}
			
			
		}
		
		return true;
	}


    public function check_broker_expire_housebeannum($uid)
    {

        $mem_key = $this->_mem_key.'_check_broker_expire_housebeannum_6'.$uid;
        $this->mc->delete($mem_key);
        $cache = $this->mc->get($mem_key);

        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $num = $cache['data'];
        }
        else
        {

            $endtime = strtotime('next month',strtotime(date('Y-m')));
            $this->db->select_sum('total');
            $cond_where = "broker_id = '$uid' and endtime <='$endtime'";
            $this->db->where( $cond_where );
            $arr_data = $this->db->get('payment_housebean_record')->result_array();


            $this->db->select('credit,frozen');
            $cond_where = "broker_id = '$uid'";
            $this->db->where( $cond_where );
            $arr_data_broker = $this->db->get('growth_credit')->result_array();

            if(is_array($arr_data) && !empty($arr_data) && is_array($arr_data_broker) && !empty($arr_data_broker))
            {

                $broker_credit    =$arr_data_broker[0]['credit']-$arr_data_broker[0]['frozen'];

                if($arr_data[0]['total']>$broker_credit) {
                    $num = $broker_credit;
                }
                else
                {
                    $num = $arr_data[0]['total'];
                }

                $this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$num) ,  86400);
            }
            else
            {
                $num =0;
            }


        }

        return $num;
    }
    public function check_broker_expire_housebeannum2($uid,$credit)
    {
        $mem_key = $this->_mem_key.'_check_broker_expire_housebeannum_6'.$uid;
        $this->mc->delete($mem_key);
        $cache = $this->mc->get($mem_key);

        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $num = $cache['data'];
        }
        else
        {
            $endtime = strtotime('next month',strtotime(date('Y-m')));
            $this->db->select_sum('total');
            $cond_where = "broker_id = '$uid' and endtime <='$endtime'";
            $this->db->where( $cond_where );
            $arr_data = $this->db->get('payment_housebean_record')->result_array();

            if(is_array($arr_data) && !empty($arr_data))
            {
                if($arr_data[0]['total']>$credit) {
                    $num = $credit;
                }
                else
                {
                    $num = $arr_data[0]['total'];
                }
                $this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$num) ,  86400);
            }
            else
            {
                $num =0;
            }
        }

        return $num;
    }


	public function check_broker_growth_credit($uid)
	{
		$this->db->select('id');
		$cond_where = "broker_id = '$uid'";
		$this->db->where( $cond_where );
		$arr_data = $this->db->get('growth_credit')->result_array(); 
		//print_r($arr_data);die;

		if(empty($arr_data))
		{
			$insert_data = array();
        
			$insert_data['broker_id'] = $uid;
			$insert_data['credit'] = 0;
			$insert_data['backup_credit'] = 0;
			$insert_data['frozen'] = 0;
			$insert_data['status'] = 1;
			$this->db->insert('growth_credit',$insert_data);
		}
		
	}
    private function getIP(){
        if (getenv('HTTP_CLIENT_IP')) {
            return getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            return getenv('HTTP_X_FORWARDED_FOR');
        }
        if (getenv('HTTP_X_FORWARDED')) {
            return getenv('HTTP_X_FORWARDED');
        }
        if (getenv('HTTP_FORWARDED_FOR')) {
            return getenv('HTTP_FORWARDED_FOR');
        }
        if (getenv('HTTP_FORWARDED')) {
            return getenv('HTTP_FORWARDED');
        }
        if ($_SERVER['REMOTE_ADDR']) {
            return $_SERVER['REMOTE_ADDR'];
        }
        return '';
    }

	public function saveChangePasswordLog($password,$uid,$username){
	    $data = array();
        $data['broker_id'] = $uid;
        $data['action'] = 'Change_password';
        $data['action_name'] = '密码';
        $data['field'] = 'password';
        $data['change'] = $password;
        $data['change_name'] = '******';
        $data['operator_id'] = '-1';
        $data['operator_name'] = $username;
        $data['time'] = time();
        $data['ip'] = $this->getIP();
        $this->db->insert('log_broker_change',$data);
    }

    /**
     * Get Database Master
     * @return Object
     */
    public function getDatabaseMaster()
    {
        return $this->db;
    }

    /**
     * Get Database Slave
     * @return Object
     */
    public function getDatabaseSlave()
    {
        return $this->dbback;
    }

    public function save_alipay_log($old_alipay_account,$alipay_account){

        $session_info = $this->get_user_session();
        if(!$session_info){
            return false;
        }
        $data['uid'] = $session_info['uid'];
        $data['username'] = $session_info['username'];
        $data['agentcode'] = $session_info['agentcode'];
        $data['before_account'] = $old_alipay_account;
        $data['after_account'] = $alipay_account;
        $data['save_time'] = time();
        $this->db->insert('alipay_account_log',$data);

    }

    //是否允许发布
    public function rent_allow_release($infotype){
        $session_info = $this->get_user_session();
        $companycode = $session_info['agentcode'];
        $agency = $this->dbback->from("agency")->where(array('agentcode'=>$companycode))->get()->row_array();
        $rent_allow_release = $agency['rent_allow_release'];
        if(!$rent_allow_release){
            return 0;
        }
        $rent_allow_release = json_decode($rent_allow_release);
        if(in_array($infotype,$rent_allow_release)){
            return 1;
        }
        return 0;
    }


    public function all_rent_allow_release(){
        $session_info = $this->get_user_session();
        $companycode = $session_info['agentcode'];
        $agency = $this->dbback->from("agency")->where(array('agentcode'=>$companycode))->get()->row_array();
        $rent_allow_release = $agency['rent_allow_release'];
        return $rent_allow_release;
    }

    /**
     * 判断密码是否为纯数字或纯字母
     * @param $password
     * @return bool
     * @author Livfer
     */
    public function checkWeakPassword($password)
    {
        if (preg_match('/^\d+$/i', $password) || preg_match('/^[a-zA-Z]+$/i', $password)) {
            return true;
        }
        return false;
    }

    public function qrCodeLogin($username)
    {
        $authnum = $this->session->userdata('authnum');
        //清空SESSION数据
        $this->session->unset_userdata('authnum');
        $this->dbback->select("uid,accid,telno,truename,smallphoto");
        $this->dbback->where("username = '".$username."'");
        //查询
        $arr_data = $this->dbback->get('broker')->row_array();
        $this->yunxinLogin($username);
        $uid = isset($arr_data['uid']) ? $arr_data['uid'] : 0;
        //设置UID
        $this->set_uid($uid);
        //获取经纪人信息

        $broker_info = $this->get_broker_info();

        //当前时间
        $now = time();

        //判断账号是否到期
        $now_ymd = date('Y-m-d', $now);
        if($broker_info['expiredate'] < $now_ymd)
        {
            return 'exp_error';
        }

        //判断账号是否禁用
        if($broker_info['valid_flag'] != '1')
        {
            return 'vad_error';
        }

        //验证无误，把用户基本信息存入SESSION，并记录登陆日志
        $this->broker_model->set_user_session($broker_info);
        $this->broker_model->set_rand_post();
        $ip = get_ip(); //登陆IP
        $log_data = array('kind'=>'qrcode', 'uid'=>$uid, 'logintime'=>$now, 'ip'=>$ip);
        $this->log_broker_login($log_data);

        return 'success';
    }

    /**
     * 更新用户中心的密码
     * @param $uid
     * @param $password
     * @return mixed
     * @author mellon
     */
    public function updateUcPwd($uid, $password)
    {
        // 调用用户中心更新
        $this->load->model('zsb_api_model');// 租售宝API调用类
        $ucParams = array(
            'brokerId' => $uid,
            'password' => $password,
            'city' => GB_CITY,
        );
        $ucParams['sign'] = $this->zsb_api_model->getSign($ucParams);
        return $this->zsb_api_model->getRequrstData('uc_update', $ucParams);
    }

    /**
     * 更改用户中心手机号码
     * @param $uid
     * @param $newPhone
     * @return mixed
     * @author mellon
     */
    public function changeUcPhone($uid, $newPhone)
    {
        // 调用用户中心更新
        $this->load->model('zsb_api_model');// 租售宝API调用类
        $ucParams = array(
            'uid' => $uid,
            'phone' => $newPhone,
            'city' => GB_CITY,
        );
        return $this->zsb_api_model->getRequrstData('change_uc_phone', $ucParams);
    }

}
/* End of file Broker_model.php */
/* Location: ./zsb/model/Broker_model.php */