<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service;

use think\facade\Db;


/**
 * ID/编码生成服务
 * @package app\service
 */
class IdService
{
     /**
     * 生成订单号
     * @return string
     */
    public static function generateOrderNo(): string
    {
        return date('YmdHis') . mt_rand(1000, 9999);
    }

     /**
     * 生成随机邀请码
     * @param int $length
     * @return string
     */

    public static function randomInviteCode(int $length): string
    {
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $max = strlen($chars) - 1;
        $out = '';
        for ($i = 0; $i < $length; $i++) {
            $out .= $chars[random_int(0, $max)];
        }
        return $out;
    }

     /**
     * 生成唯一邀请码
     * @param int $length
     * @return string
     */
    public static function generateUniqueInviteCode(int $length = 8): string
    {
        for ($i = 0; $i < 30; $i++) {
            $code = self::randomInviteCode($length);
            $exists = 0;
            try {
                $exists = (int)Db::name('sys_users')->where('invite_code', $code)->count();
            } catch (\Throwable $e) {
                $exists = 0;
            }
            if ($exists <= 0) {
                return $code;
            }
        }
        $bytes = (int)max(4, ceil($length / 2));
        return strtoupper(substr(bin2hex(random_bytes($bytes)), 0, $length));
    }
}