<?php

namespace App\Http\Controllers\Auth;

use App\Exceptions\AlertException;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Core\Auth;
use App\Models\PartnerModel;
use App\Models\User\UserModel;
use App\Models\User\AuthKey;
use App\Services\Auth\PhoneService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Ixudra\Curl\Facades\Curl;

class AuthController extends Controller
{
    /**
     * 验证当前手机号-发送验证码
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @throws AlertException
     */
    public function sendVerify2Current()
    {
        $uid = Auth::auth();
        $user = UserModel::findOrFail($uid);
        if (empty($user->phone)) {
            throw new AlertException('你还没有绑定手机号', 101);
        }

        $ps = new PhoneService();
        if ($ps->sendVerifyCode($user->phone)) {
            return array(
                'code' => 200,
                'message' => 'success'
            );
        }

        throw new AlertException('发送失败', 102);
    }

    /**
     * 验证当前手机号-检验验证码
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function checkVerify2Current(Request $request)
    {
        $this->validate($request, ['code' => 'required']);
        $uid = Auth::auth();
        $user = UserModel::findOrFail($uid);
        if (empty($user->phone)) {
            throw new AlertException('你还没有绑定手机号', 101);
        }

        $code = $request->post('code');
        if (Cache::get("smsverifycode:{$user->phone}") == $code) {
            return [
                'code' => 200,
                'message' => 'success',
            ];
        } else {
            return [
                'code' => 401,
                'message' => '验证码错误',
            ];
        }
    }

    /**
     * 换绑手机号-发送验证码
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function sendVerify2New(Request $request)
    {
        $this->validate($request, ['phone' => 'required']);
        $phone = $request->post('phone');
        Auth::auth();
        $ps = new PhoneService();
        if ($ps->sendVerifyCode($phone)) {
            return array(
                'code' => 200,
                'message' => 'success'
            );
        }

        throw new AlertException('发送失败', 102);
    }

    /**
     * 换绑手机号-检验验证码
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function checkVerify2New(Request $request)
    {
        $this->validate($request, ['phone' => 'required', 'code' => 'required']);
        $phone = $request->post('phone');
        $code = $request->post('code');
        $uid = Auth::auth();
        if (Cache::get("smsverifycode:{$phone}") == $code) {
            $puser = UserModel::where('phone', $phone)->first();
            if (!collect($puser)->isEmpty()) {
                $ack = uniqid();
                Cache::put("fpdx:checkverify2new:{$ack}", $puser->phone, 1);
                return array(
                    'code' => 201,
                    'message' => '该手机号已绑定了其他账号',
                    'data' => array(
                        'nickname' => $puser->nickname,
                        'ack' => $ack
                    )
                );
            }

            UserModel::where('uid', $uid)->update(['phone' => $phone]);
            return [
                'code' => 200,
                'message' => 'success',
            ];
        } else {
            return [
                'code' => 401,
                'message' => '验证码错误',
            ];
        }
    }

    /**
     * 绑定手机号
     * @param  Request  $request
     * @return array
     */
    public function bindPhone(Request $request)
    {
        $this->validate($request, ['phone' => 'required']);
        $phone = $request->post('phone');
        $result = Curl::to(env("AUTH_URL") . "/api/auth/bind")
            ->withHeader("authorization", $request->header("authorization"))
            ->withData([
                'authkey' => $phone,
                'authtype' => 'phone'
            ])->asJsonResponse(true)->put();
        return $result;
    }

    /**
     * 换绑冲突手机号
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @throws AlertException
     */
    public function changePhone(Request $request)
    {
        throw new AlertException("暂停换绑手机号");
        $uid = Auth::auth();
        $this->validate($request, ['ack' => 'required']);
        $ack = $request->post('ack');
        $phone = Cache::get("fpdx:checkverify2new:{$ack}");
        if (empty($phone)) {
            throw new AlertException("验证码失效,请重新验证", 202);
        }

        $puser = UserModel::where('phone', $phone)->firstOrFail();
        DB::beginTransaction();
        try {
            $puser->phone = null;
            $puser->save();
            PartnerModel::where('id', $puser->partner_id)->update(['is_sell' => 0]);
            UserModel::where('uid', $uid)->update(['phone' => $phone]);
            DB::commit();
            return response([
                'code' => 200,
                'message' => 'success'
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            throw $exception;
        }
    }
}
