<?php

namespace App\Http\Controllers\Core;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\Vendor\BaiduAi\FaceService;

class Oauth extends Controller
{

    public function faceToken(Request $request)
    {
        $url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
        $data = array(
            'api_key' => 'z_TyHj53JaD8JXVLXVTPFpGqKwZVoWjv',
            'api_secret' => 'KbEfAb7eMm828ViP4_Y1oTrm4KG5_qS-',
        );
        $data = array_merge($data, $request->toArray());
        $response = \Curl::to($url)->withData($data)->post();
        return $response;
    }

    public function match(Request $request)
    {
        $this->validate($request, [
            'liveness_image' => 'required',
            'check_image' => 'required'
        ]);
        $fs = new FaceService();
        $images = array(
            [
                'image' => $request->post('liveness_image'),
                'image_type' => 'URL',
                'face_type' => 'LIVE',
                'quality_control' => 'NONE',
                'liveness_control' => 'LOW'
            ],
            [
                'image' => $request->post('check_image'),
                'image_type' => 'URL',
                'face_type' => 'LIVE',
                'quality_control' => 'NONE',
                'liveness_control' => 'NONE'
            ]
        );
        $data = $fs->match($images);
        dump($data);
    }

    public function faceverify(Request $request)
    {
        $this->validate($request, [
            'image' => 'required'
        ]);
        $fs = new FaceService();
        $images = array(
            [
                'image' => $request->post('image'),
                'image_type' => 'URL',
                'face_field' => 'occlusion,blur,completeness',
            ]
        );
        $data = $fs->faceverify($images);
        dump($data);
    }

    public function sendVerifyCode(Request $request)
    {
        $phone = $request->input('phone');
        $code = rand(1000, 9999);
        $result = \ChuanglanSms::sendSMS($phone, "【无邪科技】您的短信验证码为:{$code},若非本人操作请忽略。");
        if (isset($result['code']) && $result['code'] == '0') {
            \Cache::put("smsverifycode:{$phone}", $code, 1);
            return [
                'code' => 200,
                'message' => 'Success',
            ];
        } else {
            return [
                'code' => 401,
                'message' => '发送频繁',
            ];
        }
    }

    /**
     * @param  Request  $request
     * @return mixed
     */
    public function checkVerifyCode(Request $request)
    {
        $phone = $request->input('phone');
        $code = $request->input('code');
        if (\Cache::get("smsverifycode:{$phone}") == $code) {
            return [
                'code' => 200,
                'message' => '验证成功',
            ];
        }
        return [
            'code' => 401,
            'message' => '验证码错误',
        ];
    }
}
