<?php
namespace app\wuye\controller;


use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class Login extends \app\BaseController
{
    public function Login() {

        $where['pad.account'] = Request::param("username");
        $where['pad.password'] = md5(Request::param("password"));
        $userInfo = Db::name('property_admin')->alias("pad")->leftJoin('ruer_property_role','ruer_property_role.role_id = pad.role_id')->where($where)->field("pad.property_id,pad.property_admin_id,pad.account,ruer_property_role.name,pad.type,ruer_property_role.url_ids")->find();
        if($userInfo){
            //判断物业公司装填
            $propertyInfo = DB::name('house_property')->where(['property_id'=>$userInfo['property_id']])->field('status,property_name')->find();
            if($propertyInfo['status'] != 1) {
                return $this->returnJson([],'物业公司不存在或被禁用!',400);
            }
            //把jwt放入redis缓存中
            $data['uid'] = $userInfo['property_admin_id'];
            $data['property_id'] = $userInfo['property_id'];
            $jwt = JWT::encode($data,config("app.jwt_key"));  //根据参数生成了 token;

            $redis= Cache::store('redis')->handler();
            $redis->setnx("property_tokens_".$data['uid'],$jwt);
            $redis->EXPIRE("property_tokens_".$data['uid'],3600); //设置过期时间
            //查询相关的能访问的导航权限
            //超级管理员
            if($userInfo['type']==1) {
                $res = Db::name('property_nav')->where(['property_nav_status'=>1])->order(['level'=>'asc','sort_id'=>'desc'])->field("property_nav_id,url_name,url,parent_id")->select()->toArray();
            } else { //普通管理员
                $res = Db::name('property_nav')->where(['property_nav_status'=>1])->whereIn('property_nav_id',$userInfo['url_ids'])->field("property_nav_id,url_name,url,parent_id")->order(['level'=>'asc','sort_id'=>'desc'])->select()->toArray();
            }
            $navs = $this->getTree($res,0,"property_nav_id");
            $userInfo['urls_id'] =$navs;
            $userInfo['property_name'] = $propertyInfo['property_name'];
            return $this->returnJson(['token'=>$jwt,'adminInfo'=>$userInfo],'success');
        } 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("property_tokens_".$decodeData['uid']);
            if(!$r_token || $r_token!=$token) {
                return $this->returnJson([],'success');
            }
        } else {
            return $this->returnJson([],'error',400);

        }
    }

}