<?php
/**
 * Created by PhpStorm.
 * User: yangx
 * Date: 2020/6/23
 * Time: 下午12:19
 */

namespace App\Http\Controllers\Web;


use App\Exceptions\ControllerException;
use App\Http\Controllers\Controller;


use Illuminate\Support\Facades\Session;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function login(Request $request)
    {
        if (request()->isMethod('post')) {


            if (!$request->password) {
                throw new ControllerException(400, '口令不能为空');
            }
            if (!$request->name) {
                throw new ControllerException(400, '昵称必须填写');
            }

            $user = DB::connection('mongodb')       //选择使用mongodb
            ->collection('users')->where('name',$request->name)->first();

            if ($user){
                if ($user['password'] == md5($request->password)){
                    $result = true;
                }else{
                    $result = false;
                }

                if (!$result){
                    return error('用户验证失败');
                }

                $id = ($user['_id'])->jsonSerialize();
                $user['_id'] = $id['$oid'];

                Session::put("user",json_encode($user));
                return success($user);
            }

            return error('用户验证失败');


        } else {

            return view('admin.login');
        }
    }

    /**
     * 退出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        Session::remove('user');
        return Redirect('/web/login');

    }
}