<?php

namespace App\Http\Controllers\API\User;

use App\Models\UseUser;
use App\Models\UserWallet;
use App\Models\BlindBoxList;

class CreateUser
{
    public function useCreateAccount($address, $id)
    {
        # 前端连接钱包成功后，判断是否创建用户
        $user = UseUser::query()->where('user_address', $address)->first();
        $invitation_code = '';
        if (!$user) {
            #用户不存在
            # 生成邀请码的位数
            $count = 6;
            #循环判断是否存在
            for ($i = 1; $i <= 10; $i++) {
                $res = self::CreateSuccess($address, $count);
                if (!$res->status) {
                    $count += 1;
                } else {
                    $invitation_code = $res->invitation_code;
                    break;
                }
            }
        } else {
            # 已存在--获取邀请码
            $code = UseUser::query()->where('user_address', $address)->first(['invitation_code']);
            $invitation_code = $code->invitation_code;
        }
        # 创建成功--返回邀请码
        $obj = (object)[];
        # 邀请链接
        $obj->invitation_link = url("/raffle/$invitation_code/$id");
        # 已邀请列表
        $invite_list = UserWallet::query()->where('Invitees_address', $address)->where('Invitees_box_id', $id)->where('status', 1)->get(['user_address']);
        $obj->invite_list = $invite_list ?? [];
        #获取当前盲盒单个邀请增加的几率
        $rate = BlindBoxList::query()->where('id', $id)->first(['invite_up_rate']);
        $obj->rate = $rate->invite_up_rate;
        return $obj;

    }

    /**
     *生成随机字符串
     */
    private function getRandomStr($count)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        # 随机取值
        for ($i = 0, $lc = strlen($chars) - 1; $i < $lc; $i++) {
            $num = mt_rand(0, $lc);
            $code .= $chars[$num];
            if (strlen($code) >= $count) {
                break;
            }
        }
        return $code;
    }

    private function CreateSuccess($address, $count)
    {
        $status = false;
        for ($i = 1; $i <= 20; $i++) {
            # 生成邀请码
            $invitation_code = self::getRandomStr($count);
            # 判断表中是否存在相同邀请码
            $item = UseUser::query()->where('invitation_code', $invitation_code)->first();
            if ($item) {
                # 存在相同的邀请码
                continue;
            } else {
                # 不存在-创建账户
                UseUser::query()->create(['user_address' => $address, 'invitation_code' => $invitation_code]);
                $status = true;
                break;
            }
        }
        $obj = (object)[];
        $obj->invitation_code = $invitation_code;
        $obj->status = $status;
        return $obj;
    }
}
