<?php

namespace App\Managers;

use App\Exceptions\AlertException;
use App\Http\Controllers\Core\Auth;
use App\Http\Controllers\Order;
use App\Models\CouponModel;

class CouponManager
{

    /**
     * @var CouponModel
     */
    protected $coupon;


    public function __construct()
    {
        $this->coupon = new CouponModel();
    }


    /**
     * 使用券
     * @param $orderId
     * @param $couponId
     */
    public function use($orderId, $couponId)
    {
        $coupon = $this->coupon->find($couponId);

        $coupon->use($orderId, $couponId);
    }


    /**
     * 未支付返还优惠券
     * @param $couponId
     */
    public function cancelUse($couponId)
    {
        $coupon = $this->coupon->find($couponId);
        $coupon->order_id = 0;
        $coupon->used_at = 0;
        $coupon->save();
    }


    /**
     * 计算优惠券
     * @param  int  $goodsId
     * @param  int  $couponId
     * @return int
     * @throws AlertException
     */
    public function getSettlementAmount(int $goodsId, int $couponId)
    {
        $uid = Auth::auth();
        $coupon = $this->coupon->find($couponId);

        if (!$coupon->isOwner($uid)) {
            throw new AlertException("兑换码不正确哦");
        }

        if ($coupon->isUsed()) {
            throw new AlertException("卡券已使用");
        }

        if (!$coupon->isOpened()) {
            throw new AlertException("卡券未到使用时间");
        }

        if ($coupon->isOverdue()) {
            throw new AlertException("卡券过期啦");
        }

        if (!$coupon->isGoodsScope($goodsId)) {
            throw new AlertException("该商品/业务不可使用此优惠券");
        }

        if (!$coupon->isSatisfyPrice($goodsId)) {
            throw new AlertException("未满优惠券使用金额");
        }

        $goods = Order::GOODS[$goodsId];
        $total_amount = $goods['total_fee'];

        switch ($coupon->type) {
            case "无门槛券":
            case "72小时入场券":
            case "满减券":
                $coupon_amount = ($coupon->coupon_amount > $total_amount)
                    ? $total_amount
                    : $coupon->coupon_amount;
                break;
            case "折扣券":
                $coupon_amount = floor($goods['total_fee'] * (1 - $coupon->discount / 10) / 10) * 10;
                break;
            default:
                throw new AlertException("未定义的卡券");
        }

        $settlement_total_amount = (int)($total_amount - $coupon_amount);

        return $settlement_total_amount;
    }


    /**
     * 开通SuperVip送72小时入场券
     * @param $uid
     * @param  int  $number
     * @return bool
     */
    public function generateSuperVip72FreeCoupons($uid, $number = 1)
    {
        $batchId = "vip" . date("Ym");
        $attributes = [
            'uid' => $uid,
            'goods_scope' => 'pair',
            'type' => '72小时入场券',
            'name' => '72小时CP直升入场券',
            'describe' => 'SVIP专属，直升全场最高匹配成功率',
            'coupon_amount' => 990,
            'min_amount' => 990,
            'get_at' => time(),
            'open_at' => time(),
            'overdue_at' => now()->addWeek(1)->addHour(12)->getTimestamp(),
            'batch_id' => $batchId,
        ];
        return $this->generateCoupons($attributes, $number);
    }


    /**
     * 签到送超级会员满减折扣券
     * @param $uid
     * @param  int  $number
     * @return bool
     */
    public function generateSignSuperVipCoupons($uid, $number = 1)
    {
        $batchId = "sign" . date("Ym");
        $attributes = [
            'uid' => $uid,
            'goods_scope' => 'pair',
            'type' => '72小时入场券',
            'name' => '72小时CP直升入场券',
            'describe' => 'SVIP专属，直升全场最高匹配成功率',
            'coupon_amount' => 990,
            'min_amount' => 990,
            'get_at' => time(),
            'open_at' => time(),
            'overdue_at' => now()->addWeek(1)->addHour(12)->getTimestamp(),
            'batch_id' => $batchId,
        ];
        return $this->generateCoupons($attributes, $number);
    }


    /**
     * 签到送72小时抵扣券
     * @param $uid
     * @param  int  $number
     * @return bool
     */
    public function generateSign72DiscountCoupons($uid, $number = 1)
    {
        $batchId = "sign" . date("Ym");
        $attributes = [
            'uid' => $uid,
            'goods_scope' => 'pair',
            'type' => '折扣券',
            'name' => '72小时CP报名折扣券',
            'describe' => '非免费入场时，可享受相应折扣',
            'discount' => 6.8,
            'min_amount' => 990,
            'get_at' => time(),
            'open_at' => time(),
            'overdue_at' => now()->addMonth(1)->getTimestamp(),
            'batch_id' => $batchId,
        ];

        return $this->generateCoupons($attributes, $number);
    }


    /**
     * 生成券
     * @param  array  $attributes
     * @param  int  $number
     * @return bool
     */
    public function generateCoupons(array $attributes, int $number = 1)
    {
        $data = [];
        while ($number) {
            $attributes['created_at'] = time();
            $attributes['updated_at'] = time();
            $attributes['code'] = \getChars(8);
            array_push($data, $attributes);
            $number--;
        }
        return $this->coupon->insert($data);
    }
}
