<?php

namespace  Api\PhpServices\User;

use Api\PhpUtils\Http\Request;
use Api\PhpUtils\Log\FileLog;

class WechatBind
{
    /**
     * 获取微信绑定用户信息
     *
     * @param array $params
     *      $params['openid'=> 'openid', 'user_id'=> 123]，非必填，至少一个
     * @return array
     */
    public static function getUserWechatBind($params)
    {
        $url = config('interface', 'goods.public.user_wechat_bind');
        $res = (new Request())->get($url, $params);
        if ($res['code'] == 0 && isset($res['response'])) {  
            return !empty($res['response']['result']) ? $res['response']['result'] : [];
        }
        return [];
    }

    /**
     * 是否是新微信用户, 默认注册时间24小时以内算是新用户
     *
     * @param string $openid
     * @return array
     */
    public static function isNewWechatUser($openid, int $timeInterval = 86400)
    {
        $url = config('interface', 'goods.public.user_wechat_bind');
        $res = (new Request())->get($url, ['openid'=> $openid]);
        if ($res['code'] == 0 && isset($res['response'])) {  
            if(empty($res['response']['result'])) {
                return true;//没有查到数据暂时先认定为新用户
            }
            $userInfo = $res['response']['result'];
            $userInfo = current($userInfo);
            if ((strtotime($userInfo['create_time']) + $timeInterval) > time()) {
                return true;
            }
            return false;
        }
        // 没有查询到对应的openid数据
        FileLog::error("调用isNewWechatUser方法未获取到数据:", json_encode(['openid' => $openid, 'timeInterval' => $timeInterval, 'res' => $res]));
        return false;
    }
}
