<?php
namespace app\shequ\controller;


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

class Login extends  BaseController
{
    public function Login() {

        $where['cad.account'] = Request::param("account");
        $where['cad.password'] = md5(Request::param("password"));
        $where['cad.status'] = 1;
        $userInfo = Db::name('community_admin')->alias("cad")->leftJoin('community_role cr','cr.role_id = cad.role_id')
            ->field("cad.community_admin_id,cad.account,cad.name,cad.type,cr.url_ids,cad.village_id")
            ->where($where)->find();
        if($userInfo){
            //查看当前小区的状态
            $villageInfo= Db::name('house_village')->where(['village_id'=>$userInfo['village_id'],'status'=>1])
                ->field('village_id,village_name,village_address,village_logo,province_id,province_name,city_id,city_name,area_id,area_name')
                ->find();
            if(!$villageInfo){
                return $this->returnJson([],'小区不存在或当前小区被禁用,请联系管理员!',400);
            }
            $data['uid'] = $userInfo['community_admin_id'];
            $data['village_id'] = $villageInfo['village_id'];
            $jwt = JWT::encode($data,config("app.jwt_key"));  //根据参数生成了 token
            //把jwt放入set缓存中
            $redis= Cache::store('redis')->handler();
            $redis->setnx("community_tokens_".$data['uid'],$jwt);
            $redis->EXPIRE("community_tokens_".$data['uid'],3600); //设置过期时间
            //查询相关的能访问的导航权限
            //超级管理员
            if($userInfo['type']==1) {
                $res = Db::name('community_nav')->where(['community_nav_status'=>1])->order("sort_id,level")->field("community_nav_id,url_name,url,parent_id")->select()->toArray();
            } else { //普通管理员
                $res = Db::name('community_nav')->where(['community_nav_status'=>1])->whereIn('community_nav_id',$userInfo['url_ids'])->field("community_nav_id,url_name,url,parent_id")->order("sort_id,level")->select()->toArray();
            }
            $navs = $this->getTree($res,0,"community_nav_id");
            $userInfo['urls_id'] =$navs;
            return $this->returnJson(['token'=>$jwt,'adminInfo'=>$userInfo,'villageInfo'=>$villageInfo],'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("community_tokens_".$decodeData['uid']);
            if(!$r_token || $r_token!=$token) {
                return $this->returnJson([],'success');
            }
        } else {
            return $this->returnJson([],'error',400);

        }
    }









}