<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2019/3/6
 * Time: 10:17
 */

namespace App\Http\Controllers\Web;

use App\Models\AlbumManufacturerModel;
use App\Models\AlbumUserModel;
use Illuminate\Http\Request;
use EasyWeChat\Factory;

class AuthController extends Controller
{
    public function bind(Request $request)
    {
        $store_id = $request->input('store_id');
        $weChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $config = [
            'app_id' => $weChatApp->G_app_id,
            'secret' => $weChatApp->G_app_secret,
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/web/notify?store_id=' . $store_id,
            ]

        ];
        $app = Factory::officialAccount($config);
        $response = $app->oauth
            ->redirect();
        return $response;
    }
    public function notify(Request $request)
    {
        $store_id = $request->input('store_id');
        $weChatApp = AlbumManufacturerModel::where('store_id', $store_id)->first();
        $config = [
            'app_id' => $weChatApp->G_app_id,
            'secret' => $weChatApp->G_app_secret,
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/web/notify',
            ]
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
// 获取 OAuth 授权结果用户信息
        $user = $oauth->user()->toArray();
        $check_user = AlbumUserModel::where([['store_id',$store_id],['wechat_union_id',$user['original']['unionid']]])->first();
        if ($check_user) {
            $check_user->g_open_id = $user['id'];
            $check_user->save();
        } else {
            $data['username'] = $user['name'];
            $data['wechat_union_id'] = $user['original']['unionid'];
            $data['avatar'] = $user['avatar'];
            $data['g_open_id'] = $user['id'];
            $data['store_id'] = $store_id;
            $data['is_dealer'] = 0;
            $data['role'] = 0;
            $data['model'] = 0;
            $data['up_agent_id'] = 0;
            AlbumUserModel::create($data);
        }
        return view('web.auth.bind');
    }

    public function welcome()
    {
        return view('welcome');
    }
}