<?php

namespace App\Http\Controllers\Miniprogram;

use App\Exceptions\AlertException;
use App\Services\Auth\AuthKeyService;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;
use App\Models\User\AuthKey;
use App\Models\User\UserModel;

class Auth extends Controller
{
    /**
     * 用户认证
     * @return int uid 用户id
     * @return JWTException
     * @throws JWTException
     */
    public static function auth()
    {
        try {
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                throw new JWTException("请先授权登陆", 401);
            }
        } catch (JWTException $e) {
            throw new JWTException("登陆已过期，请重新授权登陆", 401);
        }

        // 代理
        $debug_uid = Redis::hget("fpdx_admin_debug", $user->uid);
        if (!empty($debug_uid)) {
            return $debug_uid;
        }
        return $user->uid;
    }

    /**
     * 获取用户信息
     * @return array
     * @throws JWTException
     */
    public function user()
    {
        $uid = self::auth();
        $user = UserModel::find($uid);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $user
        ];
    }

    /**
     * 绑定小程序登录方式
     * @param  Request  $request
     * @return array
     * @throws JWTException
     */
    public function bindAuthType(Request $request)
    {
        $this->validate($request, [
            'unionid' => 'required',
            'openid' => 'required'
        ]);
        try {
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                throw new JWTException("请先授权登陆", 401);
            }
        } catch (JWTException $e) {
            throw new JWTException("登陆已过期，请重新授权登陆", 401);
        }
        $public_id = config('miniprogram.public_id');
        $auth = AuthKey::where('auth_key', $request->unionid)->first();
        if (collect($auth)->isEmpty()) {
            throw new JWTException("用户未授权", 401);
        } elseif ($user->uid != $auth->uid) {
            throw new JWTException("无绑定权限", 403);
        }
        $typeAuth = AuthKey::where(array(['uid', $auth->uid], ['auth_type', $public_id]))->first();
        if (!collect($typeAuth)->isEmpty()) {
            throw new JWTException("你已绑定过该微信号，请联系管理员解绑", 403);
        }
        $authkey = new AuthKey();
        $openAuth = $authkey->where('auth_key', $request->openid)->first();
        if (collect($openAuth)->isEmpty()) {
            $openAuth = $authkey->fill([
                'uid' => $auth->uid,
                'auth_key' => $request->openid,
                'auth_type' => $public_id
            ]);
            if ($openAuth->save()) {
                return [
                    'code' => 200,
                    'message' => 'success'
                ];
            } else {
                throw new JWTException("绑定异常", 401);
            }
        } elseif ($openAuth->auth_type != $public_id) {
            throw new JWTException("该登陆key已被绑定，请联系管理员", 401);
        } else {
            return [
                'code' => 200,
                'message' => 'success'
            ];
        }
    }

    /**
     * 绑定微信id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function bindWxid(Request $request)
    {
        $this->validate($request, [
            'wxid' => 'required'
        ]);
        $wxid = $request->post('wxid');
        $uid = \App\Http\Controllers\Core\Auth::auth();
        $aks = new AuthKeyService();
        $aks->bindKey($uid, $wxid, 'wxid');
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * jscode
     * @param  string  $jscode
     * @return array
     * @throws \Exception
     */
    public function jscode(string $jscode)
    {
        $core = new Core();
        $data = $core->jscode2session($jscode);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ];
    }

    /**
     * 解密小程序数据包
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function decryptData(Request $request)
    {
        $this->validate($request, [
            'iv' => 'required',
            'session_key' => 'required',
            'encrypted_data' => 'required'
        ]);
        $appid = config('miniprogram.app_id');
        $session_key = $request->input('session_key');
        $decrypt = new Decrypt($appid, $session_key);
        $result = $decrypt->decryptData($request->input('encrypted_data'), $request->input('iv'), $data);
        if ($result == 0) {
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => $data
            );
        } else {
            throw new AlertException("解密失败", $result);
        }
    }
}
