package com.gingersoft.gsa.delivery_pick_mode.ui.activity

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.base.widget.DialogUtils
import com.gingersoft.gsa.cloud.constans.FunctionManagerConstants
import com.gingersoft.gsa.cloud.function.FunctionManager
import com.gingersoft.gsa.cloud.print.bean.OrderDetails
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
import com.gingersoft.gsa.cloud.ui.utils.BtnBuilder
import com.gingersoft.gsa.cloud.ui.view.AddKeyBoard
import com.gingersoft.gsa.delivery_pick_mode.R
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.MessageBean
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.ServiceChargeRecordBean
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.TransportationBean
import com.gingersoft.gsa.delivery_pick_mode.databinding.ActivityOrderDetailsBinding
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel.Companion.DeliveryPrint
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel.Companion.OrderDelivery
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel.Companion.PrintCode
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel.Companion.Transportation
import com.gingersoft.gsa.delivery_pick_mode.mvp.ui.activity.PrjQueryActivity
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.DeliveryAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.FoodListAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.OrderDetailsAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.ThirdExpensesAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.base.BaseActivity
import com.gingersoft.gsa.delivery_pick_mode.util.InjectorUtil
import com.gingersoft.gsa.delivery_pick_mode.util.getmColor
import com.gingersoft.gsa.delivery_pick_mode.util.showSelectDialog
import com.gingersoft.gsa.delivery_pick_mode.util.showWaringDialog
import com.jess.arms.mvp.IPresenter
import com.qmuiteam.qmui.widget.QMUITopBar
import kotlinx.android.synthetic.main.activity_order_details.*
import java.lang.StringBuilder
import java.util.*

class OrderDetailsActivity : BaseActivity<IPresenter>() {

    private lateinit var pageViewModel: PageViewModel

    private lateinit var binding: ActivityOrderDetailsBinding
    private lateinit var orderId: String
    private var orderType: Int = 0
    private var orderPayType: Int = 0
    private var isRead: Int = -1
    private var state: Int = -1
    private var isTimeOut: Boolean = false
    private var isBookingOrder: Boolean = false
    lateinit var skeletonScreen: ViewSkeletonScreen
    var restaurantId: Int = -1

    private var orderNo: String? = null
    lateinit var rvThirdExpenses: RecyclerView
    lateinit var thirdExpensesLayout: LinearLayout

