<?php

namespace app\index\controller;

use EasyWeChat\Factory;
use think\facade\Session;
use think\facade\Log;

class Login extends Base
{
	private app_id;
	private secret;
    public function __construct()
    {
        parent::__construct();
        $this->app_id 	= Config::get('wechat.request.app_id'); //微信appid,推荐写在配置文件或环境变量
        $this->secret 	= Config::get('wechat.request.secret'); //微信appid对应secret,推荐写在配置文件或环境变量
    }


	//微信登录
	public function wechatLogin(){
		//回调地址
		$callback = urldecode(input("callback", ''));
        if ($callback == '') {
			//跳去欢迎页
            $callback=(String)url("/index",[],"",true);
        }
		Session::set('target_url', $callback);
		
        $config = [
            // 'http' => $this->proxy,
            'app_id' => $this->app_id,
            'secret' => $this->secret,	
            'oauth' => [
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',
                'scopes' => ['snsapi_userinfo'],
                'callback' => (String)url("Login/wechatGetInfo",['callback'=>$callback],"",true),
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
		return $oauth->redirect();
	}
	
	//获取微信授权信息
	public function wechatGetInfo(){
		$param_callback = urldecode(input("callback", ''));
		//开始授权
		$user 	= Session::get('wx_user', '');	
		if($user != ''){
			$target_url 	= Session::get('target_url', '');
			if($target_url == ''){
				$target_url = $param_callback;
			}
			$callback 	= $this->merge_link($target_url, $user);
			//尝试跳走
			header('location:' . $callback); // 跳转到 user/profile
			return;
		}	
		$callback 	= (String)url("Login/wechatGetInfo",['callback'=>$param_callback],"",true);
        $config = [
			// 'http' => $this->proxy,
            'app_id' => $this->app_id,
            'secret' => $this->secret,	
            'oauth' => [
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',
                'scopes' => ['snsapi_userinfo'],
                // 'callback' => ,
                'callback' => $callback,
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $userObj = $oauth->user()->toArray();
        $user = [
            "openid" => $userObj["id"],
            "nickname" => $userObj["nickname"],
            "avatar" => $userObj["avatar"],
        ];
		Log::info(' 授权信息 user:'.json_encode($user));		
		Session::set('wx_user', $user);
		//授权后更新微信用户信息到数据库
		$wx_userinfo 	= [];
		if($user['nickname'] != ''){
			$wx_userinfo['nickname'] 	= $user['nickname'];
		}
		if($user['avatar'] != ''){
			$wx_userinfo['avatar'] 	= $user['avatar'];
		}
		if($user['openid'] != '' && count($wx_userinfo) != 0){
			/*
			 *  登录后业务处理
			*/
		}
		$targetUrl = Session::get('target_url', '') == '' ? '/' : Session::get('target_url');
		$targetUrl 	= $this->merge_link($targetUrl, $user);
		Log::info('授权信息 targetUrl:'.json_encode($targetUrl));		
		header('location:' . $targetUrl); // 跳转到 user/profile
	}
	
	//整合登录链接
	private function merge_link($targetUrl, $user=[]){
		if(strpos($targetUrl, '#') === false){ 
			$targetUrl 	.= '/#';
		}
		if(strpos($targetUrl, '?') === false){ 
			$targetUrl 	.= '?';
		}
		else{
			$targetUrl 	.= '&';
		}
		foreach($user as $k => $v){
			$targetUrl 	.= $k.'='.$v.'&';
		}
		return $targetUrl;
	}
}