<?php
declare (strict_types = 1);

namespace app\index\controller;

use think\facade\View;
use think\facade\Request;
use think\facade\Db;
use think\facade\Session;
use think\response\Redirect;
use think\response\Json;

class Login
{
    public function index(){
        if(Session::get('user_info')){
            return redirect('/login/logout');
        }
        return View::fetch();
    }
    /**
     * 处理登录
     */
    public function dologin(): Json
    {
        if (!Request::instance()->isPost()) return json();
        $username = Request::instance()->post('username');
        $password = Request::instance()->post('password');
        $find = Db::name('user')->where(array('username' => $username, 'is_delete' => 0, 'status' => 1))->find();
        if(!$find){
            Session::delete('user_info');
            return json(['code' => 0, 'msg' => '用户不存在']);
        }
        if(think_ucenter_md5($password, UC_AUTH_KEY) == $find['password'] && !empty($find['password'])){
            Session::set('user_info',$find);
            return json(['code'=>1,'msg'=>'登录成功','url'=>'/']);
        }else{
            Session::delete('user_info');
            return json(['code'=>0,'msg'=>'密码错误']);
        }
    }
    /**
     * 退出登录
     */
    public function logout(): Redirect
    {
        Session::delete('user_info');
        return redirect('/login/index');
    }
}