package com.adealink.weparty.order

import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.adealink.frame.base.Rlt
import com.adealink.frame.network.data.PageReq
import com.adealink.frame.spi.RegisterService
import com.adealink.weparty.App
import com.adealink.weparty.module.order.IOrderService
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.adealink.weparty.module.order.data.OrderDiscountInfo
import com.adealink.weparty.module.order.data.QueryUnCompleteOrderReq
import com.adealink.weparty.module.order.viewmodel.IOrderViewModel
import com.adealink.weparty.order.datasource.remote.OrderHttpService
import com.adealink.weparty.order.manager.discountManager
import com.adealink.weparty.order.viewmodel.OrderViewModel
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory

@RegisterService(IOrderService::class)
class OrderServiceImpl : IOrderService {

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

    override fun onLogout() {
        discountManager.clear()
    }

    override fun getService(): IOrderService {
        return this
    }

    override fun getOrderViewModel(owner: ViewModelStoreOwner): IOrderViewModel? {
        return ViewModelProvider(owner, OrderViewModelFactory())[OrderViewModel::class.java]
    }

    override suspend fun queryUnCompleteOrder(uid: String): Rlt<List<OrderDetailInfo>> {
        val rlt =
            orderHttpService.queryUnCompleteOrder(QueryUnCompleteOrderReq(uid, PageReq(20, null)))
        return when (rlt) {
            is Rlt.Failed -> {
                rlt
            }

            is Rlt.Success -> {
                Rlt.Success(rlt.data.data?.list ?: emptyList())
            }
        }
    }

    override fun queryDiscountInfo() {
        discountManager.queryDiscountInfo()
    }

    override suspend fun suspendQueryDiscountInfo(): Rlt<Any> {
        return discountManager.suspendQueryDiscountInfo()
    }

    override fun getDiscountInfo(): OrderDiscountInfo? {
        return discountManager.getDiscountInfo()
    }

}