<?php
// +----------------------------------------------------------------------
// | ThinkOAO （Online And Offline）
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.hanchao9999.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaogg <xiaogg@sina.cn>
// +----------------------------------------------------------------------
namespace Member\Controller;
use Common\Controller\HanchaoController;
class OauthController extends HanchaoController {
	//登录地址
	public function login($type = null) {
		
		empty($type) && $this->error('参数错误');
		//加载ThinkOauth类并实例化一个对象
		$sns = \Common\Vendor\ThinkOauth::getInstance($type);
		//die(OAUTH_URL_CALLBACK);
		//跳转到授权页面
		//print_r($sns);exit;
		redirect($sns->getRequestCodeURL());
	}
	//授权回调地址
	public function callback($type = null, $code = null) {
		
		header('content-type:text/html;charset=UTF-8;');
		(empty($type) || empty($code)) && $this->error('参数错误');
		//加载ThinkOauth类并实例化一个对象
		$sns = \Common\Vendor\ThinkOauth::getInstance($type);
		
		//腾讯微博需传递的额外参数
		$extend = null;
		if ($type == 'tencent') {
			$extend = array('openid' => I('get.openid'), 'openkey' => I('get.openkey'));
		}
		//请妥善保管这里获取到的Token信息，方便以后API调用
		//调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
		//如： $qq = ThinkOauth::getInstance('qq', $token);
		//print_r($sns);exit;
		$token = $sns->getAccessToken($code, $extend);
        $ip=get_client_ip(1);
		//die($token);
		//获取当前登录用户信息
		if (is_array($token)) {
			$user_info = A('Type', 'Event')->$type($token);
			$OMember = M('OauthMember');
			//$Member = D('Member');
			$Member = D('Common/Login');
			//账户是否已经存在
			$rst = $OMember->where("_from='{$type}' and openid='{$token['openid']}' and status=1")->find();
            if($rst['lock_to_id']){
                $uid=$rst['lock_to_id'];
                $memberinfo=$Member->find($uid);
            }
            //$MEMBER_id=session('MEMBER_id');
			if(!empty($MEMBER_id)) {//如果用户已经local账户登陆过，则表示要绑定第三方				
				if (!empty($rst)) {
					$this->error('该帐号已被本站其他账号绑定！', U("Index/index"));exit();
				}
				$data = array(
					'_from'				 => $type,
					'_name'				 => $user_info['name'],
					'head_img'			 => $user_info['head'],
					'create_time'		 => NOW_TIME,
					'lock_to_id'		 => $_SESSION["MEMBER_id"],
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ip,
					'login_times'		 => 1,
					'status'			 => 1,
					'access_token'		 => $token['access_token'],
					'expires_date'		 => (int) (NOW_TIME + $token['expires_in']),
					'openid'			 => $token['openid'],
				);
				if ($OMember->add($data)) {
					$this->success('账号绑定成功！', U("Index/index"));
				} else {
					$this->error('账号绑定失败！', U("Index/index"));
				}
			} else if ($uid && $memberinfo) {
				//数据库已经有该用户登录信息
				$data = array(
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ip,
					'login_times'		 => $rst['login_times'] + 1,
					'access_token'		 => $token['access_token'],
					'expires_date'		 => (int)(NOW_TIME + $token['expires_in']),
				);
				$OMember->where("_from='{$type}' and openid='{$token['openid']}'")->save($data);
                session("MEMBER_type",$type);
                session("MEMBER_id",$uid);
                session("MEMBER_name",$rst["_name"]);
                $Member->loginupdate($memberinfo);
				action_log('user_login', 'Member', $uid, $uid);
				$this->success('登录成功！', U("Index/index"));
			} elseif ($OMember->where("_from='{$type}' and openid='{$token['openid']}' and status=0")->field('id')->find()) {
				$this->error('您账号已被禁止，请联系网站管理员！', U("portal/index/index"));
			} else {
				//本地用户中创建对应一条数据
				$mem_insert = array(
					'username'	 => $user_info['name'],
				);
				//跳转到登录页面，将第三方信息存session
				//print_r(1);exit;
				
				//$memberinfo = $Member->register($mem_insert,1);
				//第三方用户表中创建数据
				$data = array(
					'_from'				 => $type,
					'_name'				 => $user_info['name'],
					'head_img'			 => $user_info['head'],
					'create_time'		 => NOW_TIME,
					'lock_to_id'		 => $memberinfo['id'],
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ip,
					'login_times'		 => 1,
					'status'			 => 1,
					'access_token'		 => $token['access_token'],
					'expires_date'		 => (int) (NOW_TIME + $token['expires_in']),
					'openid'			 => $token['openid'],
				);
				session('oauthmemberlogin',$data);
				$this->redirect('Home/Login/index');exit;
				if ($OMember->add($data)) {
					session("MEMBER_type",$type);
					session("MEMBER_id",$memberinfo['id']);
					session("MEMBER_name",$user_info["name"]);
					$Member->loginupdate($memberinfo);
					action_log('user_login', 'Member', $uid, $uid);
					$this->success('登录成功！', U("Index/index"));
				}else {
					$this->error('用户信息获取失败！', U("Index/index"));
				}
			}
		} else {
			$this->success('登录失败！', U("Index/index"));
		}
	}
}