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

use Carbon\Carbon;
use Modules\Project\Entities\Coupon;
use Modules\Project\Services\Counpon\Type\FixedRebate;
use Modules\Project\Services\Counpon\Type\PercentRebate;

class CouponService extends BaseService
{
    public function __construct(Coupon $coupon)
    {
        $this->model = $coupon;
    }

    protected static $types = [
        FixedRebate::class,
        PercentRebate::class,
    ];

    public static function getTypeOptions()
    {
        $options = [];
        foreach (self::$types as $type) {
            $options[$type] = $type::getName();
        }

        return $options;
    }

    public static function getConfig($type)
    {
        if (in_array($type, static::$types)) {
            return (new $type())->getConfig();
        }
    }

    /**
     * 优惠券列表
     *
     * @return mixed
     */
    public function getList()
    {
        return $this->model->list();
    }

    /**
     * 用户券列表
     *
     * @param $queryData
     *
     * @return mixed
     */
    public function listOfUser($queryData)
    {
        $user = \Auth()->user();

        $query = $user->coupons();

        if ($statusQuery = $queryData['status']) {
            $query->$statusQuery();
        }

        return $query->latest()->get();
    }

    /**
     * 领取优惠券
     *
     * @param $queryData
     */
    public function getCoupon($queryData)
    {
        $user = \Auth()->user();
        $coupon = $this->model->find($queryData['coupon_id']);
        if (!$coupon || $coupon->disabled == 1 || ($coupon->end && $coupon->end->lt(Carbon::now()))) {
            throw \Illuminate\Validation\ValidationException::withMessages([
                'coupon_id' => ['优惠券ID不可用'],
            ]);
        }

        if ($coupon->isCollected($user->id)) {
            throw \Illuminate\Validation\ValidationException::withMessages([
                'coupon_id' => ['已领取过该优惠券'],
            ]);
        }

        $create = ['user_id' => $user->id, 'used' => 0];
        if ($coupon->end) {
            $create['expired_at'] = $coupon->end;
        }
        if ($coupon->expire_after_days) {
            $create['expired_at'] = Carbon::now()->addDay($coupon->expire_after_days);
        }

        $insert = array_pad([], $coupon->limit, $create);
        $coupon->users()->createMany($insert);
    }
}
