<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */



namespace app\api\service;


use app\common\cache\UserTokenCache;
use app\common\model\UserSession;
use think\facade\Config;

class UserTokenService
{
    /**
     * @notes 设置或更新用户token
     * @param $userId
     * @param $terminal
     * @param int $multipointLogin
     * @return array|false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function setToken($userId, $terminal)
    {
        $time = time();
        $userSession = UserSession::where([['user_id', '=', $userId], ['terminal', '=', $terminal]])->find();

        //获取token延长过期的时间
        $expireTime = $time + Config::get('project.user_token.expire_duration');
        $userTokenCache = new UserTokenCache();

        //token处理
        if ($userSession) {

            //清空缓存
            $userTokenCache->deleteUserInfo($userSession->token);
            //重新获取token
            $userSession->token = create_token($userId);
            $userSession->expire_time = $expireTime;
            $userSession->update_time = $time;
            $userSession->save();
        } else {
            //找不到在该终端的token记录，创建token记录
            $userSession = UserSession::create([
                'user_id' => $userId,
                'terminal' => $terminal,
                'token' => create_token($userId),
                'expire_time' => $expireTime
            ]);

        }
        return $userTokenCache->setUserInfo($userSession->token);
    }

    /**
     * @notes 延长token过期时间
     * @param $token
     * @return array|false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function overtimeToken($token)
    {
        $time = time();
        $adminSession = UserSession::where('token', '=', $token)->find();
        //延长token过期时间
        $adminSession->expire_time = $time + Config::get('project.user_token.expire_duration');
        $adminSession->update_time = $time;
        $adminSession->save();

        try {
            $ip = $_SERVER['REMOTE_ADDR'];
            $ip_address = '';
            // 初始化，指定QQWry.dat文件路径
            $qqwry = new \app\common\service\QQWry('qqwry.dat');
            // 查询IP地理位置
            $location = $qqwry->getLocation($ip);
            $ip_address = $location['country'];
            // 记录ip地址，登录时间
            \app\common\model\User::update(['ip'=>$ip,'ip_address'=>$ip_address,'login_time'=>time()],['id'=>$adminSession->user_id]);
            
        } catch (\Exception $e) {
            // echo "发生错误: " . $e->getMessage();
        }
        
        return (new UserTokenCache())->setUserInfo($adminSession->token);
    }

    /**
     * @notes 设置token为过期
     * @param $token
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function expireToken($token)
    {
        $userSession = UserSession::where('token', '=', $token)
            ->find();
        if (empty($userSession)) {
            return false;
        }

        $time = time();
        $userSession->expire_time = $time;
        $userSession->update_time = $time;
        $userSession->save();

        return (new  UserTokenCache())->deleteUserInfo($token);

    }

}