<?php
/**
 * Created by PhpStorm.
 * User: qiuzijian
 * Date: 4/1/22
 * Time: 6:29 PM
 */

namespace Modules\Admin\Http\Controllers\Api;

use App\Enum\ApiEnum;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Admin\Entities\User;
use Modules\Admin\Http\Requests\TokenRequest;
use Modules\Staff\Entities\Staff;
use Symfony\Component\HttpFoundation\Response;

class TokenController extends Controller
{
    public function token(Request $request)
    {
        $result['status'] = true;
        $result['msg']    = ApiEnum::RETURN_SUCCESS;
        $result['data']   = [];

        $username = $request->input('username');

        $user = \App\User::where('staff_num', $username)->first();
        if (!$user) {
            return $this->error(1001, '用户不存在');
        }

        $result = $this->issueToken($request, 'password');
        if ($result->getStatusCode() == 401) {
            return $this->error(1002, '密码错误');
        }

        $data = json_decode($result->getContent(), true);

        $result = [
            'code'    => 0,
            'message' => 'SUCCESS',
            'data'    => $data
        ];

        return response()->json($result);
    }

    protected function error($code = 1, $msg = '')
    {
        return [
            'code'    => $code,
            'message' => $msg,
        ];
    }

    /**
     * Passport 接口请求
     * @param Request $request
     * @param         $grant_type
     * @param string  $provider
     * @param string  $scope
     * @return Response
     */
    protected function issueToken(Request $request, $grant_type, $provider = 'users', $scope = '*'): Response
    {
        $client = config('passport.password');
        $params = [
            'grant_type'    => $grant_type,
            'client_id'     => $client['client_id'],
            'client_secret' => $client['client_secret'],
            'username'      => $request->username ?: $request->email,
            'password'      => $request->password,
            'provider'      => $provider,
            'scope'         => $scope,
        ];

        $proxy = $request::create('oauth/token', 'POST');
        $proxy->request->add($params);
        return app()->handle($proxy);
    }
}