<?php

namespace App\Http\Controllers\WapAlipay\Oauth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cookie;
use App\Modules\User\Services\UserService;
use Log;
use DB;
use GuzzleHttp\Client;

class UsersController extends Controller
{

    /**
     * 微信授权回掉
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function Aliback(Request $request,$distribution_channel_id)
    {
        if(!is_numeric($distribution_channel_id)){
            $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }
        $url = Cookie::get('auth_redirect');
        //auth_code、app_id、scope

        $auth_code = $request->get('auth_code');
        $app_id = $request->get('app_id');
        $scope = $request->get('scope');

        return redirect()->to(urldecode($url));
    }

    /**
     * 授权用户信息
     * @param $data
     * @return bool
     */
    protected function createUser($data)
    {
        if (empty($data['unionid']) || empty($data['openid'])) return false;
        $user = UserService::getUserByUnionAndChannelId($data['openid'],$data['distribution_channel_id']);
        if ($user) return $user;
        return UserService::addUser(
            ['openid' => $data['openid'],
                'unionid' => $data['unionid'],
                'distribution_channel_id' => $data['distribution_channel_id'],
                'send_order_id'=>$data['send_order_id'],
                'is_new'=>1
            ]);
    }

    /**
     *使用auth_code换取接口access_token及用户userId
     * @param string $auth_code
     * @return string
     */
    private function authToUserInfo(string $auth_code):string{
        $client = new Client([
            'timeout'  => 3,
        ]);
        $res = null;
        try{
            $res = $client->request('POST','https://openapi.alipay.com/gateway.do',[
                'form_params'=>[
                    'grant_type'=>'authorization_code',
                    'code'=>$auth_code
                ]
            ])->getBody()->getContents();
        }catch (\Exception $e){
            return '';
        }
        if(empty($res)){
            return '';
        }

        $res = json_decode($res,1);
        if(isset($res['alipay_system_oauth_token_response'])){
              return   $res['alipay_system_oauth_token_response']['user_id'];
        }

        return '';
    }
}