<?php

namespace app\service\order;

use app\exception\ServiceException;
use app\service\Math;
use think\facade\Config as CConfig;

class Compute
{
    /**
     * 分销配置
     *
     * @return array
     */
    public static function configSales(): array
    {
        CConfig::load('extra/sales', 'sales');
        return config('sales') ?? [];
    }

    /**
     * 查询积分抵扣金额
     *
     * @param  int  $score
     * @return float
     * @throws \app\exception\ServiceException
     */
    public static function score2price(int $score): float
    {
        list($rateScore, $ratePrice) = self::checkScoreDeduct();

        return (Math::mul($score, Math::div($ratePrice, $rateScore)));
    }

    /**
     * 查询金额需要多少积分
     *
     * @param  float  $price
     * @return int 积分必须为正整数,因此向上取整
     * @throws \app\exception\ServiceException
     */
    public static function price2score(float $price): int
    {
        list($rateScore, $ratePrice) = self::checkScoreDeduct();
        $score = (Math::mul($price, Math::div($rateScore, $ratePrice)));

        return ceil($score);
    }

    /**
     * 返回积分抵扣配置值
     *
     * @return int[]
     * @throws \app\exception\ServiceException
     */
    public static function checkScoreDeduct(): array
    {
        $config  = self::configSales();
        $rate    = $config['score_deduct_price'] ?? '10:1';//默认是积分:金额 10:1
        $rateArr = explode(':', $rate);
        if (count($rateArr) !== 2) {
            throw new ServiceException('积分兑换比例配置错误');
        }

        $rateScore = (int) $rateArr[0];
        $ratePrice = (int) $rateArr[1];
        if ($rateScore <= 0 || $ratePrice <= 0) {
            throw new ServiceException('积分兑换比例配置值必须大于零');
        }

        if (!is_int($rateScore) || $rateScore <= 0) {
            throw new ServiceException('积分兑换比例配置中积分必须是正整数');
        }

        return [$rateScore, $ratePrice];
    }
}