<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/9
 * Time: 17:43
 */
namespace Modules\Project\Services\Counpon\Type;

use Modules\Project\Services\Counpon\UseCouponInterface;

class PercentRebate extends Base
{
    protected $config = [
        'percent' => [
            'slider' => ['percent', '优惠比例'],
            'options' => [['max' => 100, 'min' => 1, 'step' => 1,]],
            'default' => [10],
            'rules' => ['required|min:1|max:100'],
        ],
        'order_amount' => [
            'currency' => ['order_amount', '最低订单金额'],
            'default' => [0],
            'rules' => ['required'],
            'options' => [['groupSeparator'=>'']],
            'symbol' => ['￥'],
        ],
    ];

    public static function getName()
    {
        return '百分比优惠';
    }

    public function getConfig()
    {
        return $this->config;
    }

    public function validate(UseCouponInterface $order, $config = [])
    {
        if (bccomp($order->getTotal(), $config['order_amount'], 2) == -1) {
            throw new \Exception('订单金额小于最低金额');
        }

        return $this->getRebate($order, $config);
    }

    public function getRebate(UseCouponInterface $order, $config = [])
    {
        return bcdiv($order->getTotal() * $config['percent'], 100, 2);
    }
}
