<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\User;
use App\Models\UserReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $credentials = $request->only('phone', 'password');
        if(Auth::guard('mini')->attempt($credentials)) {
            $user = Auth::guard('mini')->user();
            $user->updateToken();
            $user->avatar = $user->avatar ? $user->avatar : 'https://t18.9026.com/mini/default-user.png';
            $user->topRole = $user->getTopRole();
            return $this->success(['data' => $user]);
        }
        return $this->error(['msg' => '账号或密码错误']);
    }

    public function loginByWechat(Request $request)
    {
        $app = app('wechat.mini_program');
        if($request->input('code')) {
            $res = $app->auth->session($request->input('code'));
            if(isset($res['session_key'])) {
                $data = $app->encryptor->decryptData($res['session_key'], $request->input('iv'), $request->input('encryptedData'));
                if(isset($data['openId'])) {
                    if($request->input('bind')) {
                        $token = $request->header('X-Token');
                        $user = User::where('token', $token)->first();
                        if(!$user) return $this->error(['msg' => '找不到用户']);
                    } else {
                        $user = User::where('open_id', $data['openId'])->first();
                        if(empty($user)) return $this->error(['msg' => '用户不存在，请先绑定账户']);
                    }
                    $user->update([
                        'nickname' => $data['nickName'],
                        'avatar' => $data['avatarUrl']
                    ]);
                    $user->updateToken();
                    $user->topRole = $user->getTopRole();
                    return $this->success(['data' => $user]);
                }
            }
        }
        return $this->error(['msg' => '登陆失败']);
    }

    public function reset(Request $request)
    {
        $user = User::where('phone', $request->input('phone'))->first();
        if(!$user) return $this->error(['msg' => '账号不存在']);
        UserReset::create([
            'user_id' => $user->id,
            'phone' => $request->input('phone'),
            'name' => $request->input('name')
        ]);
        return $this->success();
    }

    public function getUserInfo()
    {
        $user = Auth::guard('mini')->user();
        $user->avatar = $user->avatar ? $user->avatar : 'https://t18.9026.com/mini/default-user.png';
        return $this->success(['data' => $user]);
    }
}
