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

import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.WindowManager
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.billy.cc.core.component.CC
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.base.widget.DialogUtils
import com.gingersoft.gsa.cloud.constans.PrintConstans
import com.gingersoft.gsa.cloud.print.bean.OrderDetails
import com.gingersoft.gsa.other_order_mode.R
import com.gingersoft.gsa.other_order_mode.data.WeatherRepository
import com.gingersoft.gsa.other_order_mode.data.model.bean.*
import com.gingersoft.gsa.other_order_mode.ui.adapter.DeliveryAdapter
import com.jess.arms.utils.ArmsUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PageViewModel(private val repository: WeatherRepository) : ViewModel() {

    companion object {
        var fragmentStatus = arrayOf("0,1,2,3", "0,1", "2", "3", "3")
        var fragmentType = arrayOf("0", "0", "0", "2", "7")
        val PrintCode = 1001//打印
        val SendCode = 1002//指派送貨
        val OrderDelivery = 1003//訂單配送
        val Closing = 1004//結賬
        val CancelOrder = 1005//取消訂單
        val CancelLogistics = 1006//取消物流
        val ProductionComplete = 1007//製作完成
    }

    var mOrderNum = arrayListOf<MutableLiveData<Int>>()

    var mOrderList = arrayListOf<MutableLiveData<ArrayList<OrderList.DataBeanX.DataBean>>>()

    //其他的所有數據
    var otherInfo = MutableLiveData<OrderList.DataBeanX.DataBean>()

    //刷新狀態，有數據更新就會更改這個變量，將這個變量修改為allOrderStatus...上面五種狀態，fragment中監聽這個變量，再調用接口獲取最新數據
    var refreshState = MutableLiveData<Int>()
    //訂單號
    var orderNo: String = ""
    //手機號
    var phone: String = ""
    //派送員信息
    var deliveryBean: DeliveryBean? = null

    /**
     * 獲取訂單數量
     * status
     * 0:未支付;
     * 1:待確認(已支付, 待餐廳確認);
     * 2:制作中（餐廳确認）;
     * 3:外賣是派送中，自取是待取餐
     * 4:确認收貨（完成）;
     * 5:是否評論;6:取消;
     * 已確認，外賣是指派送單，自取是製作完成
     */
    fun getOrderGroupNum(restaurantId: String) {
        launch({
            repository.getOrderGroup(restaurantId).apply {
                //先把所有置0
                for (i in mOrderNum) {
                    i.value = 0
                }
                //遍歷獲得外賣自取的 待確認和製作中的總單數
                for (i in data.selfTakeaway) {
                    when {
                        i.STATUS == 0 -> //未支付的待確認
                            mOrderNum[1].value = mOrderNum[1].value?.plus(i.SumNum)
                        i.STATUS == 1 -> //已支付的待確認
                            mOrderNum[1].value = mOrderNum[1].value?.plus(i.SumNum)
                        i.STATUS == 2 -> //製作中
                            mOrderNum[2].value = i.SumNum
                    }
                }
                //狀態為三時，下標為3(送貨中)的值為外賣的數量，下標為4(待取餐)的值為自取的數量
                for (i in data.takeaway) {
                    if (i.STATUS == 3) {
                        mOrderNum[3].value = i.SumNum
                    }
                }
                for (i in data.self) {
                    if (i.STATUS == 3) {
                        mOrderNum[4].value = i.selfSumNum
                    }
                }

                //下標為0時是全部，把集合所有值加起來
                var num = 0
                for (i in mOrderNum) {
                    //五個模塊
                    if (i.value != null) {
                        num += i.value!!
                    }
                }
                mOrderNum[0].value = num
            }
        }, {

        })
    }

    /**
     * 獲取訂單列表
     */
    fun getOrderList(restaurantId: String, position: Int, page: String, isLoadMore: Boolean) {
        launch({
            repository.requestOrderList(restaurantId, fragmentStatus[position], fragmentType[position], page, orderNo, phone).apply {
                getOrderGroupNum(restaurantId)
                loadInfo(isLoadMore, position)
            }
        }, {
            //出錯
            mOrderList[position].value = null
        })
    }

    private fun OrderList.loadInfo(isLoadMore: Boolean, position: Int) {
        if (getData() != null && getData()?.data != null) {
            val myData: ArrayList<OrderList.DataBeanX.DataBean> = getData()?.data as ArrayList<OrderList.DataBeanX.DataBean>
            if (myData.isNotEmpty()) {
                //取得最後一個對象，裡面有營業狀態和外賣訂單數，自取訂單數
                val dataBean: OrderList.DataBeanX.DataBean = myData[myData.size - 1]
                if (dataBean.Open_Status != null) {
                    restaurantState.value = dataBean.Open_Status!!.toInt()
                }
                if (position == 0) {//查詢全部訂單時才加載這些數據
                    otherInfo.value = myData[myData.size - 1]
                }
                //移除掉最後一個對象
                myData.removeAt(myData.size - 1)
                //如果是加載更多
                if (isLoadMore) {
                    if (mOrderList[position].value != null) {
                        mOrderList[position].value!!.addAll(myData)
                        mOrderList[position].postValue(mOrderList[position].value)
                    }
                } else {
                    mOrderList[position].value = myData
                }
            } else {
                mOrderList[position].value = null
            }
        } else {
            mOrderList[position].value = null
        }
    }

    //餐廳營業狀態，控制按鈕
    var restaurantState = MutableLiveData<Int>()

    /**
     * 修改餐廳營業狀態
     * 0=休息中, 1=營業中,2=繁忙中不可接單,3繁忙可接單
     */
    fun updateRestOpenStatus(state: Int, restaurantId: String) {
        launch({
            repository.updateRestOpenStatus(state, restaurantId).apply {
                if (success) {
                    restaurantState.value = state
                }
            }
        }, {

        })
    }

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


    /**
     * 根據餐廳ID和訂單ID獲取物流信息
     */
//    fun getShipanyOrderTime(restaurantId: String, orderId: String) {
//        launch({
//            repository.getShipanyOrderTime(restaurantId, orderId).apply {
//            }
//        }, {
//            //出錯
//            it.printStackTrace()
//        })
//    }


    var orderDetails = MutableLiveData<OrderDetails>()

    //待优化，将订单详情和物流送达时间分开，通过监听者通知更新物流时间
    fun getShipanyAndOrderInfo(restaurantId: String, orderId: String) {
        launch({
            withContext(Dispatchers.IO) {
                val orderDetail = withContext(Dispatchers.Default) { repository.getOrderInfo(orderId) }
                orderDetails.postValue(orderDetail)
                if (orderDetail.data != null && orderDetail.data!!.isNotEmpty()) {
                    //訂單詳情不為空
                    if (orderDetail.data!![0].isDelete == 0) {//為0是第三方物流單
                        if (orderDetail.data!![0].curStat != 0) {
                            val data = orderDetail.data!![0]
                            val type: Int
                            val estimatedTime: String
                            when (orderDetail.data!![0].curStat) {
                                1 -> {
                                    type = 2
                                    estimatedTime = "預計配送員接單時間："
                                }
                                2, 3 -> {
                                    type = 3
                                    estimatedTime = "預計配送員到店時間："
                                }
                                4, 5, 6 -> {
                                    type = 4
                                    estimatedTime = "配送員預計送達時間："
                                }
                                else -> {
                                    type = 1
                                    estimatedTime = "預計整張訂單完成時間："
                                }
                            }
                            val estimatedBean = withContext(Dispatchers.Default) { repository.getShipanyOrderTime(restaurantId, orderId, type) }//1、预计整张订单完成时间2、預計配送員接單時間3、預計配送員到店時間4、配送員預計送達時間
//                            if (estimatedBean.data.estimated_time > 0) {
                            data.estimatedTime = estimatedTime + ("${estimatedBean.data.estimated_time}分鐘後")
                            orderDetails.postValue(orderDetail)
//                            } else {
//                                data.estimatedTime = ""
//                            }
                        }
                    }
                }
            }
        }, {
            orderDetails.postValue(null)
        })
    }

    //設置為已讀
    fun updateIsRead(orderId: String) {
        launch({
            repository.updateIsRead(orderId)
        }, {

        })
    }


    fun updateOrderStatusByBtn(btnId: Int, dataBean: OrderDetails.DataBean, restaurantId: String, listener: (Int, Boolean) -> Unit) {
        launch({
            when (btnId) {
                BtnBuilder.sureBtn -> {
                    // 確認訂單
                    //      1、如果是外賣，指派到第三方物流
                    //      2、如果是自取，狀態改為製作中
                    repository.getDeliveryConfigDTO(restaurantId).apply {
                        var third = false
                        //獲取配送設置，查看當前單是否是第三方物流
                        for (i in 0 until data.list.size) {
                            if (data.list[i].distributionType == dataBean.deliveryMode) {
                                third = data.list[i].type == 1
                                break
                            }
                        }
                        if (third) {
                            // 如果是第三方物流,調用第三方接口
                            thirdSend(restaurantId, dataBean, 2, listener)
                        } else {
                            updateOrderAndPrint(restaurantId, dataBean, 2, listener)
                        }
                    }
                }
                BtnBuilder.printBtn -> {
                    //打印
                    printOrder(dataBean, listener)
                }
                BtnBuilder.ProductionCompletedBtn -> {
                    //製作完成
                    repository.gsUpdateOrderStatus(dataBean.ID.toString(), 3, dataBean.order_type, 1, "", "", "", "0", "", 1, 0).apply {
                        listener.invoke(ProductionComplete, code == "1")
                    }
                }
            }
        }, {
            listener.invoke(0, false)
        })
    }


    fun gsUpdateOrderStatus(orderDetails: OrderDetails.DataBean, payTypeId: Int = 0, listener: (Int, Boolean) -> Unit) {
        launch({
            repository.gsUpdateOrderStatus(orderDetails.ID.toString(), 4, orderDetails.order_type, 3, "", "", "", "0", "", 1, 0, payTypeId).apply {
                orderDetails.payType = payTypeId
                val bean = GsonUtils.GsonToBean(GsonUtils.GsonString(data), OrderClosingBean::class.java)
                orderDetails.oldPoints = bean.oldPoints
                orderDetails.nowPoints = bean.nowPoints
                orderDetails.addPoints = bean.addPoints
                printOrderClosing(orderDetails, listener)
            }
        }, {
            listener.invoke(OrderDelivery, false)
//            integralBean.postValue(null)
        })
    }

    /**
     * 待確認 --- 確認之後狀態變為 製作中，按鈕顯示：自取：製作完成，外賣：指派送貨----自取的狀態為待取餐，按鈕為結賬，外賣的狀態為派送中，按鈕顯示結賬
     * 更新訂單信息，自取或是外賣
     * status 0,1待確認
     * 2 已確認，外賣是指派送單，自取是製作完成
     */
    fun updateOrderStatus(context: Context, data: OrderList.DataBeanX.DataBean, orderDetails: OrderDetails, listener: (Boolean) -> Unit) {
//        launch({
//            val status = when (data.STATUS) {//如果以前的狀態是0，則修改為2。。。。
//                0 -> 2
//                1 -> 2
//                2 -> 3
//                3 -> 4
//                else -> 0
//            }
//            val isPush = when (status) {
//                2 -> 2
//                3 -> 1
//                4 -> 0
//                else -> 2
//            }
////            if (data.order_type == 2) {
//            // 是外賣
//            if (status == 3) {
//                //指派送貨，自取是製作完成
//                if (data.order_type == 2) {
//                    if (orderDetails.data!![0].isDelete != 0) {
//                        if (deliveryBean != null && deliveryBean!!.data.isNotEmpty()) {
//                            selectorDelivery(listener, context, data, status, isPush)
//                        } else {
//                            ToastUtils.show(context, "沒有送貨員信息")
//                        }
//                    } else {
//                        //第三方的單，執行重印功能
//                        printOrder(orderDetails, data, context, listener)
//                    }
//                } else {
//                    //自取
//                    repository.gsUpdateOrderStatus(data.Id.toString(), status, data.order_type, 1, "", "", "", "0", "", 1, 0).apply {
//                        listener.invoke(code == "1")
//                    }
//                }
//            } else if (status == 4) {
//                //結賬，彈窗確認是否結賬
//                if (orderDetails.data!![0].isDelete == 0) {
//                    //第三方物流單，沒有結賬，重印
//                    printOrder(orderDetails, data, context, listener)
//                } else {
//                    object : DialogUtils(context, R.layout.other_order_pause_orders) {
//                        override fun initLayout(hepler: ViewHepler, dialog: Dialog) {
//                            hepler.setText(R.id.tv_warning_title, "是否確認結賬？")
//                            hepler.getView<TextView>(R.id.tv_dialog_confirm).setOnClickListener {
//                                dialog.dismiss()
//                                launch({
//                                    //                                    updateOrderStatus(data.Id.toString(), "", status, "", "", isPush, data.order_type).apply {
////                                        listener.invoke(success)
////                                    }
//                                    repository.gsUpdateOrderStatus(data.Id.toString(), status, data.order_type, 3, "", "", "", "0", "", 1, 0).apply {
//                                        listener.invoke(code == "1")
//                                    }
//                                }, {
//
//                                })
//                            }
//                            hepler.getView<TextView>(R.id.tv_dialog_cancel).setOnClickListener {
//                                dialog.dismiss()
//                                listener.invoke(false)
//                            }
//                        }
//                    }.createDialogView().show()
//                }
//            } else {
//                showLoading(context)
//                // 確認訂單
//                var third = false
//                if (deliveryConfig != null) {
//                    for (i in 0 until deliveryConfig!!.data.list.size) {
//                        if (deliveryConfig!!.data.list[i].distributionType == data.deliveryMode) {
//                            third = deliveryConfig!!.data.list[i].type == 1
//                            break
//                        }
//                    }
//                }
//                if (third) {
//                    // 如果是第三方物流,調用第三方接口
//                    thirdSend(data, orderDetails, status, context, listener)
//                } else {
//                    updateOrderAndPrint(data, status, context, listener)
//                }
//            }
////            } else {
////                // 自取的確認訂單
////                repository.updateSelfOrderStatus(data.Id.toString(), status.toString(), GsaCloudApplication.getRestaurantId(context).toString()).apply {
////                    listener.invoke(success)
////                }
////            }
//        }, {
//
//        })
    }

    /**
     * 修改訂單狀態並打印
     */
    private suspend fun updateOrderAndPrint(restaurantId: String, dataBean: OrderDetails.DataBean, status: Int, listener: (Int, Boolean) -> Unit) {
        repository.gsUpdateOrderStatus(dataBean.ID.toString(), status, dataBean.order_type, 1, "", "", "", "0", "", 1, 0).apply {
            if (status == 0 || status == 1 || status == 2) {
                //確認送單
                //添加數據到prj
                val ids = StringBuffer()
                dataBean.PRODUCT_NAME.let {
                    if (it != null) {
                        for (i in it) {
                            if (i.child != null) {
                                for (j in i.child!!) {
                                    if (j.child != null) {
                                        for (x in j.child!!) {
                                            ids.append(x.odsId)
                                            ids.append(",")
                                        }
                                    }
                                    ids.append(j.odsId)
                                    ids.append(",")
                                }
                            }
                            ids.append(i.odsId)
                            ids.append(",")
                        }
                    }
                }
                repository.addPrj(dataBean.Order_ID.toString(), restaurantId, ids.toString())
                if (this.code == "1") {
                    listener.invoke(OrderDelivery, true)
                    // 打印印單
                    // 初始化用於打印的view
                    // 送單成功後，再調用接口獲取取餐碼
                    getOrderInfo(dataBean.ID.toString()) {
                        if (it != null) {
                            printOrder(dataBean, listener)
                        }
                    }
                } else {
                    listener.invoke(OrderDelivery, false)
                }
            }
        }
    }

    /**
     * 打印訂單
     */
    private fun printOrder(dataBean: OrderDetails.DataBean, listener: (Int, Boolean) -> Unit) {
        //訂單信息和廚房單
        MyOrderManage.setDataBean(dataBean)
        CC.obtainBuilder("Component.Print")
                .addParam(PrintConstans.PRINT_TYPE, 5)
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread { _, result ->
                    MyOrderManage.setDataBean(null)
                    listener.invoke(PrintCode, result.isSuccess)
                }
    }

    /**
     * 打印結賬單
     */
    private fun printOrderClosing(dataBean: OrderDetails.DataBean, listener: (Int, Boolean) -> Unit) {
        MyOrderManage.setDataBean(dataBean)
        CC.obtainBuilder("Component.Print")
                .addParam(PrintConstans.PRINT_TYPE, 7)
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread { _, result ->
                    MyOrderManage.setDataBean(null)
                    listener.invoke(PrintCode, result.isSuccess)
                }
    }

    /**
     * 打開錢箱
     */
    fun openCashBox() {
        CC.obtainBuilder("Component.Print")
                .addParam(PrintConstans.PRINT_TYPE, 6)
                .addParam(PrintConstans.PRINT_LOADING, false)
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread { _, result ->

                }
    }

    /**
     * 第三方派送
     */
    private suspend fun thirdSend(restaurantId: String, dataBean: OrderDetails.DataBean, status: Int, listener: (Int, Boolean) -> Unit) {
        val third = ThirdItem()
        //將食品數據轉為第三方需要的數據
        dataBean.PRODUCT_NAME?.let {
            for (i in it) {
                val price = ThirdItem.ThirdItemItem.UntPrice(`val` = i.PRICE!!.toDouble())
                val thirdItem = if (i.PRODUCT_NAME != null) {
                    ThirdItem.ThirdItemItem(name = i.PRODUCT_NAME!!, qty = 1, unt_price = price)
                } else {
                    ThirdItem.ThirdItemItem(name = "", qty = 1, unt_price = price)
                }
                third.add(thirdItem)
            }
        }
        //調用第三方物流接口
        repository.thirdDelivery(dataBean.ID.toString(), third).apply {
            if (success) {
                listener.invoke(OrderDelivery, true)
                updateOrderAndPrint(restaurantId, dataBean, status, listener)
            } else {
                listener.invoke(OrderDelivery, false)
            }
        }
    }

    /**
     * 選擇派送員
     */
    fun selectorDelivery(context: Context, dataBean: OrderDetails.DataBean, status: Int, listener: (Int, Boolean) -> Unit) {
        launch({
            repository.getDeliveryInfo(GsaCloudApplication.getRestaurantId(context).toString(), GsaCloudApplication.getMemberId(context).toString()).apply {
                deliveryBean = this
                if (this.data.isEmpty()) {
                    ToastUtils.show(context, "沒有配置配送員信息")
                    return@apply
                }
                //顯示選擇派送員
                object : DialogUtils(context, R.layout.other_order_layout_assign_deliveryman) {
                    override fun initLayout(hepler: ViewHepler?, dialog: Dialog?) {
                        hepler!!.getView<TextView>(R.id.tv_delivery_cancel).setOnClickListener {
                            dialog!!.dismiss()
                        }
                        val confirmBtn: TextView = hepler.getView(R.id.tv_delivery_confirm)
                        var selectIndex = -1

                        val recycler = hepler.getView<RecyclerView>(R.id.rv_delivery)
                        recycler.layoutManager = GridLayoutManager(context, 4)
                        val deliveryAdapter = DeliveryAdapter(deliveryBean!!.data)
                        recycler.adapter = deliveryAdapter

                        deliveryAdapter.setOnItemClickListener { adapter, view, position ->
                            selectIndex = position
                            deliveryAdapter.selectIndex = position
                            adapter.notifyDataSetChanged()

                            confirmBtn.background = context.resources.getDrawable(R.drawable.shape_green_btn)
                        }

                        confirmBtn.setOnClickListener {
                            if (selectIndex != -1) {
                                launch({
                                    repository.gsUpdateOrderStatus(dataBean.ID.toString(), status, dataBean.order_type, 1, "", deliveryBean!!.data[deliveryAdapter.selectIndex].userName, deliveryBean!!.data[deliveryAdapter.selectIndex].mobile, "0", "", 1, 0).apply {
                                        if (code == "1") {
                                            dialog?.dismiss()
                                            //回調
                                            listener.invoke(OrderDelivery, code == "1")//刷新頁面
                                            ToastUtils.show(context, "訂單開始派送")
                                        } else {
                                            ToastUtils.show(context, "訂單派送失敗")
                                        }
                                    }
                                }, {

                                })
                            } else {
                                ToastUtils.show(context, "請至少選擇一個送貨員")
                            }
                        }
                    }
                }.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                        .setHeight((ArmsUtils.getScreenHeidth(context) * 0.5).toInt())
                        .setGravity(Gravity.BOTTOM)
                        .show()
            }
        }, {

        })
    }

    /**
     * 選擇取消原因
     */
    fun selectorCancelReason(context: Context, cancelReason: CancelReason, title: String, listener: (Int) -> Unit) {
        object : DialogUtils(context, R.layout.other_order_layout_assign_deliveryman) {
            override fun initLayout(hepler: ViewHepler?, dialog: Dialog?) {
                hepler!!.getView<TextView>(R.id.tv_delivery_cancel).setOnClickListener {
                    dialog!!.dismiss()
                }
                hepler.getView<TextView>(R.id.tv_title).text = title

                val confirmBtn: TextView = hepler.getView(R.id.tv_delivery_confirm)
                var selectIndex = -1

                val recycler = hepler.getView<RecyclerView>(R.id.rv_delivery)
                if (cancelReason.data.isNotEmpty() && cancelReason.data.size < 3) {
                    recycler.layoutManager = GridLayoutManager(context, cancelReason.data.size)
                } else {
                    recycler.layoutManager = GridLayoutManager(context, 3)
                }

                val cancelReasons = ArrayList<DeliveryBean.Data>()
                for (bean in cancelReason.data) {
                    val data = DeliveryBean.Data(bean.id, "", bean.content)
                    cancelReasons.add(data)
                }

                val deliveryAdapter = DeliveryAdapter(cancelReasons)
                recycler.adapter = deliveryAdapter

                deliveryAdapter.setOnItemClickListener { adapter, view, position ->
                    selectIndex = position
                    deliveryAdapter.selectIndex = position
                    adapter.notifyDataSetChanged()

                    confirmBtn.background = context.resources.getDrawable(R.drawable.shape_green_btn)
                }

                confirmBtn.setOnClickListener {
                    if (selectIndex != -1) {
                        listener.invoke(selectIndex)
                    } else {
                        ToastUtils.show(context, "請選擇一個取消原因")
                    }
                }
            }
        }.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                .setHeight((ArmsUtils.getScreenHeidth(context) * 0.5).toInt())
                .setGravity(Gravity.BOTTOM)
                .show()
    }

    /**
     * 獲取配送員信息
     */
    fun getDeliveryInfo(restaurantId: String, memberId: String) {
        launch({
            repository.getDeliveryInfo(restaurantId, memberId).apply {
                deliveryBean = this
            }
        }, {

        })
    }

    /**
     * 獲取餐廳第三方物流信息
     */
    fun getDeliveryConfigDTO(restaurantId: String, listener: (DeliveryConfig?) -> Unit) {
        launch({
            repository.getDeliveryConfigDTO(restaurantId).apply {
                listener.invoke(this)
            }
        }, {

        })
    }

    /**
     * 取消物流
     */
    fun cancelLogistics(shopId: String, orderId: String, reasonId: String, reasonDesc: String, listener: (String) -> Unit) {
        launch({
            repository.cancelLogistics(shopId, orderId, reasonId, reasonDesc).apply {
                if (success) {
                    listener.invoke("已取消物流")
                } else {
                    listener.invoke(this.errMsg)
                }
            }
        }, {
            listener.invoke("取消物流失敗")
        })
    }

    /**
     * 取消訂單
     */
    fun cancelOrder(memberId: String, memberName:String, orderId: String, reasonId: String, reasonDesc: String, listener: (Boolean) -> Unit) {
        launch({
            repository.updateOrderStates(memberId, orderId, "6", memberName, reasonId, reasonDesc).apply {
                listener.invoke(code == "1")
            }
        }, {
            listener.invoke(false)
        })
    }

    /**
     * 獲取餐廳配置的取消原因
     */
    fun getCancelReason(restaurantId: String, type: String, listener: (CancelReason?) -> Unit) {
        launch({
            repository.getCancelReason(restaurantId, type).apply {
                listener.invoke(this)
            }
        }, {
            listener.invoke(null)
        })
    }

    var payTypeBean = MutableLiveData<PayTypeInfo.DataBean>()
    /**
     * 獲取支付方式
     */
    fun getPayMethod(orderId: String) {
        launch({
            repository.getPayMethod(orderId).apply {
                if (this.code == "1" && this.data != null) {
                    payTypeBean.postValue(this.data)
                } else {
                    payTypeBean.postValue(null)
                }
            }
        }, {
            payTypeBean.postValue(null)
        })
    }


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

}