<?php

namespace Modules\User\Http\Controllers\Api\Socialite;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\User\Events\UserLoginSuccess;
use Modules\User\Models\User;

class UniCloudController extends Controller
{

    public function app(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'access_token' => 'required',
            'openid'       => 'required',
        ], [
            'access_token.required' => 'access_token必须填写',
            'openid.required'       => 'openid必须填写',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first(), 422);
        }
        $data   = [
            'access_token' => $request->access_token,
            'openid'       => $request->openid,
        ];
        $secret = config('user.socialite.unicloud.self_secret', '');
        $domain = config('user.socialite.unicloud.domain', '');
        $url    = config('user.socialite.unicloud.cloud_function_url.one_key', '');
        if (! $secret || ! $domain || ! $url) {
            return $this->failed('过程参数存在错误');
        }
        ksort($data);
        $signString = urldecode(http_build_query($data));
        $sign       = hash_hmac('sha256', $signString, $secret);
        $params     = $signString.'&sign='.$sign;
        $url        = $domain.$url.'?'.$params;
        $res        = json_decode(file_get_contents($url));

        if ($res->success) {
            $user = User::firstOrCreate([
                'username' => $res->phoneNumber,
            ], [
                'password' => 111111,
            ]);

            $token = Api::login($user);

            event(new UserLoginSuccess($user, $request, '本机一键登录'));

            return $this->success([
                'token_type'   => 'Bearer',
                'access_token' => $token,
                'is_new'       => $user->wasRecentlyCreated,
            ]);

        } else {
            return $this->failed('一键登录失败');
        }

    }

    public function query(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
        ], [
            'mobile.required' => '请传入手机号',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first(), 422);
        }
        $user = User::firstOrCreate([
            'username' => $request->mobile,
        ], [
            'password' => 111111,
        ]);

        $token = Api::login($user);

        event(new UserLoginSuccess($user, $request, '本机一键登录'));

        return $this->success([
            'token_type'   => 'Bearer',
            'access_token' => $token,
            'is_new'       => $user->wasRecentlyCreated,
        ]);
    }

}
