<?php
namespace app\ucentre\controller;

use app\ucentre\WenBaseController;
use app\ucentre\model\Client;
use app\ucentre\service\PwUser;
use wendasns\facade\Wendid;
use wendasns\Wend;
use think\facade\View;

class Login extends WenBaseController
{
	protected $vo;
	
    public function index($dispatch='run')
    {
    	if(!in_array($dispatch, ['run','authorize','callback','logout'])){
    		error('404');
    	}
        return $this->$dispatch();
    }
    
    private function run()
    {
    	if($this->loginUser->isLogin){
    		error('您已经登录');
    	}
    	if(request()->isPost()){
    		$this->execute();
    	}
    	
    	//客户端
    	$config = configure('wendid');

    	if($config['system']=='client'){
    		$get = [
    			'client_id' => $config['clientId'],
    			'redirect_uri' => (string)url('ucentre/login/index',['dispatch'=>'callback'])->domain(true),
    		];
    		$url = (string)url('ucentre/login/index',['dispatch'=>'authorize'])->domain($config['serverUrl']);
    		$url .= '?'.http_build_query($get);
    		return redirect($url);
    	}
    	
		event('LoginPage');
        return View::fetch('index');
    }

    //授权登录
    private function authorize()
    {
    	$clientId = input('get.client_id',0,'intval');
    	$redirect_uri = input('get.redirect_uri','');

        $dm = Client::find($clientId);
        if(!$dm){
        	error('对不起，该网站尚未开通WendID帐号登录');
        }
        $redirect = parse_url($redirect_uri);
        $url = parse_url($dm->url);
        if($redirect['host']!=$url['host']){
        	error('redirect uri is illegal');
        }

    	if(request()->isPost()){
    		$this->vo = (object)[
    			'client' => $dm,
    			'redirect_uri' => $redirect_uri,
    		];
    		$this->execute(1);
    	}
    	
        return view('index');
    }
    
    //授权登录回调-执行本地登录
    private function callback()
    {
        $account_token = input('get.account_token','');
    	$_time = input('get.time','');
    	
    	$config = configure('wendid');

        $token = Wend::strDecrypt($account_token, $config['clientKey']);
        list($wend_id, $times, $rememberme) = explode("\t", $token);
        $time = Wend::getTime();
        if($_time!=$times){
        	error('非法请求');
        }elseif($time - $_time > 120){
        	error('请求超时');
        }
        $dm = Wendid::getUser($wend_id);
        $dm->rememberme = $rememberme;
        
        $app = empty($this->app->http->getName())?'wendasns':$this->app->http->getName();
        $class_name = '\\app\\'.$app.'\\service\\PwUser';
        try{
        	$user = new $class_name();
        	$user->login($dm);
        } catch (\think\Exception $e){
        	error($e->getMessage());
        }
    	return '<script>window.parent.location.reload();</script>';
    }
    
    //退出登录
    private function logout()
    {
    	cookie('WendaUser',null);
    	return redirect('/');//重定向跳转,需要跳转到上次记住的URL的时候使用：
    }

    private function execute($authorize = 0)
    {
    	list($name, $value) = input('post.account','','wendasns\facade\Filter::safeAccount');//org\Filter::safeHtml,获取post变量 并用org\Filter类的safeHtml方法过滤
    	$password = input('post.password', '');
    	$rememberme = input('post.rememberme', 0, 'intval');
    	$vcode = input('post.vcode', '');
    	$option = [];
    	
    	//验证数据
    	try {
            validate(\app\ucentre\validate\User::class)->check([
            	$name => $value,
            	'password' => $password,
            ]);
        } catch (\think\exception\ValidateException $e) {
            error($e->getError());
        }
    	
    	event('Login');
    	
        try{
        	$user = new PwUser();
        	$user->account = [$name, $value];
        	$user->password = $password;
        	$user->rememberme = $rememberme;
        	$dm = $user->mode($authorize)->login();
        } catch (\think\Exception $e){
        	error($e->getMessage());
        }
        
        success('登录成功', [], $dm->getUrl($this->vo));
    }
}