<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\wendasns\controller;

use app\wendasns\WenBaseController;

use app\wendasns\service\PwRegister;
use app\wendasns\model\User as byUser;
use wendasns\Wend;


class Login extends WenBaseController
{

    public function index(){
    	if($this->loginUser->isLogin){
    		error('您已经登录', [], true, (string)url('user/index'));
    	}
    	if(request()->isPost()){
    		$this->_login();
    	}
    	
    	//$referer = $this->request->header('Referer');

    	//$this->setSeo(lang('user.login'));
        return view();
    }
    
    private function _login(){
    	
    	//list($name,$value) = $this->request->post('account','','org\Filter::safeHtml');//org\Filter::safeHtml,获取post变量 并用org\Filter类的safeHtml方法过滤
    	list($name, $value) = input('post.account','','wendasns\facade\Filter::safeAccount');
    	$password = input('post.password','','');
    	$rememberme = input('post.rememberme',0,'intval');
    	$vcode = input('post.vcode','','');
    	$vcodestr = input('post.vcodestr','','');
    	
    	//检查图文验证码
    	if(configure('verify.userlogin')){
    		if(!captcha_check($vcode)){
    			error('图片验证码有误');
    		}
    	}
    	
    	//验证数据
    	try {
            $this->validate([
            	$name => $value
            ], 'login');
        } catch (think\exception\ValidateException $e) {
            // 验证失败 输出错误信息
            error($e->getError());
        }
    	$user = byUser::where($name, $value)->find();
    	
    	if(!$user){
    		error('用户不存在');
    	}
    	
    	$dm = new PwRegister();
    	$dm->uid = $user->id;
    	$dm->password = $user->password;
    	$dm->salt = $user->salt;
    	$dm->rememberme = $rememberme;
        if (($info = $dm->login($password)) instanceof Exception) {
        	error($info->getMessage());
        }else{
        	success('登录成功', [], true, (string)url('user/index'));
        }
    }
    
    
    public function logout(){
    	Wend::setCookie('wenda_user');
    	return redirect('/')->restore();//重定向跳转,需要跳转到上次记住的URL的时候使用：
    }
}
