package com.gingersoft.gsa.cloud.order.discount;

import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.order.bean.discount.CouponDiscountBean;

import lombok.Getter;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-09-19
 * 修订历史：2020-09-19
 * 描述: 優惠券折扣{@link CouponDiscountBean}
 */
@Getter
public class CouponDiscount extends MultyDiscount {

    private CouponDiscountBean couponDiscount;

    public CouponDiscount(String name, int status, MultyDiscount nextMultyDiscount, CouponDiscountBean couponDiscount) {
        super(name, status, nextMultyDiscount);
        this.couponDiscount = couponDiscount;
    }

    @Override
    public double calculate(double money) {
        if (couponDiscount != null) {
            //配置了消費滿減
            double totalAmount = money;
            if (couponDiscount.getSpend() != null && totalAmount > couponDiscount.getSpend()) {
                //未滿足消費滿條件
            } else {
                discountMoney = calculationCoupon(couponDiscount, money);
                money = MoneyUtil.sum(money, discountMoney);
            }
        }
        return super.calculate(money);
    }

    /**
     * 計算優惠券金額
     *
     * @param couponDiscount
     * @param sourceMoney
     * @return
     */
    public static double calculationCoupon(CouponDiscountBean couponDiscount, double sourceMoney) {
        double discountMoney = 0;
        if (couponDiscount.getCouponType() == 2) {
            //金額折扣
            discountMoney = couponDiscount.getAmount();
        } else {
            //百分比折扣
            discountMoney = MoneyUtil.divide(MoneyUtil.multiply(sourceMoney, couponDiscount.getDiscount()), 100).doubleValue();
        }
        if (sourceMoney < discountMoney) {
            //折扣金額不能超出總額
            discountMoney = sourceMoney;
        }
        return -MoneyUtil.get_ItemDecimals_money(Math.abs(discountMoney));
    }

    /**
     * 獲取優惠券折扣ID
     *
     * @return
     */
    public Long getCouponDiscountId() {
        if (couponDiscount != null) {
            return couponDiscount.getId();
        }
        return null;
    }

}
