<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\api\channel;

use app\repository\user\UserRepository;
use app\service\AuthService as JwtAuthService;
use app\service\StorageService;
use app\service\api\BaseApiService;
use app\service\domain\channel\CoreChannelAuthService;
use think\Request;


/**
 * 渠道认证服务
 * Class AuthService
 * @package app\service\api\channel
 */
class AuthService extends BaseApiService
{

    /**
     * 微信小程序登录
     * @param Request $request 请求对象
     * @return array
     */
    public function weappLogin(Request $request): array
    {
        return $this->buildLoginResponse(
            $request,
            $this->core()->loginWithWeappCode(
                trim((string)$request->post('code', '')),
                $this->resolveActorUserId($request)
            )
        );
    }


    /**
     * 微信授权登录
     * @param Request $request 请求对象
     * @return array
     */
    public function wechatAuthorize(Request $request): array
    {
        return $this->core()->buildWechatOauthUrl(
            trim((string)$request->get('scope', 'snsapi_userinfo')),
            trim((string)$request->get('state', ''))
        );
    }


    /**
     * 微信回调登录
     * @param Request $request 请求对象
     * @return array
     */

    public function wechatCallback(Request $request): array
    {
        return $this->buildLoginResponse(
            $request,
            $this->core()->loginWithWechatCode(
                trim((string)$request->get('code', '')),
                trim((string)$request->get('state', '')),
                $this->resolveActorUserId($request)
            )
        );
    }


    /**
     * 支付宝回调登录
     * @param Request $request 请求对象
     * @return array
     */

    public function aliappLogin(Request $request): array
    {
        return $this->buildLoginResponse(
            $request,
            $this->core()->loginWithAliappAuthCode(
                trim((string)$request->post('auth_code', '')),
                $this->resolveActorUserId($request)
            )
        );
    }


    /**
     * 微信手机号登录登录
     * @param Request $request 请求对象
     * @return array
     */

    public function weappPhoneLogin(Request $request): array
    {
        return $this->buildLoginResponse(
            $request,
            $this->core()->loginWithWeappPhoneCode(
                trim((string)$request->post('code', '')),
                trim((string)$request->post('iv', '')),
                trim((string)$request->post('encrypted_data', '')),
                $this->resolveActorUserId($request)
            )
        );
    }

    /**
     * 构建登录响应
     * @param Request $request 请求对象
     * @param array $result 登录结果
     * @return array
     */
    private function buildLoginResponse(Request $request, array $result): array
    {
        if ((int)($result['code'] ?? 0) !== 0) {
            return $result;
        }

        $userId = (int)($result['data']['user_id'] ?? 0);
        $user = $this->userRepository()->findById($userId);
        if (!$user || (int)($user->status ?? 0) !== 1) {
            return ['code' => 1, 'msg' => ''];
        }

        return [
            'code' => 0,
            'msg' => (string)($result['msg'] ?? ''),
            'data' => [
                'token' => JwtAuthService::createToken($userId),
                'is_new_user' => (int)($result['data']['is_new_user'] ?? 0),
                'channel_auth' => $result['data']['channel_auth'] ?? [],
                'user' => [
                    'id' => (int)$user->id,
                    'username' => (string)$user->username,
                    'nickname' => (string)($user->nickname ?? ''),
                    'avatar' => StorageService::toFullAssetUrl($request, (string)($user->avatar ?? '')),
                    'verify_status' => (int)($user->verify_status ?? 0),
                    'level_id' => (int)($user->level_id ?? 0),
                ],
            ],
        ];
    }

    /**
     * 解析请求头中的用户ID
     * @param Request $request 请求对象
     * @return int
     */
    private function resolveActorUserId(Request $request): int
    {
        $token = trim((string)$request->header('Authorization', ''));
        if ($token === '') {
            return 0;
        }

        if (stripos($token, 'Bearer ') === 0) {
            $token = trim(substr($token, 7));
        }

        if ($token === '') {
            return 0;
        }

        $payload = JwtAuthService::validateToken($token);
        if (!(bool)($payload['ok'] ?? false) || (int)($payload['type'] ?? 1) !== 1) {
            return 0;
        }

        return max(0, (int)($payload['uid'] ?? 0));
    }

    /**
     * 获取核心认证服务
     * @return CoreChannelAuthService
     */
    private function core(): CoreChannelAuthService
    {
        return $this->app->make(CoreChannelAuthService::class);
    }

    /**
     * 获取用户仓库
     * @return UserRepository
     */
    private function userRepository(): UserRepository
    {
        return $this->app->make(UserRepository::class);
    }
}