<?php

namespace app\common\arw\adjfut\src\Unit;

use think\helper\Arr;
use think\helper\Str;

/**
 * @method static string b2kb(string $number,?int $scale)
 * @method static string b2mb(string $number,?int $scale) 
 * @method static string b2gb(string $number,?int $scale) 
 * @method static string b2tb(string $number,?int $scale) 
 * 
 * @method static string kb2b(string $number,?int $scale) 
 * @method static string kb2mb(string $number,?int $scale) 
 * @method static string kb2gb(string $number,?int $scale) 
 * @method static string kb2tb(string $number,?int $scale) 
 * 
 * @method static string mb2b(string $number,?int $scale) 
 * @method static string mb2kb(string $number,?int $scale) 
 * @method static string mb2gb(string $number,?int $scale) 
 * @method static string mb2tb(string $number,?int $scale) 
 * 
 * @method static string gb2b(string $number,?int $scale) 
 * @method static string gb2mb(string $number,?int $scale) 
 * @method static string gb2kb(string $number,?int $scale) 
 * @method static string gb2tb(string $number,?int $scale) 
 * 
 * @method static string tb2b(string $number,?int $scale) 
 * @method static string tb2mb(string $number,?int $scale) 
 * @method static string tb2kb(string $number,?int $scale) 
 * @method static string tb2gb(string $number,?int $scale) 
 */
class File
{
    /**
     * 间隔
     */
    const INTERVAL = 1024;
    /**
     * 顺序
     */
    const ORDER = ['b', 'kb', 'mb', 'gb', 'tb'];
    /**
     * 获取字典单位
     *
     * @param string $size
     * @return string
     * @date 2022-07-23
     * @example
     * @author arw
     * @since 1.0.0
     */
    public static function getByteUnit(string $size): string
    {
        for ($i = 0; $size >= self::INTERVAL && $i < 4; $i++) {
            $size = bcdiv($size, self::INTERVAL);
        }
        return round($size, 2) . self::ORDER[$i];
    }

    public static function __callStatic($name, $arguments)
    {
        $number = Arr::get($arguments, 0, 0);
        $scale  = Arr::get($arguments, 1, 0);
        $name = Str::lower($name);
        $a = null;
        $b = null;
        if (Str::contains($name, 2)) {
            list($a, $b) = explode('2', $name);
        } else {
            list($a, $b) = explode('to', $name);
        }
        $a_index = array_search($a, self::ORDER);
        $b_index = array_search($b, self::ORDER);
        $type = $a_index < $b_index;
        for ($i = 0; $i < abs(bcsub($a_index, $b_index, 0)); $i++) {
            if ($type) {
                $number = bcdiv($number, self::INTERVAL, $scale);
            } else {
                $number = bcmul($number, self::INTERVAL, $scale);
            }
        }
        return $number;
    }
}
