package com.gingersoft.gsa.delivery_pick_mode.model.viewModel

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.billy.cc.core.component.CC
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.component.ComponentName
import com.gingersoft.gsa.cloud.common.constans.PrintConstans
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails
import com.gingersoft.gsa.cloud.order.order.TakeawayOrder
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter
import com.gingersoft.gsa.delivery_pick_mode.data.HistoryOrderRepository
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.HistoryOrderBean
import kotlinx.coroutines.launch

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


    var historyData = MutableLiveData<HistoryOrderBean>()
    var historyTime = MutableLiveData<String>(TimeUtils.getOldDate(0)) //按時間查詢
    var status = MutableLiveData("4")  //按類型查詢
    var searchValue = MutableLiveData("")//按搜索內容查詢
    var orderType = 0

    fun getHistoryOrderList(pageIndex: String, orderNum: String = "", startDate: String, endDate: String, status: String) {
        launch({
            var phone = ""
            var orderNumber = ""
            if (orderNum.length <= 11) {
                phone = orderNum
            } else {
                orderNumber = orderNum
            }
            historyOrderRepository.getHistoryOrderList(RestaurantInfoManager.newInstance().getRestaurantId().toString(), status, startDate, endDate, pageIndex, "10", orderType, orderNumber, phone).apply {
                this.data?.let {
                    if (it.size > 0) {
                        it.removeAt(it.size - 1)//移除最後一個，最後一個是顯示總條數的
                    }

                    if (pageIndex == "1") {
                        historyData.postValue(this)
                    } else {
                        historyData.value!!.data!!.addAll(it)
                        historyData.postValue(historyData.value)
                        historyData.value!!.success = true
                    }
                }
            }
        }, {
            //出錯
            it.printStackTrace()
            historyData.postValue(null)
        })
    }

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

    fun printOrder(context: Context, data: HistoryOrderBean.DataBean, listener: (Boolean) -> Unit) {
        launch({
            getOrderInfo(data.Id.toString()) {
                printOrder(it, data, context, listener)
            }
        }, {
            listener.invoke(false)
        })
    }

    /**
     * 打印訂單
     */
    private fun printOrder(orderDetails: OrderDetails, data: HistoryOrderBean.DataBean, context: Context, listener: (Boolean) -> Unit) {
        if (orderDetails.data != null) {
            //訂單信息和廚房單
            orderDetails.data!![0].order_type = data.order_type
            orderDetails.data!![0].orderPayType = data.orderPayType
            TakeawayOrder.getInstance().shoppingCart.deliveryAndPickupData = orderDetails.data!![0]

            var contentAdapter = PrintContentAdapter()
            var printContent = contentAdapter.adaptationPrintTakeawayFormContent(TakeawayOrder.getInstance().shoppingCart.deliveryAndPickupData)

            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_OTHER_ORDER)
                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                    .setActionName("printActivity")
                    .build()
                    .callAsyncCallbackOnMainThread { _, result ->
                        Log.e("error", "是否成功打印：" + result.isSuccess)
                        if (!result.isSuccess) {
                            ToastUtils.show(context, "打印失敗")
                            listener.invoke(false)
                        } else {
                            listener.invoke(true)
                        }
                        TakeawayOrder.getInstance().shoppingCart.deliveryAndPickupData = null
                    }
        } else {
            ToastUtils.show(context, "沒有訂單內容,打印失敗")
            listener.invoke(false)
        }
    }


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