<?php

namespace App\Http\Controllers\api\thirdPart\weixin;

use App\Components\ApiProcurementResponse;
use App\User;
use App\UserDetail;
use Firebase\JWT\JWT;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;

class AuthController extends Controller
{
    use ApiProcurementResponse;

    public function login(): \Illuminate\Http\JsonResponse
    {
        $phone=request('phone');
        $password = request("password");
        $user=User::query()->with('roles')
            ->whereHas('userDetail',function ($query)use($phone){
            /** @var Builder $query */
            $query->where('mobile_phone',$phone);
        })->whereHas('roles',function ($builder){
                /** @var Builder $builder */
            $builder->whereIn('name',['供应商','收货员']);
            })
            ->first();
        if (!$user)return $this->error('当前用户不存在');
        if (!Hash::check($password,$user->password))return $this->error('很抱歉，您的手机号和密码不匹配');

        $credentials = [
            'id'=>$user->id,
            'name'=>$user->name,
        ];
        $token = $this->getJWTToken($credentials);
        $userType=0;
        foreach ($user->roles as $role){
            if ($role->name=='供应商')$userType=1;
            if ($role->name=='收货员')$userType=2;
        }
        return $this->success($token,$userType);
    }

    public function getJWTToken($value): string
    {
        $time = time();
        $payload = [
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time+7200,
            'data' => [
                'id' => $value['id'],
                'name' => $value['name']
            ]
        ];
//        $key =  env('JWT_SECRET');
        $key =  config('weiXin.jwt.JWT_SECRET');
        $alg = 'HS256';
        $token = JWT::encode($payload,$key,$alg);
        return $token;
    }

    public function banding(Request $request): \Illuminate\Http\JsonResponse
    {
        if (!$request->input('code'))return $this->error('code 不能为空！');
        $requests= [
            'appid'=>config('weiXin.xiaoChengXu.appId'), //小程序appid
            'secret'=>config('weiXin.xiaoChengXu.appSecret'), //小程序appsecret
            'js_code'=>$request->input('code'),
            'grant_type'=>'authorization_code',
        ];
        $url='https://api.weixin.qq.com/sns/jscode2session?';
        $get=Http::get($url,$requests);
        $resp=$get->json();
        if (!isset($resp['openid'])) return $this->error('授权失败，无法获取openid');
        UserDetail::query()
            ->where('user_id',Auth::user()['id'])
            ->update(['procurement_wechat_open_id'=>$resp['openid'],]);
        return $this->success($resp['openid'],'获取openID成功');
    }

}
