<?php

namespace Application\Form;


use Application\Common\RedisEnum;
use Application\Service\Extension\Laminas;
use Overtrue\Socialite\User;

class LoginForm
{

    public string $code;

    public function getLoginInfo($code): string
    {
        //获取hash值
        $data['code'] = $code;
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $data['create_time'] = time() + 180;
        return serialize($data);
    }

    /**
     * 设置用户状态, 及token
     * @param User $user
     * @return array
     */
    public function setCallback(User $user)
    {
        $query = Laminas::$serviceManager->adminUser->fetchOne([
            'where' => [
                'openid' => $user->getId(),
                'is_del' => 0
            ]
        ]);

        // 用户未绑定
        if (!$query) {
            // 前端需要用这些信息做绑定
            $status = [
                'bind_status' => -1,
                'nickname' => $user->getNickname(),
                'avatar' => $user->getAvatar(),
                'openid' => $user->getId(),
            ];
        } else {
            $status = Laminas::$serviceManager->identity->getLoginInfo($query['id']);
            $status['bind_status'] = 1;
            $data['id'] = $query['id'];
            // 更新用户信息, 头像, 昵称
            $data['nickname'] = $user->getNickname();
            $data['avatar'] = $user->getAvatar();
            Laminas::$serviceManager->adminUser->save($data);
        }

        // 插入用户状态, 3600秒生存时间, 防止扫完码不取数据一直占用内存
        Laminas::$serviceManager->redisExtend->getRedisInstance()->setex(RedisEnum::USER_STATUS . $this->code, 60 * 60 , json_encode($status));

        return $status;
    }

}