<?php

namespace Modules\User\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Jason\Api\Api;
use Modules\User\Http\Resources\UserInfoBaseResource;
use Modules\User\Http\Resources\UserInfoResource;
use Vinkla\Hashids\Facades\Hashids;
use Illuminate\Support\Facades\Config;

class IndexController extends Controller
{

    /**
     * Notes   : 用户主页信息
     *
     * @Date   : 2021/3/11 5:45 下午
     * @Author : <Jason.C>
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        $user = Api::user();

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

    /**
     * Notes   : 用户信息
     *
     * @Date   : 2021/6/16 2:14 下午
     * @Author : Mr.wang
     * @return JsonResponse
     */
    public function info(): JsonResponse
    {
        $user = Api::user();

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

    /**
     * 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('失败');
        }

    }

    /**
     * Notes   : 用户邀请码接口
     *
     * @Date   : 2021/5/27 14:15
     * @Author : Mr.wang
     * @return JsonResponse
     */
    public function invite(): JsonResponse
    {
        $user = Api::user();
        if ($user->identityFirst()->id > 1) {
            $invite = Hashids::connection('code')->encode($user->id);
        } else {
            $invite = '';
        }
        $url = Config::get('user.invite_code.url').'?invite='.$invite;

        $code = 'data:image/png;base64,'.base64_encode(QrCode::format('png')
                ->size(100)
                ->margin(3)
                ->generate($url));

        return $this->success([
            'code'      => $code,
            'invite'    => $invite,
            'children'  => $user->children()->count(),
            'user_info' => new UserInfoBaseResource($user),
        ]);
    }

    /**
     * Notes   : 绑定邀请码
     *
     * @Date   : 2021/7/20 10:30 上午
     * @Author : wang
     * @param  Request  $request
     * @return JsonResponse
     */
    public function bind(Request $request): JsonResponse
    {
        $invite = $request->invite ?? '';
        if (empty($invite)) {
            return $this->failed('邀请码不能为空');
        }
        $invite = Hashids::connection('code')->decode($invite);
        if (empty($invite)) {
            return $this->failed('邀请码不正确');
        }

        $user = Api::user();
        if ($user->parent) {
            return $this->failed('用户已有上级，不能重复绑定');
        }

        if ($user->updateParent($invite[0])) {
            return $this->success('绑定成功');
        } else {
            return $this->failed('绑定失败');
        }
    }

    /**
     * Notes: 获取小程序码
     *
     * @Author: 玄尘
     * @Date: 2022/9/28 13:13
     */
    public function getMiniCode(Request $request)
    {
        $user = Api::user();
        $size = $request->size ?? '300';
        $url  = $request->url ?? 'pages/mall/index/index';

        $name      = "share_user_mini_{$user->id}.png";
        $path      = "share/".$name;
        $file_path = storage_path("app/public/".$path);

        $data = [
            'username' => $user->username,
            'nickname' => $user->info->nickname ?? '',
            'avatar'   => $user->info->avatar ?? '',
        ];

        $invite = Hashids::connection('code')->encode($user->id);

        $parse = parse_url($url);

        $arr['invite'] = $invite;
        $str           = $parse['path'].'?'.http_build_query($arr);
        if (! file_exists($file_path)) {
            $app      = app('wechat.mini_program');
            $response = $app->app_code
                ->get($str, [
                    'width'      => $size,
                    'is_hyaline' => true,
                ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs(storage_path("app/public/share"), $name);
            }
        }

        $data = array_merge($data, [
            'qrcode' => Storage::url($path),
        ]);

        return $this->success($data);
    }

}
