<?php
/**
 * @2021-7-10
**/
namespace app\Admin\controller;
use think\Db;
use app\Admin\model\User;
class Login
{

    /**
     * @method post
     * @param username 账户名
     * @param password  密码
     *
     */
    public function __construct(){
        if(request()->isOptions()){
            echo '';
            die();
        }
    }
    public function index(){
         $post=request()->post();
         $username = isset($post['username'])&&$post['username']!="" ? trim($post['username']) :"";
         if($username==""){
             return error_show(1004,"参数username 不能为空");
         }
         $password = isset($post['password'])&&$post['password']!="" ? trim($post['password']):"";
        if($password==""){
            return error_show(1004,"参数password 不能为空");
        }

        $account = Db::name("admin")->where(["is_del"=>0,"username"=>$username])->find();

        if(empty($account)){
            return error_show(1005,"账户未找到");
        }
       if($account['status']==0){
           return error_show(1005,"账户已禁用");
       }
       $pass = sha1($password.$account['salt']);
           if($pass!=$account['password']){
               return error_show(1006,"账户密码错误");
           }
        $token = makeToken($account);
        $userinfo = ["username"=>$account['username'],"nickname"=>$account['nickname'],"mobile"=>$account['mobile'],"role_id"=>$account['role_id']];
        $userinfo['token'] = $token;
        write_log("账户{$account['username']}登录系统","","login","",0);
        return app_show(0,"登录成功",$userinfo);
     }

    /**
     * @param Token
     * 退出登录
     */
     public function logout(){
         $post=request()->post();
         $token =  isset($post['token'])&&$post['token']!="" ? trim($post['token']) :"";
         if($token==""){
             return error_show(101,"参数token 不能为空");
         }
         $verify = verifyToken($token);
         if($verify['code']!=0){
             return error_show($verify['code'],$verify['msg']);
         }
         $info = Db::name("admin_token")->where(["token"=>$token])->update(['token'=>""]);
        if($info){
            return app_show(0,"退出成功");
        }else{
            return error_show(1004,"退出失败");
        }
     }

     public function LastVersion(){
         $version = Db::name("version")->order("addtime desc")->find();
         return app_show(0,"获取成功",$version);
     }

}