    var tipsCost = 0
    lateinit var btnBuilder: BtnBuilder
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_details)
        val functionByResModule = FunctionManager.getDefault().getFunctionByResModule(this, FunctionManagerConstants.takeaway::class.java, FunctionManagerConstants.takeaway.orderDetails, "orderDetails/btn")
        btnBuilder = BtnBuilder.getInstance(functionByResModule)

        val rootView = findViewById<View>(R.id.scroll_order_info)
        thirdExpensesLayout = findViewById(R.id.layout_third_expenses)
        rvThirdExpenses = findViewById(R.id.rv_third_expenses)

        skeletonScreen = Skeleton.bind(rootView)
                .load(R.layout.activity_order_details_loading)
                .shimmer(true)
                .duration(1000)
                .angle(20)
                .color(R.color.white)
                .show()

        restaurantId = GsaCloudApplication.getRestaurantId()
        orderId = intent.getStringExtra("orderId")//訂單id
        orderType = intent.getIntExtra("orderType", 0)//訂單類型
        orderPayType = intent.getIntExtra("orderPayType", 0)//訂單支付方式
        isRead = intent.getIntExtra("isRead", -1)//是否已讀訂單
        state = intent.getIntExtra("orderStatus", -1)//訂單狀態
        isTimeOut = intent.getBooleanExtra("isTimeOut", false)//接單是否超時
        isBookingOrder = intent.getBooleanExtra("isBookingOrder", false)//是否是預約單

        pageViewModel = ViewModelProvider(this, InjectorUtil.getWeatherModelFactory())[PageViewModel::class.java].apply {
            if (isRead == 0) {
                //如果是未讀，調用設為已讀接口
                updateIsRead(orderId)
            }
            //獲取訂單詳情
            getOrderDetails(orderId, binding)
        }
        initTopBar(qm_order_details_bar)
    }

    private fun initTopBar(topbar: QMUITopBar) {
        topbar.setTitle(GsaCloudApplication.getRestaurantName())
        topbar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener { finish() }
        topbar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color))

    }

    private fun PageViewModel.getOrderDetails(orderId: String, binding: ActivityOrderDetailsBinding) {
        getShipanyAndOrderInfo(restaurantId, orderId)
        getAdditionalByOrderId(orderId)
        orderDetails.observe(this@OrderDetailsActivity, Observer { it ->
            skeletonScreen.hide()//隱藏骨架屏
            if (it?.data != null && it.data!!.isNotEmpty()) {
                //初始化頁面佈局
                val orderDetails = it.data!![0]
                orderNo = orderDetails.ORDER_NO.toString()
                qm_order_details_bar.addRightImageButton(R.drawable.ic_print, R.id.iv_prj_history).setOnClickListener {
                    PrjQueryActivity.startPrjQueryActivity(this@OrderDetailsActivity, orderNo)
                }
                orderDetails.order_type = orderType
                orderDetails.orderPayType = orderPayType
                binding.data = orderDetails
                binding.totalAmount = orderDetails.TOTAL_AMOUNT!!.toDouble()
                binding.isSelf = orderDetails.order_type == 7

                val btnList = ArrayList<BtnBuilder.BtnBean>()

                val orderStatusText: String
                val type = if (orderDetails.order_type == 7) "自取" else "外送"
                when (orderDetails.orderStatus) {
                    2 -> {//製作中
                        if (state == 0) {
                            //防止調用了第三方物流接口，沒調用到確認訂單接口
                            btnBuilder.getSureBtn()?.let {
                                btnList.add(it)
                            }
                            orderStatusText = "待確認"
                            tv_order_state.setTextColor(getmColor(R.color.order_state0_color))
                            if (orderDetails.isDelete == 0) {
                                btnBuilder.getLogisticsBtn()?.let {
                                    btnList.add(it)
                                }
                                //已超時，添加追加服務費的按鈕
                                if (isTimeOut && orderDetails.companyType == 2) {
                                    btnBuilder.getAdditionalServiceChargeBtn()?.let {
                                        btnList.add(it)
                                    }
                                }
                            }
                        } else {
                            btnBuilder.getPrintBtn()?.let {
                                btnList.add(it)
                            }
                            if (orderDetails.order_type == 7) {
                                //製作中的自取，應該製作完成、打印、取消訂單
                                btnBuilder.getProductionCompletedBtn()?.let {
                                    btnList.add(it)
                                }
                                tv_order_state.setTextColor(getmColor(R.color.order_state0_color))
                            } else {
                                //製作中的外賣，應該有打印、取消物流、取消訂單
                                if (orderDetails.isDelete == 0) {
                                    btnBuilder.getLogisticsBtn()?.let {
                                        btnList.add(it)
                                    }
                                    if (isTimeOut && orderDetails.companyType == 2) {
                                        //已超時，添加追加貼士的按鈕
                                        btnBuilder.getAdditionalServiceChargeBtn()?.let {
                                            btnList.add(it)
                                        }
                                    }
                                } else {
                                    if (orderDetails.companyType == 2) {
                                        btnBuilder.getTransportationBtn()?.let {
                                            btnList.add(it)
                                        }
                                    }
                                    btnBuilder.getAssignDeliveryBtn()?.let {
                                        btnList.add(it)
                                    }
                                }
                                tv_order_state.setTextColor(getmColor(R.color.order_state1_color))
                            }
                            orderStatusText = "製作中"
                        }
                        btnBuilder.getCancelBtn()?.let {
                            btnList.add(it)
                        }
                    }
                    3 -> {//外賣是送貨中，自取是待取餐
                        btnBuilder.getPrintBtn()?.let {
                            btnList.add(it)
                        }
                        if (orderDetails.order_type == 7) {
                            //自取待取餐，有打印和結賬
                            orderStatusText = "待取餐"
                            btnBuilder.getClosingBtn()?.let {
                                btnList.add(it)
                            }
                            tv_order_state.setTextColor(getmColor(R.color.order_state3_color))
                        } else {
                            // 外賣有打印
                            // 如果是第三方物流，不顯示結賬
                            // 如果是本店配送，有結賬按鈕
                            if (orderDetails.isDelete == 0) {
                                //如果是第三方物流，不顯示結賬按鈕
                            } else {
                                btnBuilder.getAssignDeliveryBtn()?.let {
                                    btnList.add(it)
                                }
                                btnBuilder.getClosingBtn()?.let {
                                    btnList.add(it)
                                }
                            }
                            orderStatusText = "派送中"
                            tv_order_state.setTextColor(getmColor(R.color.order_state2_color))
                        }
                    }
                    8 -> {//預約單
                        if (!isBookingOrder) {
                            btnBuilder.getSureBtn()?.let {
                                btnList.add(it)
                            }
                        }
                        btnBuilder.getCancelBtn()?.let {
                            btnList.add(it)
                        }
                        orderStatusText = "待確認"
                    }
                    else -> {//待確認訂單
                        btnBuilder.getSureBtn()?.let {
                            if (isBookingOrder) {
                                it.btnContent = "確認接單"
                            }
                            btnList.add(it)
                        }
                        btnBuilder.getCancelBtn()?.let {
                            btnList.add(it)
                        }
                        orderStatusText = "待確認"
                        tv_order_state.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity, R.color.order_state0_color))
                    }
                }
                if (orderDetails.orderPayType == 2 && orderDetails.payMultiple != null) {
                    val sb = StringBuilder()
                    for (value in orderDetails.payMultiple!!) {
                        sb.append(value.payName)
                        sb.append(",")
                    }
                    if (sb.isNotEmpty()) {
                        sb.deleteCharAt(sb.length - 1)
                    }
                    binding.patMethod = sb.toString()
                }

                binding.orderStatus = type + orderStatusText

                rv_food.layoutManager = LinearLayoutManager(this@OrderDetailsActivity)
                rv_food.adapter = FoodListAdapter(this@OrderDetailsActivity, orderDetails.PRODUCT_NAME!!)
                val orderBtnAdapter = OrderDetailsAdapter(btnList)

                rv_order_details_btn.apply {
                    adapter = orderBtnAdapter
                    var spanCount = 3
                    val gridLayoutManager =
                            if (btnList.size != 0 && btnList.size <= spanCount) {
                                spanCount = btnList.size
                                GridLayoutManager(this@OrderDetailsActivity, spanCount)
                            } else {
                                GridLayoutManager(this@OrderDetailsActivity, spanCount)
                            }

                    gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                        override fun getSpanSize(position: Int): Int {
                            //5個按鈕，第五個的position=4. 4
                            return if (position < spanCount) {
                                1
                            } else {
                                if (btnList.size > (((position + 1) / spanCount) + 1) * spanCount) {
                                    1
                                } else {
                                    val size = btnList.size % spanCount
                                    if (size > (spanCount / 2)) {
                                        1
                                    } else {
                                        spanCount / size
                                    }
                                }
                            }
                        }
                    }
                    layoutManager = gridLayoutManager
                }

// 亂糟糟的代碼，該優化了
//--------------------------------------------------------------不同按鈕點擊事件----------------------------------------------------------------------------------------
                orderBtnAdapter.setOnItemClickListener { _, _, position ->
                    when (btnList[position].type) {
                        BtnBuilder.LogisticsBtn ->
                            //取消第三方物流  彈出彈窗詢問是否確認取消
                            cancelLogistics(orderDetails)
                        BtnBuilder.AssignDeliveryBtn ->
                            //指派送貨
                            selectorDelivery(this@OrderDetailsActivity, orderDetails, 3) { _, _ -> finish() }
                        BtnBuilder.CancelBtn ->
                            //取消訂單
                            cancelOrder(orderDetails)
                        BtnBuilder.TransportationBtn -> {
                            //lalamove重新選擇運輸工具
                            showLoading()
                            getIsUpdateTransportation(restaurantId) {
                                cancelDialogForLoading()
                                if (it == null || it.isEmpty()) {
                                    ToastUtils.show(this@OrderDetailsActivity, "未獲取到交通工具")
                                } else {
                                    showSelectTransportation(it, orderDetails, false)
                                }
                            }
                        }
                        BtnBuilder.ClosingBtn -> {
                            //如果是在線支付的訂單，就直接修改訂單狀態
                            if (orderPayType != 1) {
                                gsUpdateOrderStatus(orderDetails, null) { _, isSuccess ->
                                    if (isSuccess) {
                                        finish()
                                    } else {
                                        ToastUtils.show(this@OrderDetailsActivity, "結賬失敗")
                                    }
                                }
                            } else {
                                val intent = Intent(this@OrderDetailsActivity, PayActivity::class.java)
                                intent.putExtra("orderDetails", orderDetails)
                                startActivityForResult(intent, 1001)
                            }
                        }
                        BtnBuilder.SureBtn -> {
                            if (isBookingOrder) {
                                //是預約單，其他都不做改變，只修改狀態為8
                                updateOrderAndPrint(restaurantId, orderDetails, 8, false, listener)
                            } else {
                                //確認訂單，判斷是本店還是zeek或是lalamove
                                if (orderDetails.order_type == 7) {
                                    //如果是自取單，將物流類型改為本店
                                    orderDetails.companyType = 0
                                }

                                when (orderDetails.companyType) {
                                    0, 1 -> {
                                        //本店配送和zeek
                                        confirmOrder(orderDetails)
                                    }
                                    2 -> {
                                        //lalamove
                                        selectLalaMove(orderDetails, true) { it, orderDetails ->
                                            showIsUpdateTransportation(it, orderDetails, true)
                                        }
                                    }
                                    else -> ToastUtils.show(this@OrderDetailsActivity, "未知的物流類型")
                                }
                            }
                        }
                        BtnBuilder.PrintBtn -> {
                            //打印
                            printOrder(PrintCode, orderDetails) {}
                        }
                        BtnBuilder.ProductionCompletedBtn -> {
                            //製作完成
                            updateOrderAndPrint(restaurantId, orderDetails, 3) {
                                if (it.success) {
                                    finish()
                                }
                                ToastUtils.show(this@OrderDetailsActivity, if (it.success) {
                                    "製作完成"
                                } else if (!TextUtil.isEmptyOrNullOrUndefined(it.errorMsg)) {
                                    it.errorMsg
                                } else {
                                    "修改訂單狀態失敗"
                                })
                            }
                        }
                        BtnBuilder.AdditionalServiceChargeBtn -> {
                            //追加貼士
                            showAddServiceChangeDialog()
                        }
                        else -> {
                            showLoading()
                            confirmOrder(orderDetails)
                        }
                    }
                }
            } else {
                ToastUtils.show(this@OrderDetailsActivity, "獲取訂單詳情失敗")
                finish()
            }
        })

        //添加服務費
        addServiceChargeBean.observe(this@OrderDetailsActivity, Observer {
            cancelDialogForLoading()
            if (it != null) {
                finish()
                if (TextUtil.isNotEmptyOrNullOrUndefined(it.errMsg)) {
                    ToastUtils.show(this@OrderDetailsActivity, it.errMsg)
                }
            }
        })
