<?php


namespace app\admin\controller;

use app\BaseController;
use Firebase\JWT\JWT;
use think\App;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

class Login extends BaseController
{

    public function login() {
        if(Request::isPost()){

            $username = Request::param('username');
            $password = Request::param('password');

            //验证字段是否合理
            $validate = Validate::rule([
                'username|账号' => 'require', //第二个可写可不写,如果写了的话,后面自定义msesage可以自动用这个来提示,第三个验证规则可以用来确定表user中的字段的唯一性,需要与username字段对应
                'password|密码' => 'require',
            ]);

            $result = $validate->check([
                'username' => $username,
                'password' => $password,
            ]);

            if(!$result){
                $msg = $validate->getError();
                return $this->returnJson([],$msg,'404');
            }

            //数据库验证数据
            $where['ad.username'] = $username;
            $where['ad.password'] = md5($password);
            $where['ad.status'] = 1;

            $userInfo = Db::name('admin')->alias("ad")->join('admin_role','admin_role.role_id = ad.role_id')->where($where)->field("ad.type,ad.admin_id,ad.username,admin_role.name,admin_role.url_ids")->find();

            $data['uid'] = $userInfo['admin_id'];

            $jwt = JWT::encode($data,config('app.jwt_key'));  //根据参数生成了 token
            if($userInfo){
                //把jwt放入set缓存中

                $redis= Cache::store('redis')->handler();
                $redis->setnx("admin_tokens"."_".$data['uid'],$jwt);
                $redis->EXPIRE("admin_tokens"."_".$data['uid'],3600); //设置过期时间,一小时
                //查询相关的能访问的导航权限
                //超级管理员
                if($userInfo['type']==1) {
                    $res = Db::name('admin_nav')->where(['admin_nav_status'=>1])->order("sort_id,level")->field("admin_nav_id,url_name,url,parent_id")->select()->toArray();

                } else { //普通管理员
                    $res = Db::name('admin_nav')->where(['admin_nav_status'=>1])->whereIn('admin_nav_id',$userInfo['url_ids'])->field("admin_nav_id,url_name,url,parent_id")->order("sort_id,level")->select()->toArray();
                }
                $navs = $this->getTree($res,0,"admin_nav_id");
                $userInfo['urls_id'] =$navs;
                return $this->returnJson(['token'=>$jwt,'adminInfo'=>$userInfo],'success');
            } else {
                return $this->returnJson([],'用户不存在!',400);
            }
        }else {
            return $this->returnJson([],'请求错误!',400);
        }

    }



    //退出
    public function logout() {

        $token =  Request::header('token');
        //判断是否在redis中
        $redis= Cache::store('redis')->handler();
        $decodeData = (array)JWT::decode($token,"zhihuishequ",array("HS256"));
        if(!isset($decodeData['code'])){
            $r_token= $redis->del("admin_tokens_".$decodeData['uid']);
            if(!$r_token || $r_token!=$token) {
                return $this->returnJson([],'success');
            }
        } else {
            return $this->returnJson([],'error',400);

        }
    }
}