<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\service;

use app\common\library\jwt\Token;
use app\common\model\Admin as AdminModel;
use app\common\model\Users as UsersModel;
use app\common\model\chat\ChatUsers as ChatUsersModel;

/**
 * @package app\common\service
 * @class Users
 * @author xzncit 2024-02-01
 */
class Users {

    /**
     * @var array
     */
    private static $user = [];

    /**
     * @param $data
     */
    public static function init($data){
        self::$user = $data??[];
    }

    /**
     * @param null $name
     * @param string $default
     * @return array|mixed|string
     */
    public static function get($name=null,$default=""){
        if(is_null($name)){
            return self::$user;
        }

        if(!isset(self::$user[$name])){
            return $default;
        }

        return self::$user[$name];
    }

    /**
     * @param $name
     * @param null $value
     */
    public static function set($name,$value=null){
        self::$user[$name] = $value;
    }

    /**
     * 获取会员信息
     * @param $name
     * @param $default
     * @return array|mixed|string|null
     */
    public static function auth($name=null,$default=null){
        try{
            if(!self::isEmpty($name)){
                return self::get($name);
            }

            $module = app('http')->getName();
            if($module == "api"){
                $user = UsersModel::where("id",Token::get("id"))->find();
            }else if($module == "adminapi"){
                $user = AdminModel::where("id",Token::get("id"))->find();
            }else if($module == "online"){
                $user = ChatUsersModel::where("id",Token::get("id"))->find();
            }else{
                return $default;
            }

            if(empty($user)){
                return $default;
            }

            self::init($user);
            return self::get($name,$default);
        }catch (\Exception $ex){
            return $default;
        }
    }

    /**
     * @param $name
     * @return bool
     */
    public static function isEmpty($name){
        return empty(self::$user[$name]);
    }

}