<?php

namespace App\Utils;

// 权限工具类
class Auth
{
    // 白名单接口
    public array $whiteApi;

    // 特殊接口 存在需要
    public array $specialApi;

    public function __construct()
    {
        $this->whiteApi = [
            "/" => "*",
            "/patient/index" => "get",
            "/login/wechat_mobile_login" => "post", // 微信登陆
            "/login/mobile_login" => "post", // 手机号登陆
            "/code/phone" => "post",// 获取手机号验证码
            "/disease/expertise" => "get",// 疾病专长列表-搜索使用
            "/area/province" => "get",// 获取省份信息
            "/area/city" => "get", // 获取城市信息
            "/area/county" => "get", // 获取区县信息
            "/callback/wxpay/inquiry/success" => "post", // 微信问诊支付回调
            "/callback/wxpay/inquiry/refund" => "post", // 微信问诊退款回调
            "/callback/wxpay/product/success" => "post", // 微信药品支付回调
            "/callback/wxpay/product/refund" => "post", // 微信药品退款回调
            "/callback/im" => "post", // im回调
            "/callback/platform/logistics" => "post", // 处方平台物流回调
            "/test" => "get", // 测试
        ];
    }

    /**
     * 检测接口白名单
     * @param string $path_info 请求地址 /v1/user/info
     * @param string $method 请求方式 POST
     * @return bool true:在白名单 false:不在白名单
     */
    public function checkApiWhiteList(string $path_info,string $method): bool
    {
        // 版本白名单-app使用
        /*$version_white_list = config('jwt.version_white_list', []);
        if (!empty($version_white_list)) {
            foreach ($version_white_list as $value) {
                $req = substr_compare($path_info,"/" . $value,0,strlen($value));
                if ($req === 0){
                    return true;
                }
            }
        }*/

        if(!empty($this->whiteApi)){
            if (array_key_exists($path_info, $this->whiteApi)) {
                if ($this->whiteApi[$path_info] == '*') {
                    return true;
                }
                if (stristr($this->whiteApi[$path_info], $method)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 检测token的快过期时间.
     * @param array $token token
     */
    public function checkTokenExpTime(array $token): bool
    {
        $time_difference = $token['exp'] - time();

        // 设定24小时过期时间
        if ($time_difference < (3600 * 24)) {
            return true;
        }
        return false;
    }
}