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

class Login extends MY_Controller
{

	function __construct()
	{
		parent::__construct();

		$this->load->model("user_model");
		$this->load->library("user_class");
		$this->load->helper("template_helper");
		$this->user_id = checklogin();
	}

    //登录页面
	function index()
	{
        Header("HTTP/1.1 301 Moved Permanently");
        Header("Location: http://passport.house365.com/index/login?others_returnback=http://newrent.house365.com/user-center/index");
        exit;
        //IM 埋点
        if($_GET['from']=='im'){
            setcookie('fromim',1,time()+3600*24*180,'/','house365.com');
        }
		$data['title'] = '用户登录';
		if($_POST)
		{

			$time = time();
			$randNum = rand(100000,999999);
			//echo randomString();
			$method	= $this->input->post('method');
			$telno	= $this->input->post('telno');
			$password	= $this->input->post('password');
			$telCode	= $this->input->post('telCode');
			$loginkind	= $this->input->post('loginkind');
			$password2	= $this->input->post('password2');
            $name 	= $this->input->post('name');
            $action	= $this->input->post('action');
            $refer	= $this->input->post('refer');
            $refer1	= $this->input->post('refer1');
            
            $ajaxyz	= $this->input->post('ajaxyz');

            //隐藏表单的提交
            if($this->input->post('telnotj'))
            {
              $telno = $this->input->post('telnotj');
            }
            if($this->input->post('passwordtj'))
            {
              $password2 = $this->input->post('passwordtj');
            }
            if($this->input->post('telcodetj'))
            {
              $telCode = $this->input->post('telcodetj');
            }
            if($this->input->post('loginkindtj'))
            {
              $loginkind = $this->input->post('loginkindtj');
            }

			if( $loginkind == 1 )
			{
					//验证是否有此手机用户
					$result = $this->user_model->yztelno($telno);

					if( $result == 0 )
					{
						echo 'N_USER';
					    exit;
					}
                   
					//动态密码登录
					$user_isset = $this->user_model->yzlogindt($telno,$telCode);
                    $result = $user_isset['id'];
                    $password = $user_isset['password'];

					if( $result == 0 )
					{
				        echo 'N_PASS';
					    exit;
					}elseif($ajaxyz==1 && $result>0){


                        //  根据passport_uid 调用窦世文个人中心接口，种sso_token Cookie。 code by : wmc
					    if(isset($user_isset['passport_uid']) && $user_isset['passport_uid']){
                            $this->register_tf_ucenter_cookie($user_isset['passport_uid']);
                        }

						/********* xue add 2015-02-10动态登录时登录全站个人会员中心START***********/
						//查出密码，
                        $esf_password = $this->user_model->getEsfPassword($telno);
						//到全站会员中心注册
                        $ucenter_result = $this->user_model->ucenterLogin($telno,$esf_password);
						/********* xue add 2015-02-10END***********/


                        //2016-1-28 zhou 添加crm记录 ----------- start ------------->
                        $crm_uri	= '?city='.GB_CITY;

                        $crm_uri	.= '&activefrom=212';//降价通知
                        $fmailaction	= '登录-用户中心' ;


                        $crm_uri .= '&activename='.urlencode($fmailaction);
                        //CRM联系人信息-username

                        //CRM联系人方式信息-mobile
                        $mobile		= strip_tags($telno);
                        $crm_uri .= '&mobile='.$mobile;
                        $crm_uri .= '&username='.$mobile;
                        $remark = '登录-用户中心';

                        $crm_uri .= '&joinremark='.urlencode($remark);



                        $this->get_api("http://crm.house365.com/index.php/Simulate/sea".$crm_uri);


                        //2016-1-28 zhou 添加crm记录 ----------- end ------------->

                        echo 'Y';
					    exit;   
                    }
				
			}
			else
			{

                if($ajaxyz==1)
                { 
                   $telno = trim(iconv('UTF-8', 'gbk', $telno));
				   /********* xue add 2015-02-10普通登录时先登录全站个人会员中心START***********/
				   //在第一遍验证的时候登录全站
				   $ucenter_result = $this->user_model->ucenterLogin($telno,md5($password2));
				
					$new_data =$this->get_api("http://job.2sf.house365.com/esf_jobs/getUserLoginLog.php?telno=$telno&del=2");
					
				   if($new_data==10)
				   {
					  echo 'N_LIMIT';
					  exit();
				   }
				   if( $ucenter_result['result']==0)
				   {
						$new_data =$this->get_api("http://job.2sf.house365.com/esf_jobs/getUserLoginLog.php?telno=$telno&del=0");
						//echo $new_data;die;
						if($new_data==10)
					    {
						    echo 'N_LIMIT';
							exit();
					    }
				   }else
				   {
						$this->get_api("http://job.2sf.house365.com/esf_jobs/getUserLoginLog.php?telno=$telno&del=1");
				   }

				   //print_r($ucenter_result);exit;
				  
				   /********* xue add 2015-02-10普通登录时先登录全站个人会员中心END***********/
                }                
				
				$esf_result	= $this->user_model->yzlogin($telno,$password2);

                if($esf_result >0){
                    $userinfo = $this->user_model->get_user_info($esf_result);
                    if($userinfo && $userinfo['telno']){
                        $telno = $userinfo['telno'];
                    }
                }
				/********* xue add 2015-02-10普通登录时二手房和全站个人会员中心处理START***********/
				if($ajaxyz==1){

					if($ucenter_result['result']==1 && $esf_result>0){
                         if($uid = $this->user_model->get_passport_uid_by_id($esf_result)){
                             $this->register_tf_ucenter_cookie($uid);
                         }
				         echo 'Y';
						 exit();
				     }elseif($ucenter_result['result']==1 && $esf_result==0){
						// echo "1111";exit;

				         $esfCheckTel = $this->user_model->yztelno($telno);
						 if($esfCheckTel==0){
                              //无此用户向二手房库插入一条用户信息
							  $passport_uid = $ucenter_result['data']['passport_uid'];
                              $password = md5($password2);
							  $telno = $telno;
                              $city = $ucenter_result['data']['city'];
							  $email = $ucenter_result['data']['email'];
							  $username = $ucenter_result['data']['username'];
							  $nickname = $ucenter_result['data']['nickname'];
							  $avatar = $ucenter_result['data']['avatar'];
							  $ip = $ucenter_result['data']['ip'];							
						      $this->user_model->addUserFromUcenter($passport_uid,$password,$telno,$city,$email,$username,$nickname,$avatar,$ip);

						 }else{
						    //密码不同,修改二手房密码
                              $this->user_model->updateEsfPassowrd($telno,$password2);
                              //记录日志
							  $msg = date('Y-m-d H:i:s').":".$telno." \n";
							  @file_put_contents('./password_err',$msg,FILE_APPEND); 		

						 }
						 $this->register_tf_ucenter_cookie($ucenter_result['data']['passport_uid']);
						 echo 'Y';
						 exit();
				
				     }elseif($ucenter_result['result']==0 && $esf_result>0){
					      //二手房有，全站会员中心无,记录日志
						if($uid = $this->user_model->get_passport_uid_by_id($esf_result)){
							$this->register_tf_ucenter_cookie($uid);
						}
						  $msg = date('Y-m-d H:i:s').":".$telno." \n";
						  @file_put_contents('./ucenter_err',$msg,FILE_APPEND); 
						  echo 'Y';
						  exit();
						  					 
					 }else{
					 
					     echo 'N_USER';
						 exit();
					 
					 }				
				
				}
				
                /********* xue add 2015-02-10普通登录时二手房和全站个人会员中心处理END***********/


				/*
					1、调取用户中心登录;是否登录成功	$ucenter_result 
					2、执行二手房判断	$esf_result

					if( $ucenter_result == $esf_result > 0 ) {
						continue;
					} else if ( $ucenter_result > 0 AND  $esf_result == 0 ) {
						if( 你没有值 ) {
							插入数据，做日志1
						} else {
							//密码不一样，更新你的密码
						}
					} else if ( $ucenter_result == 0 AND  $esf_result > 0 ) {
						//正常登录，做日志2
					} else if ( $ucenter_result == 0 AND  $esf_result == 0 ) {
						echo 'N_USER';
					}
					
				*/
				//$result	= $this->user_model->yzlogin($telno,$password2);
 
                $password = md5($password2);
                $name = $telno;
                /***********xue add 2015-02-10 START************/
				$result = $esf_result;
				/***********xue add 2015-02-10 END************/

                /*
   				if( $result == 0 )
				{
  					echo 'N_USER';
					exit;
				}elseif($ajaxyz==1 && $result>0){
                 	echo 'Y';
					exit;               
                }*/
			}

			 //2016-1-28 zhou 添加crm记录 ----------- start ------------->
			$crm_uri	= '?city='.GB_CITY;
			
			$crm_uri	.= '&activefrom=212';//降价通知
			$fmailaction	= '登录-用户中心' ;
			
			
			$crm_uri .= '&activename='.urlencode($fmailaction);
			//CRM联系人信息-username
			
			//CRM联系人方式信息-mobile
			$mobile		= strip_tags($telno);
			$crm_uri .= '&mobile='.$mobile;
			$crm_uri .= '&username='.$mobile;
			$remark = '登录-用户中心';
			
			$crm_uri .= '&joinremark='.urlencode($remark);
			
			
			
			$this->get_api("http://crm.house365.com/index.php/Simulate/sea".$crm_uri);


			  //2016-1-28 zhou 添加crm记录 ----------- end ------------->
			if( $result > 0 && $action!='loginyz' && $ajaxyz!='1')
			{

				 $this->user_model->updatelogintime($result);

				 $this->user_class->user_login($result,$password,$telno,$name);

                if($this->input->post('redirectUrl'))
                {
                    $redirectUrl = $this->input->post('redirectUrl');
                    jumpto($redirectUrl);
                }
				 //2018-8-3 增加，抽奖页面跳转回去，by lk
                if(strpos($_SERVER['HTTP_REFERER'],'lucky_prize')){
                    jumpto($_SERVER['HTTP_REFERER']);
                }

                 //如果上一页是登陆页面，就直接跳首页
                 if((!empty($refer1) or !empty($refer)) && $refer!=USER_CENTER.'user/logout' && $refer1!=USER_CENTER.'user/logout')
                 {

                   //jumptotk(USER_CENTER.'user',"您已登录,进入会员中心首页!",3000,'tips');
                   if(!empty($refer)){
                   jumpto($refer);
                   }else{
                   jumpto($refer1);
                   }
                 }else{
                   //jumptotk($_SERVER['HTTP_REFERER'],"登录成功,页面将跳转到之前的页面。",3000,'tips');
                   jumpto(USER_CENTER.'user');
                 }
                 exit;
			}
		}else{
        if( $this->user_id > 0 )
		{
          //jumptotk(USER_CENTER.'user',"您已登录,进入会员中心首页!",3000,'tips');



          jumpto(USER_CENTER.'user');
		}
        }

        if($_GET['redirectUrl']){
		    $redirectUrl = $_GET['redirectUrl'];
            if(preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$redirectUrl)){
                    $data['redirectUrl'] = $redirectUrl;
            }
        }