//        getAdditionalByOrderId(orderId) {
//            if (it != null && it.data.isNotEmpty()) {
//                thirdExpensesLayout.visibility = View.VISIBLE
//                it.data.add(0, ServiceChargeRecordBean.DataX(0, 0, 0, 0, 0, 0, 0.0, 0, 0, 0, 0, 0, "", ""))
//                rvThirdExpenses.adapter = ThirdExpensesAdapter(it.data)
//                rvThirdExpenses.layoutManager = LinearLayoutManager(this@OrderDetailsActivity)
//            }
//        }
        serviceChargeRecordBeans.observe(this@OrderDetailsActivity, Observer {
            if (it != null && it.data.isNotEmpty()) {
                for (value in it.data) {
                    tipsCost += value.paymentValue
                }
                thirdExpensesLayout.visibility = View.VISIBLE
                it.data.add(0, ServiceChargeRecordBean.DataX(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", ""))
                rvThirdExpenses.adapter = ThirdExpensesAdapter(it.data)
                rvThirdExpenses.layoutManager = LinearLayoutManager(this@OrderDetailsActivity)
            }
        })
    }

    private fun showAddServiceChangeDialog() {
        object : DialogUtils(this@OrderDetailsActivity, R.layout.layout_add_service_charge) {
            override fun initLayout(hepler: ViewHepler, dialog: Dialog) {
                hepler.setOnClickListenter(R.id.tv_cancel) { dialog.dismiss() }
                if (tipsCost != 0) {
                    hepler.setText(R.id.tv_add_service_charge_title, "追加貼士(已追加$tipsCost)")
                    hepler.getView<TextView>(R.id.ed_service_charge).hint = "不能超過(${100 - tipsCost})"
                }
                hepler.getView<AddKeyBoard>(R.id.keyboard_addservice_charge).setMaxValue(100 - tipsCost)
                hepler.getView<AddKeyBoard>(R.id.keyboard_addservice_charge).setOnKeyResultListener { isComplete, value ->
                    hepler.setText(R.id.ed_service_charge, value)
                    if (isComplete && value.isNotEmpty()) {
                        if (tipsCost == 0 && value.toDouble() < 10) {
                            ToastUtils.show(this@OrderDetailsActivity, "最低金額$10")
                        } else if (tipsCost + value.toInt() > 100) {
                            ToastUtils.show(this@OrderDetailsActivity, "金額不能超過$100元")
                        } else {
                            //添加服務費
                            dialog.dismiss()
                            additionalServiceCharge(value.toInt())
                        }
                    }
                }
            }
        }
                .setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                .setGravity(Gravity.BOTTOM)
                .show()
    }

    private fun additionalServiceCharge(amount: Int) {
        showLoading()
        pageViewModel.additionalServiceCharge(GsaCloudApplication.getMemberId().toString(), orderId, amount)
    }

    private fun PageViewModel.selectLalaMove(orderDetails: OrderDetails.DataBean, isPrint: Boolean, black: (it: List<TransportationBean.DataX.Transportation>, orderDetails: OrderDetails.DataBean) -> Unit) {
        showLoading()
        getIsUpdateTransportation(restaurantId) {
            cancelDialogForLoading()
            if (it == null) {
                ToastUtils.show(this@OrderDetailsActivity, "未獲取到交通工具")
            } else {
                for (value in it) {
                    if (value.status == 1) {
                        //默認交通工具，判斷價格是不是在這個金額範圍內，如果在，則不提示，如果不在，提示用戶修改交通工具
                        if (orderDetails.PAY_AMOUNT > value.amountUnder && orderDetails.PAY_AMOUNT < value.amountOn) {
                            //價格在範圍內
                            confirmOrder(orderDetails, value.type.toString(), isPrint)
                            return@getIsUpdateTransportation
                        } else {
                            //價格不在默認交通工具範圍內，回到activity中彈出彈窗，讓用戶選擇交通工具
                            //否則彈窗讓用戶手動選擇
                            black(it, orderDetails)
                        }
                    }
                }
            }
        }
    }

    private fun PageViewModel.showIsUpdateTransportation(it: List<TransportationBean.DataX.Transportation>, orderDetails: OrderDetails.DataBean, isPrint: Boolean) {
        showWaringDialog("金額範圍和對應的運輸工具不符，是否修改運輸工具", { dialog ->
            //要修改運輸工具，彈出彈窗讓用戶選擇
            showSelectTransportation(it, orderDetails, isPrint)
            dialog.dismiss()
        }, { dialog ->
            //不修改運輸工具，使用默認的
            for (value in it) {
                if (value.status == 1) {
                    confirmOrder(orderDetails, value.type.toString(), isPrint)
                    break
                }
            }
            dialog.dismiss()
        })
    }

    private fun PageViewModel.showSelectTransportation(transportationBeans: List<TransportationBean.DataX.Transportation>, orderDetails: OrderDetails.DataBean, isPrint: Boolean) {
        //獲取實際金額
        showLoading()
        getActualAmount(orderId, GsaCloudApplication.getMemberId(), restaurantId) { it ->
            cancelDialogForLoading()
            it?.let { transportAmountBean ->
                transportAmountBean.data.let { transportData ->
                    val data = ArrayList<String>()
                    for (value in transportData) {
                        if (value.deliveryAmount <= 0) {
                            data.add(value.typeName)
                        } else {
                            data.add(value.typeName + "($" + value.deliveryAmount + ")")
                        }
                    }
                    val adapter = DeliveryAdapter(data)
                    adapter.setOnItemClickListener {
                        if (data[it].contains("Van仔")) {
                            ToastUtils.show(this@OrderDetailsActivity, "Van仔不支持上門服務,需客戶自行落樓取餐")
                        }
                    }
                    showSelectDialog("選擇運輸工具", 2, adapter as RecyclerView.Adapter<RecyclerView.ViewHolder>, {
                        if (adapter.selectIndex == -1) {
                            ToastUtils.show(this@OrderDetailsActivity, "請選擇交通工具")
                        } else {
                            confirmOrder(orderDetails, transportationBeans[adapter.selectIndex].type.toString(), isPrint)
                        }
                    }, { dialog ->
                        dialog.dismiss()
                    })
                }
            }
        }
    }

    var listener: (msg: MessageBean) -> Unit
        get() = { msg ->
            cancelDialogForLoading()
            val intent = Intent()
//            intent.putExtra("deliveryAmount", orderDetails.deliveryAmount)
            setResult(1001, intent)
            when (msg.code) {
                Transportation.toString() -> {//修改運輸工具
                    finish()
                    ToastUtils.show(this@OrderDetailsActivity, if (TextUtil.isNotEmptyOrNullOrUndefined(msg.errorMsg)) {
                        msg.errorMsg
                    } else {
                        "修改成功"
                    })

                }
                DeliveryPrint.toString() -> {//訂單已確認，是否打印成功
                    finish()
                    ToastUtils.show(this@OrderDetailsActivity, if (msg.success) {
                        "打印成功"
                    } else {
                        "打印失敗"
                    })
                }
                OrderDelivery.toString() -> {
                    //已確認訂單，重新刷新當前頁面
                    if (msg.success) {
                        ToastUtils.show(this@OrderDetailsActivity, "訂單已確認")
                    } else if (!TextUtil.isEmptyOrNullOrUndefined(msg.errorMsg)) {
                        ToastUtils.show(this@OrderDetailsActivity, msg.errorMsg)
                    } else {
                        ToastUtils.show(this@OrderDetailsActivity, "訂單確認失敗")
                    }
                    finish()
                }
                else -> {
                    cancelDialogForLoading()
                }
            }
        }
        set(value) = TODO()

    private fun PageViewModel.confirmOrder(orderDetails: OrderDetails.DataBean, trafficType: String = "", isPrint: Boolean = true) {
        showLoading()
        var status = 2
        confirmOrder(orderDetails, status, trafficType, restaurantId, if (isBookingOrder) false else isPrint, listener)
    }

    /**
     * 取消訂單，獲取取消原因
     */
    private fun PageViewModel.cancelOrder(orderDetails: OrderDetails.DataBean) {
        //獲取取消原因讓用戶選擇
        showLoading()
        getCancelReason(GsaCloudApplication.getBrandId(), restaurantId, 3) { cancelReson ->
            cancelDialogForLoading()
            if (cancelReson != null && cancelReson.data.isNotEmpty()) {
                //如果有配置取消原因
                //彈出彈窗讓用戶選擇取消原因
                selectorCancelReason(this@OrderDetailsActivity, cancelReson, "選擇取消原因") {
                    isSureCancelOrder(orderDetails, cancelReson.data[it].id.toString(), cancelReson.data[it].content)
                }
            } else {
                //後台沒有配置取消原因，彈出彈窗詢問是否取消
                isSureCancelOrder(orderDetails, "", "")
            }
        }
    }

    /**
     * 是否確認取消訂單
     */
    private fun PageViewModel.isSureCancelOrder(orderDetails: OrderDetails.DataBean, reasonId: String, reasonDesc: String) {
        showWaringDialog("是否確認取消訂單？", { dialog ->
            dialog.dismiss()
            showLoading()
            if (orderDetails.isDelete == 0) {
                //是第三方物流單，先取消物流，再取消訂單
                cancelLogistics(restaurantId, orderId, reasonId, reasonDesc) {
                    cancelOrder(GsaCloudApplication.getMemberId().toString(), GsaCloudApplication.getMemberName(), orderId, reasonId, reasonDesc) {
                        cancelDialogForLoading()
                        if (it) {
                            finish()
                            ToastUtils.show(this@OrderDetailsActivity, "訂單已取消")
                        } else {
                            ToastUtils.show(this@OrderDetailsActivity, "取消訂單失敗")
                        }
                    }
                }
            } else {
                //取消訂單
                cancelOrder(GsaCloudApplication.getMemberId().toString(), GsaCloudApplication.getMemberName(), orderId, reasonId, reasonDesc) {
                    cancelDialogForLoading()
                    if (it) {
                        finish()
                        ToastUtils.show(this@OrderDetailsActivity, "訂單已取消")
                    } else {
                        ToastUtils.show(this@OrderDetailsActivity, "取消訂單失敗")
                    }
                }
            }
        }, {
            it.dismiss()
        })
    }

    /**
     * 取消物流，獲取取消原因
     */
    private fun PageViewModel.cancelLogistics(orderDetails: OrderDetails.DataBean) {
        //獲取取消原因讓用戶選擇
        showLoading()
        getCancelReason(GsaCloudApplication.getBrandId(), restaurantId, 2) { cancelReson ->
            cancelDialogForLoading()
            if (cancelReson != null && cancelReson.data.isNotEmpty()) {
                //如果有配置取消原因
                //彈出彈窗讓用戶選擇取消原因
                selectorCancelReason(this@OrderDetailsActivity, cancelReson, "選擇取消原因") {
                    confirmCancelLogistics(orderDetails.ID.toString(), cancelReson.data[it].id.toString(), cancelReson.data[it].content)
                }
            } else {
                //後台沒有配置取消原因，彈出讓用戶選擇是否取消
                confirmCancelLogistics(orderDetails.ID.toString(), "", "")
            }
        }
    }

    /**
     * 是否確認取消物流
     */
    private fun PageViewModel.confirmCancelLogistics(orderId: String, reasonId: String, reasonDesc: String) {
        AppDialog().showWaringDialog(this@OrderDetailsActivity, "是否確認取消第三方派送？") { v, dialog ->
            when (v.id) {
                R.id.tv_dialog_confirm -> {
                    dialog.dismiss()
                    showLoading()
                    cancelLogistics(restaurantId, orderId, reasonId, reasonDesc) {
                        cancelDialogForLoading()
                        ToastUtils.show(this@OrderDetailsActivity, it)
                        finish()
                    }
                }
                R.id.tv_dialog_cancel -> dialog.dismiss()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001) {
            //結賬頁面
            if (resultCode == RESULT_OK) {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        DialogUtils.staticDismiss()
    }
}
