<?php

namespace App\Http\Controllers\V1;

use App\Models\Account;
use App\Models\User;
use Cache;
use EasyWeChat\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Laravel\Socialite\Facades\Socialite;
use PHPUnit\Util\Exception;
use Validator;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        try {
            $req = $request->post();
            $this->validate($request, [
                'account'      => 'required|digits:11',
                'password'     => 'required',
                'code'      => 'required',
            ]);

            $account = Account::where('account', $req['account'])
                ->where('status', 1)
                ->first();

            if(!$account){
                return $this->error('没有找到相关账号');
            }

            if(!\Hash::check($req['password'], $account->password)){
                return $this->error('账号或密码错误');
            }

            $app = Factory::miniProgram(config('wechat.mini_program.default'));
            $data = $app->auth->session($req['code']);
            $user = User::where('open_id',$data['openid'])->first();
            $user->account_id = $account->id;
            $user->save();

            $token = Auth::guard('api')->fromUser($user);

            $user = User::with(['account'])->where('id', $user->id)->first();
            $data = [
                'token' => "Bearer " . $token,
                'user_info' => $user,
            ];
            return $this->success($data);
        }catch (\Exception $ex){
            return $this->error('账号或密码不正确，请重新输入');
        }
    }

    public function wechatMiniCode(Request $request): JsonResponse
    {
        try {
            $req = $request->post();
            $this->validate($request, [
                'code'      => 'required',
            ]);
            $app = Factory::miniProgram(config('wechat.mini_program.default'));
            $data = $app->auth->session($req['code']);
            $user = User::where('open_id',$data['openid'])->first();
            if(!$user){
                $user = new User();
                $user->open_id = $data['openid'];
            }

            $user->remember_token = $data['session_key'];
            $user->save();

            return $this->success();
        }catch (\Exception $ex){
            return $this->error($ex->getMessage());
        }
    }

    public function wechatMiniPhone(Request $request)
    {
        try{
            $req = $request->post();
            $this->validate($request, [
                'encryptedData' => 'required',
                'iv'            => 'required',
            ]);
            $app = Factory::miniProgram(config('wechat.mini_program.default'));
            $user = \user()->makeVisible('remember_token');
            $decryptedData = $app->encryptor->decryptData($user['remember_token'], $req['iv'], $req['encryptedData']);

            $account = Account::where('account', $decryptedData['phoneNumber'])
                ->where('status', 1)
                ->first();
            if(!$account){
                return $this->error('没有找到相关账号');
            }

            $user = User::where('id', $user['id'])->first();
            if($user->mobile != $decryptedData['phoneNumber']) {
                $user->mobile = $decryptedData['phoneNumber'];
                $user->account_id = $account->id;
                $user->save();
            }

            $token = Auth::guard('api')->fromUser($user);

            $user = User::with(['account'])->where('id', $user->id)->first();
            $data = [
                'token' => "Bearer " . $token,
                'user_info' => $user,
            ];
            return $this->success($data);

        }catch (\Exception $ex){
            return $this->error($ex->getMessage());
        }
    }


}
