<?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
{
    protected $model;
    public function __construct()
    {
        $this->model = new User();
    }
    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');
        $session_key = $request->input('session_key');
        if(!$session_key && $request->input('code')) {
            $res = $app->auth->session($request->input('code'));
            if (empty($res['openid']) || empty($res['session_key'])){
                return $this->error(['msg' => '微信code错误']);
            }
            if(isset($res['session_key'])) $session_key = $res['session_key'];

            $data = $app->encryptor->decryptData($session_key, $request->input('iv'), $request->input('encryptedData'));
            Log::info('info'.json_encode($data));
            Log::info('info'.json_encode($res));

            if(isset($data['phoneNumber'])) {
                $user = Auth::guard('mini')->user();
                //在数据库中若存在该手机号码的数据需要update进行修改数据、若不存在需要向数据库中添加数据
                $user = User::where("phone","=",$data['phoneNumber'])->first();
                if(!empty($user)){
                    if(empty($user->open_id)){
                        //存在手机号码直接修改
                        User::where('phone',$data['phoneNumber'] )->update(['open_id' => $res['openid'],'session_key'=>$res['session_key']]);
                    }
                    $user->updateToken();
                    $user = $user->getUserInfo($session_key);
                    return $this->success(['data' => $user]);
                } else {

                    //不存在手机号码直接添加数据
                    $user = User::firstOrCreate([
                        'open_id' => $res['openid']
                    ], [
                        'open_id' => $res['openid'],
                        'session_key'=>$res['session_key'],
                        'phone' => $data['phoneNumber'],
                        //'password' => bcrypt('123456'),
                    ]);
                    $user->updateToken();
                    $user = $user->getUserInfo($session_key);
                }
                return $this->success(['data' => $user]);
            }

            return $this->error(['msg' => '获取失败']);

        }
        if($session_key) {
            $data = $app->encryptor->decryptData($session_key, $request->input('iv'), $request->input('encryptedData'));
            Log::info('info'.json_encode($data));
            $user = User::where("phone","=",$data['phoneNumber'])->first();
            if(empty($user)){
                return $this->error(['msg' => '账号错误，请重新登录']);
            }
            return $this->success(['data' => $user]);
        }
        return $this->error(['msg' => '获取失败']);
    }

    public function loginByWechat1(Request $request)
    {
        $app = app('wechat.mini_program');
        $session_key = $request->input('session_key');
        if(empty($session_key) && $request->input('code')) {
            $res = $app->auth->session($request->input('code'));
            if(isset($res['session_key'])) $session_key = $res['session_key'];
        }
        if($session_key) {
            $data = $app->encryptor->decryptData($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::firstOrCreate([
                        'open_id' => $data['openId']
                    ], [
                        'name' => $data['nickName'],
                        'nickname' => $data['nickName'],
                        'avatar' => $data['avatarUrl']
                    ]);
                    if(empty($user)) return $this->error(['msg' => '用户不存在，请先绑定账户']);
                }
                $union_id = isset($data['unionId']) ? $data['unionId'] : $user->union_id;
                $user->update([
                    'nickname' => $data['nickName'],
                    'avatar' => $data['avatarUrl'],
                    'union_id' => $union_id
                ]);
                $user->updateToken();
                $user = $user->getUserInfo($session_key);
                return $this->success(['data' => $user]);
            }
        }
        return $this->error(['msg' => '登陆失败']);
    }

    public function parsePhone(Request $request)
    {
        $app = app('wechat.mini_program');
        $session_key = $request->input('session_key');
        if(!$session_key && $request->input('code')) {
            $res = $app->auth->session($request->input('code'));
            Log::info('进入parsePhone函数 code是',$request->input('code').PHP_EOL);
            if(isset($res['session_key'])) $session_key = $res['session_key'];
        }
        if($session_key) {
            Log::info('进入parsePhone函数 有code是',$request->input('code').PHP_EOL);

            $data = $app->encryptor->decryptData($session_key, $request->input('iv'), $request->input('encryptedData'));
            Log::info('进入parsePhone函数 解析信息',json_encode($data));

            if(isset($data['phoneNumber'])) {
                Log::info('进入parsePhone函数 没有电话号码');

                $user = Auth::guard('mini')->user();
                //在个人信息中的第三个选项的手机号码绑定这一步不是先修改的操作而是先判断手机号码是否存在于数据库中，若存在于数据库就可以不用修改了直接返回该手机号码已经在后台设置了
                $phone = User::where("phone","=",$data['phoneNumber'])->first();
                if(!empty($phone)){
                    return $this->error(['msg' => '后台已经存在这个手机号码了，请换一个手机号码绑定']);
                }
                $user->update(['phone' => $data['phoneNumber']]);
                $user = $user->getUserInfo($session_key);
                return $this->success(['data' => $user]);
            }

            return $this->error(['msg' => '获取失败']);
        }
        Log::info('进入parsePhone函数 没有code'.PHP_EOL);

        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';
        $user = $user->getUserInfo();
        return $this->success(['data' => $user]);
    }
}
