<?php
//后台登录页面控制器
namespace app\admin\controller;
use think\captcha\facade\Captcha;
use think\facade\Request;
use think\facade\Session;
use think\exception\ValidateException;

class Login
{
    
	// 登录页面
    public function index(){
		$admin_id=Session::get('admin_id');
        // 已登录自动跳转
        if (Session::has('admin_id')) {
            return redirect((string)url('Index/index'));
        }
        return View();
    }

    // 校验登录
    public function checkLogin(){
        $check =Request::checkToken('__token__');
		$tdata=Request::param();
		$newtk=token();

		IS_AJAX(Request::isAjax());
		$captcha=captcha_check($tdata['captcha']);//验证码
		$info = \app\admin\model\Admin::checkLogin($tdata['name'],$tdata['pwd']);
		
		if(empty($info)){
			$info['id']='';
			$info['is_effect']='';
		}

		$value = [
                'Token' =>$check,
                'name' =>trim($tdata['name']),
                'pwd' =>$tdata['pwd'],
                'id' =>$info['id'],
                'is_effect' =>$info['is_effect'],
                'captcha' =>$captcha,
        ];

		$validate=new \app\admin\validate\Login();//验证器
        if(!$validate->check($value)) {
			$data =['error' =>'1','msg' =>$validate->getError(),'tk'=>$newtk];
			return json($data);
        }
		
		Session::set('admin_id',$info['id']);
		$adm['id']=$info['id'];
		$adm['login_time']=time();
		$adm['login_ip']=getRealIP();
		$info = \app\admin\model\Admin::strict(false)->update($adm);
		$data =['ok' =>'1','msg' =>'登录成功','info'=>$info];
		return json($data);

    }

    // 验证码
    public function captcha(){
        return Captcha::create();
    }

}
