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

import android.os.Handler;
import android.os.Looper;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.order.base.BuildConfig;
import com.jess.arms.utils.ArmsUtils;

import lombok.Getter;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-09-19
 * 修订历史：2020-09-19
 * 描述: 整單折扣{@link Discount}
 */
@Getter
public class NomalDiscount extends MultyDiscount {

    private Discount discount;

    public NomalDiscount(String name, int status, MultyDiscount nextMultyDiscount, Discount discount) {
        super(name, status, nextMultyDiscount);
        this.discount = discount;
    }

    @Override
    public double calculate(double money) {
        if (discount != null) {
            discountMoney = calculationDiscount(discount, money);
            money = MoneyUtil.sum(money, discountMoney);
        }
        return super.calculate(money);
    }

    /**
     * 計算整单折扣金額
     *
     * @param discount
     * @param sourceMoney
     * @return
     */
    public static double calculationDiscount(Discount discount, double sourceMoney) {
        double discountMoney;
        if (discount.getType() == Discount.DISCOUNT_TYPE_RATE) {
            //百分比折扣
            discountMoney = MoneyUtil.divide(MoneyUtil.multiply(sourceMoney, discount.getDiscountValue()), 100).doubleValue();
        } else {
            //金額折扣
            discountMoney = discount.getAmount();
        }
        if (Double.doubleToLongBits(discount.getDiscountCap()) != 0 && discount.getDiscountCap() < discountMoney) {
            //不能大於折扣上限
            discountMoney = discount.getDiscountCap();
            if (BuildConfig.DEBUG) {
                double finalDiscountMoney = discountMoney;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        ArmsUtils.makeText(GsaCloudApplication.getAppContext(), "此折扣上限為:" + finalDiscountMoney);
                    }
                });
            }
        }
        if (sourceMoney < discountMoney) {
            //折扣金額不能超出總額
            discountMoney = sourceMoney;
        }
        return -MoneyUtil.get_ItemDecimals_money(Math.abs(discountMoney));
    }
}
