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.constans.DeliveryPickConstans
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 historyStartTime = MutableLiveData<String>(TimeUtils.getOldDate(0)) //查詢開始時間
    var historyEndTime = MutableLiveData<String>(TimeUtils.getOldDate(0)) //查詢結束時間
    var status = MutableLiveData("4")  //按類型查詢
    var searchValue = MutableLiveData("")//按搜索內容查詢
    var orderType = DeliveryPickConstans.DELIVERY_TYPE //訂單類型 2 線上外賣訂單，7 自取訂單
    var orderFrom = 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
            }
            if (orderType.equals("1")) {
                orderFrom = 8;
            }
            historyOrderRepository.getHistoryOrderList(RestaurantInfoManager.newInstance().getRestaurantId().toString(), status, startDate, endDate, pageIndex, "10", orderType, orderFrom, orderNumber, phone).apply {
                if (this.data == null) {
                    historyData.postValue(this)
                } else {
                    this.data.let {
//                        if (it?.list != null && it?.list.size > 0) {
//                            it.list.removeAt(it.list.size - 1)//移除最後一個，最後一個是顯示總條數的
//                        }
                        if (pageIndex == "1") {
                            historyData.postValue(this)
                        } else {
                            historyData.value!!.data!!.list.addAll(it.list)
                            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)
            }
        }, {
            //出錯
            it.printStackTrace()
        })
    }

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

    /**
     * 打印訂單
     */
    private fun printOrder(orderDetails: OrderDetails, data: HistoryOrderBean.Data.OrderItem, context: Context, listener: (Boolean) -> Unit) {
        if (orderDetails.data != null) {
            //訂單信息和廚房單
            orderDetails.data!![0].order_type = data.orderType
            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)
                    .addParam(PrintConstans.PRINT_ORDER_NO, TakeawayOrder.getInstance().shoppingCart.deliveryAndPickupData.ORDER_NO)
                    .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)
        }
    }
}