package com.adealink.weparty.order.viewmodel

import androidx.lifecycle.LiveData
import com.adealink.frame.base.CommonDataNullError
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.App
import com.adealink.weparty.module.order.data.QRCodeOrder
import com.adealink.weparty.module.order.data.QRCodeOrderDetail
import com.adealink.weparty.module.order.data.QRCodeOrderDetailReq
import com.adealink.weparty.module.order.data.QRCodeOrderPayReq
import com.adealink.weparty.order.datasource.remote.OrderHttpService
import kotlinx.coroutines.launch

class QRCodeOrderViewModel : BaseViewModel() {

    private val orderHttpService by lazy {
        App.instance.networkService.getHttpService(OrderHttpService::class.java)
    }

    fun loadQRCodeOrderDetail(qrCode: String): LiveData<Rlt<QRCodeOrderDetail>> {
        val liveData = OnceMutableLiveData<Rlt<QRCodeOrderDetail>>()
        viewModelScope.launch {
            val rlt = orderHttpService.qrCodeOrderDetail(QRCodeOrderDetailReq(qrCode))
            when (rlt) {
                is Rlt.Failed -> {
                    liveData.send(rlt)
                }

                is Rlt.Success -> {
                    val data = rlt.data.data
                    if (data == null) {
                        liveData.send(Rlt.Failed(CommonDataNullError()))
                    } else {
                        liveData.send(Rlt.Success(data))
                    }
                }
            }
        }
        return liveData
    }

    fun pay(
        qrCode: String,
        orderType: QRCodeOrder,
        count: Int?,
        remark: String?
    ): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val rlt = when (orderType) {
                QRCodeOrder.SPECIAL_QRCODE -> {
                    orderHttpService.qrCodeOrderPay(
                        QRCodeOrderPayReq(qrCode, remark, null)
                    )
                }

                QRCodeOrder.COMMON_QRCODE -> {
                    orderHttpService.qrCodeOrderPay(
                        QRCodeOrderPayReq(qrCode, remark, count)
                    )
                }
            }
            liveData.send(rlt)
        }
        return liveData
    }
}