<?php

namespace Modules\User\Http\Controllers\Api\Certification;

use App\Api\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Jason\Api\Api;
use Modules\User\Http\Requests\CertificationRequest;
use Modules\User\Http\Resources\UserCertificationResource;
use Modules\User\Models\UserCertification;
use Modules\User\Models\UserCertificationConfig;

class IndexController extends Controller
{

    public function index()
    {
        $user = Api::user();
        if (! $user->certification) {
            return $this->failed('暂无认证记录');
        }

        return $this->success(new UserCertificationResource($user->certification));
    }

    /**
     * Notes   : 判定认证与秘钥
     *
     * @Date   : 2021/5/17 16:52
     * @Author : Mr.wang
     * @return JsonResponse
     */
    public function certified(): JsonResponse
    {
        $user = Api::user();
        if (! $user) {
            return $this->success(false);
        }

        return $this->success((bool) $user->certification);
    }

    /**
     * Notes   : 保存认证信息
     *
     * @Date   : 2021/7/20 10:24 上午
     * @Author : <Jason.C>
     * @param  CertificationRequest  $request
     * @return mixed
     */
    public function store(CertificationRequest $request)
    {
        $user = Api::user();
        if ($user->certification) {
            return $this->failed('用户已存在认证信息');
        }
        $keys   = [
            'name'       => $request->name,
            'idcard'     => $request->id_card,
            'front_card' => $request->front_card ?? '',
            'back_card'  => $request->back_card ?? '',
        ];
        $config = new UserCertificationConfig();
        $data   = $config->autoVerified($keys);
        if ($data['code'] == 1) {
            $verified = 1;
        } else {
            return $this->failed($data['message']);
        }
        $result = UserCertification::updateOrCreate([
            'user_id' => $user->id,
        ], [
            'name'       => $request->name,
            'id_card'    => $request->id_card,
            'front_card' => $request->front_card ?? '',
            'back_card'  => $request->back_card ?? '',
            'verified'   => $verified,
        ]);
        if ($result) {
            $user->info()->update([
                'nickname' => $request->name,
            ]);

            return $this->success('操作成功');
        } else {
            return $this->failed('操作失败');
        }
    }

}
