<?php

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

use App\Api\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\User\Models\UserWechat;

class IndexController extends Controller
{

    /**
     * Notes   : 设置页面展示
     *
     * @Date   : 2021/8/27 14:42
     * @Author : Mr.wang
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        $user   = Api::user();
        $wechat = UserWechat::where('user_id', $user->id)->first();
        if ($wechat) {
            if ($wechat->mini) {
                $bool = true;
            } else {
                $bool = false;
            }
        } else {
            $bool = false;
        }

        return $this->success([
            'avatar'        => $user->info->avatar ?? '',
            'nickname'      => $user->info->nickname ?? '',
            'is_bind'       => $bool,
            'certification' => [
                'is_true' => (bool) $user->certification,
                'message' => $user->certification ? [
                    'name'   => $user->certification->name,
                    'idcard' => $user->certification->id_card,
                ] : [],
            ],
        ]);
    }

    /**
     * Notes   : 用户基础信息修改
     *
     * @Date   : 2021/5/27 14:02
     * @Author : Mr.wang
     * @param  Request  $request
     * @param  string  $key
     * @return JsonResponse
     */
    public function update(Request $request, string $key): JsonResponse
    {
        $user = Api::user();

        switch ($key) {
            case 'nickname':
                $validator = Validator::make($request->all(), [
                    'value' => 'required',
                ], [
                    'value.required' => '用户昵称必须填写',
                ]);
                break;
            case 'avatar':
                $validator = Validator::make($request->all(), [
                    'value' => ['required', 'regex:/[^\s]*\.(jpg|jpeg|gif|png)$/i'],
                ], [
                    'value.required' => '用户头像必须上传',
                    'value.regex'    => '头像地址格式不正确',
                ]);
                break;
            default:
                return $this->failed('路径不合法');
        }

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first(), 422);
        }

        $result = $user->info()->update([$key => $request->value]);
        if ($result) {
            return $this->success('操作成功');
        } else {
            return $this->failed('失败');
        }

    }

}
