<?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 FixedRebate extends Base
{
    protected $config = [
        'amount' => [
            'currency' => ['amount', '优惠金额'],
            'default' => [1],
            'rules' => ['required|min:0.01'],
            'symbol' => ['￥'],
        ],
        '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 = [])
    {
        $orderTotal = $order->getTotal();

        return $config['amount'] < $orderTotal ? $config['amount'] : $orderTotal;
    }
}
