<?php

namespace Modules\Project\Entities;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Modules\Project\Services\Counpon\UseCouponInterface;

class UserCoupon extends Model
{
    protected $fillable = ['user_id', 'coupon_id', 'used', 'expired_at'];

    protected $with = ['coupon'];

    protected $casts = [
        'expired_at' => 'datetime',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function coupon()
    {
        return $this->belongsTo(Coupon::class);
    }

    /**
     * @param $query
     */
    public function scopeAvailable($query)
    {
        $query->where('used', 0)->where(function ($query) {
            $query->whereNull('expired_at')->orWhere('expired_at', '>=', date('Y-m-d H:i:s'));
        });
    }

    /**
     * @param $query
     */
    public function scopeExpired($query)
    {
        $query->where('used', 0)->where('expired_at', '<', date('Y-m-d H:i:s'));
    }

    /**
     * @param $query
     */
    public function scopeUsed($query)
    {
        $query->where('used', 1);
    }

    /**
     * 获取优惠券状态
     *
     * @return string
     */
    public function getStatusAttribute()
    {
        return $this->used ?
            'used' :
            (($this->expired_at && $this->expired_at->lt(Carbon::now())) ? 'expired' : 'available');
    }

    /**
     * 检查优惠券对此订单是否可用并返回金额，不可用时会抛出异常
     *
     * @param UseCouponInterface $order
     *
     * @throws \Exception
     *
     * @return float
     */
    public function canUse(UseCouponInterface $order)
    {
        $id = \Auth::id();
        if ($id != $this->user_id) {
            throw new \Exception('错误的优惠券');
        }

        if (!$this->exists()) {
            throw new \Exception('不是一个优惠券实例');
        }

        if ($this->status != 'available') {
            throw new \Exception('优惠券不可用状态!');
        }

        if ($this->coupon->start && $this->coupon->start->gt(Carbon::now())) {
            throw new \Exception('优惠券还未到可用日期');
        }

        return $this->coupon->canUse($order);
    }

    /**
     * 使用优惠券
     *
     * @param UseCouponInterface $order
     *
     * @throws \Exception
     *
     * @return float
     */
    public function use(UseCouponInterface $order)
    {
        $discount_amount = $this->canUse($order);

        $this->order_id = $order->getUID();
        $this->discount_amount = $discount_amount;
        $this->used = 1;
        $this->save();

        return $discount_amount;
    }
}
