<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\Admin as AmdinModel;

class Login extends Base
{
    /**
     * 用户登录
     */
    public function login()
    {
        // 已登录
        $uid = session('uid');
        if (session('uid')) {
            $this->redirect(url('@admin/Index/index/tab/index'));
        }

        // 判断提交方式
        if (request()->isPost()) {
            $username = input("post.username");
            $password = input("post.password");

            $captcha = input("post.captcha");
            if(!captcha_check($captcha)){
                //验证失败
                $this->error('登录失败，验证码不正确!');
            };

            $admin = AmdinModel::get(['username' => $username]);
            if ($admin && $admin->password == md5($password)) {
                session('uid', $admin['id']);          // 当前用户id
                session('username', $admin['username']);   // 当前用户昵称

                $admin->is_login = 1;
                $admin->save();
                $this->success('登录成功,正跳转至系统首页...', url('@admin/Index/index/tab/index'));
            }else{
                $this->error('登录失败,用户名或密码不正确!');
            }
        }else{
            return view("admin/login");
        }
    }

    /**
     * 用户注销
     */
    public function logout()
    {
        $uid = session('uid');
        if ($uid && AmdinModel::get(intval($uid))) {
            $admin = AmdinModel::get(intval($uid));
            $admin->is_login = 0;
            $admin->save();
        }
        // 清除所有session
        session(null);
        $this->redirect(url('@admin/Login/login'));
    }
}
