package com.adealink.weparty.module.order.data

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.weparty.module.order.OrderModule


val discountLD = ExtMutableLiveData<OrderDiscountInfo?>()

fun observeDiscount(owner: LifecycleOwner, observer: Observer<OrderDiscountInfo?>) {
    discountLD.observeWithoutCache(owner, observer)
}

fun unObserveDiscount(owner: LifecycleOwner) {
    discountLD.removeObservers(owner)
}

fun unObserveDiscount(observer: Observer<OrderDiscountInfo?>) {
    discountLD.removeObserver(observer)
}

data class FinalPrice(
    val originPrice: Float, //原始价格
    val discountPrice: Float, //折扣价格
    val discount: Float, //折扣
    val discountPercent: Float, //折扣比例(0-100)
) {
    fun hasDiscount(): Boolean {
        return discount > 0
    }
}

fun getFinalPrice(originPrice: Float?): FinalPrice {
    if (originPrice == null || originPrice <= 0) {
        return FinalPrice(
            0f, 0f, 0f, 0f
        )
    }
    val discountInfo = OrderModule.getDiscountInfo()
    if (discountInfo == null || !discountInfo.hasDiscount || discountInfo.targetPrice != originPrice) {
        return FinalPrice(
            originPrice, originPrice, 0f, 0f
        )
    }
    val discountPrice = originPrice * discountInfo.discountRate
    val discount = originPrice - discountPrice
    return FinalPrice(
        originPrice,
        discountPrice,
        discount,
        (1 - discountInfo.discountRate) * 100
    )
}

data class OrderDiscountInfo(
    val hasDiscount: Boolean,
    val discountRate: Float, //当前首单折扣率（例如0.1表示1折）
    val targetPrice: Float, //可参与优惠的SKU单价（金币）
)