		   //bibibibi
		   $data['isa_website'] = '2,19,71';
		   $data['isa_city'] = GB_CITY;
		   $data['isa_addones'] = '';
		   $data['isa_url'] = 'isa.house365.com/js/analyze.js?v=2.1';
			//bibibibi
		   //$data['ga_channel'] = 'center';

		$this->load->view('login',$data);
	}

    //登陆成功需要把sso_token以cookie形式种到浏览器中
	protected function register_tf_ucenter_cookie($passport_uid){
//        $url = "http://api.house365.com/passport/passport_gettoken_byuid.php?passport_uid=".$passport_uid;
//        if(isset($_COOKIE['utm_source']) && isset($_COOKIE['utm_medium']) && isset($_COOKIE['utm_campaign'])){
//            $url.= "&utm_source={$_COOKIE['utm_source']}&utm_medium={$_COOKIE['utm_medium']}&utm_campaign={$_COOKIE['utm_campaign']}";
//        }
//        if(isset($_COOKIE['crm_scene'])){
//            $url.= "&register_client=PC&register_application={$_COOKIE['crm_scene']}";
//        }

//        $api_res = json_decode($this->get_api($url), true);
        $api_res = $this->get_api(GB_GET_USER_INFO_BY_PASSPORT_ID_URL . '?passport_uid=' . $passport_uid );
        if(isset($api_res['result']) && $api_res['result']==1){
            setcookie('sso_token',$api_res['data']['sso_token'],time()+3600*24*180,'/','house365.com');
        }
    }

	//入CRM数据
	public function get_api($t_url)
	{
	
		$ch = curl_init();
		$t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		
		curl_setopt($ch, CURLOPT_URL, $t_url);
		curl_setopt($ch, CURLOPT_REFERER, $t_url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 3);
		$str = curl_exec($ch);
		curl_close($ch);
		return $str;
	
	
	
	}

	//iframe_login_ajax
	function iframe_login_ajax()
	{
		$telno	= $this->input->get('telno');
		$password	= $this->input->get('password');
		$tel_code	= $this->input->get('tel_code');
		$is_code_login	= $this->input->get('is_code_login');
 
		$telno = trim(iconv('UTF-8', 'gbk', $telno));

		if( $is_code_login == 1 )
		{       
			//动态密码登录
			$user_isset = $this->user_model->yzlogindt($telno,$tel_code);
            $result = $user_isset['id'];
			$password = $user_isset['password'];
			if( $result )
			{
				$this->user_model->updatelogintime($result);


				$this->user_class->user_login($result,$password, $telno);

				//隐藏手机号部分数字
				$pattern = "/(1\d{1,2})\d\d(\d{0,3})/";
				$replacement = "\$1*****\$3";
				$telno2 = preg_replace($pattern, $replacement, trim($telno));
				$showname = $telno2 ? $telno2 : "" ;
				$esfmesnum =  $this->user_model->getmessagenumbyuidwd($result);
				$password_encrypt = passport_encrypt($password);

				$ajax_return['error'] = "0";
				$ajax_return['result'] = $result;
				$ajax_return['showname'] = $showname;
				$ajax_return['esfmesnum'] = $esfmesnum;
				$ajax_return['password_encrypt'] = $password_encrypt;

			}else{
				$ajax_return['error'] = "1";            
			}
		}else{
			$result	= $this->user_model->yzlogin($telno,$password);
			if( $result )
			{
				$this->user_model->updatelogintime($result);
				$this->user_class->user_login($result, md5($password), $telno);

				//隐藏手机号部分数字
				$pattern = "/(1\d{1,2})\d\d(\d{0,3})/";
				$replacement = "\$1*****\$3";
				$telno2 = preg_replace($pattern, $replacement, trim($telno));
				$showname = $telno2 ? $telno2 : "" ;
				$esfmesnum =  $this->user_model->getmessagenumbyuidwd($result);
				$password_encrypt = passport_encrypt(md5($password));

				$ajax_return['error'] = "0";
				$ajax_return['result'] = $result;
				$ajax_return['showname'] = $showname;
				$ajax_return['esfmesnum'] = $esfmesnum;
				$ajax_return['password_encrypt'] = $password_encrypt;

			}else{
				$ajax_return['error'] = "1";            
			}
		}
		
		echo serialize($ajax_return);
		exit;
	}

	/**
	* 用户登录接口
	* @author cxf
	*/
	function api_login()
	{

		$telno = $this->input->get('telno');
		$result = $this->user_model->yztelno($telno);

		if( $result > 0 )
		{
			$this->user_model->updatelogintime($result);
			$return	= $this->user_class->user_login($result,$password,$telno);
		}
		else
		{
			$password	= $this->user_model->getyzmpassword($telno);
			$result	= $this->user_model->adduser($telno,$paasword);
			$this->user_model->updatelogintime($result);
			$this->user_class->user_login($result,$password,$telno);
		}
	}
	
    /**
	* 用户链接判断
	* @author cxf
	*/
	function login_judge()
	{
      $this->load->view('login_judge');
	}
	
	/**
	* 用户链接判断
	* @author cxf
	*/
	function login_js()
	{
      $this->load->view('login_js');
	}

    /**
	* 用户链接判断
	* @author cxf
	*/
	function login_js_fenzhan()
	{
      $this->load->view('login_fenzhan_js');
	}

    /**
	* 外地站老头部
	* @author cxf
	*/
	function login_js_oldfenzhan()
	{
      $this->load->view('login_oldfenzhan_js');
	}

}