package com.gingersoft.gsa.other_order_mode.model.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gingersoft.gsa.cloud.print.bean.OrderDetails
import com.gingersoft.gsa.other_order_mode.data.HistoryOrderRepository
import com.gingersoft.gsa.other_order_mode.data.model.bean.HistoryOrderBean
import kotlinx.coroutines.launch

class HistoryOrderViewModel(private val historyOrderRepository: HistoryOrderRepository) : ViewModel() {

    var data = MutableLiveData<HistoryOrderBean>()
    /**
     * 根據訂單id獲取訂單詳細信息
     */
    fun getHistoryOrderList(pageIndex: String, orderNum: String = "", listener: (HistoryOrderBean) -> Unit) {
        launch({
            var phone = ""
            var orderNumber = ""
            if (orderNum.length <= 11) {
                phone = orderNum
            } else {
                orderNumber = orderNum
            }

            historyOrderRepository.getHistoryOrderList("26", "4", pageIndex, "10", orderNumber, phone).apply {
                this.getData()?.let {
                    if (it.size > 0) {
                        it.removeAt(it.size - 1)
                    }
                    if (pageIndex != "1") {
                        data.value!!.getData()!!.addAll(it)
                        data.value!!.setSuccess(true)
                    }
                }
                if (pageIndex == "1") {
                    data.value = this
                }
                listener.invoke(data.value!!)
            }
        }, {
            //出錯
            it.printStackTrace()
        })
    }

    /**
     * 根據訂單id獲取訂單詳細信息
     */
    fun getOrderInfo(orderId: String, listener: (OrderDetails) -> Unit) {
        launch({
            historyOrderRepository.getOrderInfo(orderId).apply {
                listener.invoke(this)
            }
        }, {
            //出錯
        })
    }

    private fun launch(block: suspend () -> Unit, error: suspend (Throwable) -> Unit) = viewModelScope.launch {
        try {
            block()
        } catch (e: Throwable) {
            error(e)
        }
    }
}