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.common.constans.Takeaway
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails.Companion.verifiAmountTip
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager
import com.gingersoft.gsa.cloud.common.core.user.UserContext
import com.gingersoft.gsa.cloud.common.function.FunctionManager
import com.gingersoft.gsa.cloud.common.utils.ClipboardUtils
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
import com.gingersoft.gsa.cloud.ui.utils.BtnBuilder
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils
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.AmountError
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.getCustomColor
import com.gingersoft.gsa.delivery_pick_mode.util.showSelectDialog
import com.jess.arms.mvp.IPresenter
import com.lxj.xpopup.XPopup
import com.qmuiteam.qmui.widget.QMUITopBar
import kotlinx.android.synthetic.main.activity_order_details.*
import java.util.*

class OrderDetailsActivity : BaseActivity<IPresenter>() {

    private lateinit var pageViewModel: PageViewModel

    private lateinit var binding: ActivityOrderDetailsBinding
    val restaurantId by lazy { RestaurantInfoManager.newInstance().restaurantId }

    /**
     * 訂單id
     */
    private lateinit var orderId: String

    /**
     * 是否已讀
     * 0未讀
     * else 已讀
     */
    private var isRead: Int = -1

    /**
     * 是否超時
     */
    private var isTimeOut: Boolean = false

    /**
     * 是否是預約單
     */
    private var isBookingOrder: Boolean = false

    /**
     * 骨架屏加載
     */
    private lateinit var skeletonScreen: ViewSkeletonScreen

    private lateinit var rvThirdExpenses: RecyclerView
    private lateinit var thirdExpensesLayout: LinearLayout

    /**
     * 貼士：追加服務費
     */
    var tipsCost = 0

    private 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, Takeaway.ORDER_DETAILS_BTN_PERMISSION, Takeaway.TAKEAWAY_ORDER_DETAILS)
        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()

        orderId = intent.getStringExtra("orderId")!!//訂單id
        isRead = intent.getIntExtra("isRead", -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)
            }
            mEnforceBtn = FunctionManager.getDefault().getFunctionByResModule(mContext, Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION, Takeaway.TAKEAWAY_ORDER_DETAILS_ENFORCE)
            //獲取訂單詳情
            getOrderDetails(orderId, binding)
        }
        initTopBar(qm_order_details_bar)
    }

    private fun initTopBar(topbar: QMUITopBar) {
        topbar.setTitle(RestaurantInfoManager.newInstance().restaurantName)
        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]
                val orderNo = orderDetails.ORDER_NO.toString()
                //訂單編號點擊事件
                tv_order_details_order_no.setOnClickListener {
                    ClipboardUtils.copyText(orderNo)
                    showMessage("複製成功")
                }
                addTopBarMenuBtn(orderDetails)
                //總金額
                var totalAmount = orderDetails.TOTAL_AMOUNT!!.toDouble()
                //合計：總金額減去餐盒費，配送費
                val total = MoneyUtil.sub(MoneyUtil.sub(totalAmount, orderDetails.Lunchbox), orderDetails.DELIVERY_CHARGE)
                //總金額減去折扣
                orderDetails.couponList?.let {
                    for (coupon in it) {
                        val view = View.inflate(mContext, R.layout.item_discount, null)
                        view.findViewById<TextView>(R.id.tv_discount_text).text = coupon.couponName + "："
                        view.findViewById<TextView>(R.id.tv_discount_amount).text = "$" + coupon.discount_amount
                        layout_takeaway_discount.addView(view)
                        totalAmount = MoneyUtil.sub(totalAmount, coupon.discount_amount)
                    }
                }
                binding.total = total
                binding.totalAmount = totalAmount
                binding.data = orderDetails
                binding.isSelf = orderDetails.orderType == 7
                if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetails.memberPhone) && orderDetails.PHONE != orderDetails.memberPhone) {
                    binding.phone = orderDetails.memberPhone + '(' + orderDetails.PHONE + ')'
                } else if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetails.PHONE)) {
                    binding.phone = orderDetails.PHONE
                }

                val btnList = ArrayList<BtnBuilder.BtnBean>()
                val type = if (orderDetails.orderType == 7) "自取" else "外送"
                //獲得訂單狀態和有權限的按鈕
                val orderStatusText = when (orderDetails.orderStatus) {
                    OrderDetails.inProduction -> {
                        initMakingState(btnList, orderDetails)
                    }
                    OrderDetails.appointDelivery -> {
                        initDeliveryOrMealWaiting(btnList, orderDetails)
                    }
                    OrderDetails.bookingOrder -> {
                        initBookingOrderBtn(btnList)
                    }
                    else -> {
                        initWaitingConfirmedBtn(btnList)
                    }
                }
                binding.patMethod = getPayMethodString(orderDetails)
                binding.orderStatus = type + orderStatusText
                rv_food.adapter = FoodListAdapter(this@OrderDetailsActivity, orderDetails.PRODUCT_NAME!!)
                //按鈕
                val orderBtnAdapter = OrderDetailsAdapter(btnList)
                //初始化按鈕排列方式
                initBtnArrangement(orderBtnAdapter, btnList)

//--------------------------------------------------------------不同按鈕點擊事件----------------------------------------------------------------------------------------
                orderBtnAdapter.setOnItemClickListener { _, _, position ->
                    when (btnList[position].type) {
                        BtnBuilder.LogisticsBtn ->
                            //取消第三方物流  彈出彈窗詢問是否確認取消
                            cancelLogistics(orderDetails)
                        BtnBuilder.AssignDeliveryBtn ->
                            //指派送貨
                            assignDelivery(orderDetails)
                        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 -> {
                            //只要不是貨到付款
                            closingAccount(orderDetails)
                        }
                        BtnBuilder.SureBtn -> {
                            confirmOrder(orderDetails)
                        }
                        BtnBuilder.PrintBtn -> {
                            //打印
                            printOrder(PrintCode, orderDetails) {}
                        }
                        BtnBuilder.ProductionCompletedBtn -> {
                            //製作完成
                            ProductionCompleted(orderDetails)
                        }
                        BtnBuilder.AdditionalServiceChargeBtn -> {
                            //追加貼士
                            showAddServiceChangeDialog()
                        }
                        else -> {
                            showLoading()
                            confirmOrderDefaultParameters(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)
                }
            }
        })
        //服務費記錄改變時刷新
        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 PageViewModel.ProductionCompleted(orderDetails: OrderDetails.DataBean) {
        updateOrderAndPrint(restaurantId, orderDetails, OrderDetails.appointDelivery) {
            if (it.success) {
                finish()
            }
            ToastUtils.show(this@OrderDetailsActivity, if (it.success) {
                "製作完成"
            } else if (!TextUtil.isEmptyOrNullOrUndefined(it.errorMsg)) {
                it.errorMsg
            } else {
                "修改訂單狀態失敗"
            })
        }
    }

    private fun PageViewModel.closingAccount(orderDetails: OrderDetails.DataBean) {
        if (orderDetails.orderPayType != OrderDetails.payOnDelivery) {
            //如果是在線支付的訂單，就直接修改訂單狀態
            gsUpdateOrderStatus(orderDetails, null) { errorCode, isSuccess ->
                when {
                    isSuccess -> {
                        finish()
                    }
                    errorCode == PageViewModel.ErrorCode -> {
                        ToastUtils.show(this@OrderDetailsActivity, "出問題啦，請退出重試")
                    }
                    else -> {
                        ToastUtils.show(this@OrderDetailsActivity, "結賬失敗啦，請退出重試")
                    }
                }
            }
        } else {
            //跳轉到結賬頁面
            if (OrderDetails.verificationAmount(orderDetails)) {
                ToastUtils.show(this@OrderDetailsActivity, verifiAmountTip)
                return
            }
            val intent = Intent(this@OrderDetailsActivity, PayActivity::class.java)
            intent.putExtra("orderDetails", orderDetails)
            startActivityForResult(intent, 1001)
        }
    }

    private fun assignDelivery(orderDetails: OrderDetails.DataBean) {
        pageViewModel.selectorDelivery(this@OrderDetailsActivity, orderDetails, OrderDetails.appointDelivery) { _, _ -> finish() }
    }

    private fun confirmOrder(orderDetails: OrderDetails.DataBean) {
        if (isBookingOrder) {
            //是預約單，其他都不做改變，只修改狀態為8
            pageViewModel.updateOrderAndPrint(restaurantId, orderDetails, 8, false, listener)
        } else {
            //確認訂單，判斷是本店還是zeek或是lalamove
            if (orderDetails.orderType == OrderDetails.yourselfPickUp) {
                //如果是自取單，將物流類型改為本店
                orderDetails.companyType = OrderDetails.ourStoreDistribution
            }

            when (orderDetails.companyType) {
                OrderDetails.ourStoreDistribution, OrderDetails.zeekDistribution -> {
                    //本店配送和zeek
                    pageViewModel.confirmOrderDefaultParameters(orderDetails)
                }
                OrderDetails.lalamoveDistribution -> {
                    //lalamove
                    pageViewModel.selectLalaMove(orderDetails, true) { it, orderDetails ->
                        pageViewModel.showIsUpdateTransportation(it, orderDetails, true)
                    }
                }
                else -> ToastUtils.show(this@OrderDetailsActivity, "未知的物流類型")
            }
        }
    }

    private fun PageViewModel.confirmOrderDefaultParameters(orderDetails: OrderDetails.DataBean, trafficType: String = "", isPrint: Boolean = true) {
        showLoading()
        confirmOrder(orderDetails, 2, trafficType, restaurantId, if (isBookingOrder) false else isPrint, if (isBookingOrder) false else isPrint, listener)
    }
    /**
     * 添加頂部菜單按鈕
     */
    private fun addTopBarMenuBtn(orderDetails: OrderDetails.DataBean) {
        val enforceBtn = arrayListOf<String>()
        for (function in pageViewModel.mEnforceBtn) {
            enforceBtn.add(function.resName)
        }
        enforceBtn.add("打印查詢")
        val addRightImageButton = qm_order_details_bar.addRightImageButton(R.drawable.icon_topbar_overflow, R.id.topbar_right_change_button);
        addRightImageButton.setOnClickListener {
            XPopup.Builder(this)
                    .atView(addRightImageButton)
                    .hasShadowBg(false)
                    .asAttachList(enforceBtn.toTypedArray(), null) { position, text ->
                        run {
                            pageViewModel.apply {
                                if (position >= pageViewModel.mEnforceBtn.size) {
                                    PrjQueryActivity.startPrjQueryActivity(this@OrderDetailsActivity, orderDetails.ORDER_NO)
                                } else {
                                    when (mEnforceBtn[position].resUrl) {
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[0].keyRes -> {
                                            //強制確認訂單
                                            confirmOrder(orderDetails)
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[1].keyRes -> {
                                            //強制製作完成
                                            ProductionCompleted(orderDetails)
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[2].keyRes -> {
                                            //強制取消訂單
                                            cancelOrder(orderDetails)
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[3].keyRes -> {
                                            //強制打印訂單
                                            printOrder(PrintCode, orderDetails) {}
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[4].keyRes -> {
                                            //強制取消物流
                                            cancelLogistics(orderDetails)
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[5].keyRes -> {
                                            //強制指派送貨
                                            assignDelivery(orderDetails)
                                        }
                                        Takeaway.ORDER_DETAILS_BTN_ENFORCE_PERMISSION[6].keyRes -> {
                                            //強制結賬
                                            closingAccount(orderDetails)
                                        }
                                        else -> {
                                        }
                                    }
                                }
                            }
                        }
                    }.show()
        }
    }

    /**
     * 初始化按鈕排列
     */
    private fun initBtnArrangement(orderBtnAdapter: OrderDetailsAdapter, btnList: ArrayList<BtnBuilder.BtnBean>) {
        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)
                    }
            //recyclerview按鈕數量佈局
            gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    //5個按鈕，第五個的position=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
        }
    }

    /**
     * 獲取支付方式字符串
     */
    private fun getPayMethodString(orderDetails: OrderDetails.DataBean): String {
        val sb = StringBuilder()
        if (orderDetails.orderPayType == OrderDetails.onLinePay && orderDetails.payMultiple != null) {
            for (value in orderDetails.payMultiple!!) {
                sb.append(value.payName)
                sb.append(",")
            }
            if (sb.isNotEmpty()) {
                sb.deleteCharAt(sb.length - 1)
            }
        }
        return sb.toString()
    }

    /**
     * 待確認
     */
    private fun initWaitingConfirmedBtn(btnList: ArrayList<BtnBuilder.BtnBean>): String {
        btnBuilder.getSureBtn()?.let {
            if (isBookingOrder) {
                it.btnContent = "確認接單"
            }
            btnList.add(it)
        }
        btnBuilder.getCancelBtn()?.let {
            btnList.add(it)
        }
        tv_order_state.setTextColor(ContextCompat.getColor(this@OrderDetailsActivity, R.color.order_state0_color))
        return "待確認"
    }

    /**
     * 預約單
     */
    private fun initBookingOrderBtn(btnList: ArrayList<BtnBuilder.BtnBean>): String {
        if (!isBookingOrder) {
            btnBuilder.getSureBtn()?.let {
                btnList.add(it)
            }
        }
        btnBuilder.getCancelBtn()?.let {
            btnList.add(it)
        }
        return "待確認"
    }

    /**
     * 外賣是送貨中，自取是待取餐
     */
    private fun initDeliveryOrMealWaiting(btnList: ArrayList<BtnBuilder.BtnBean>, orderDetails: OrderDetails.DataBean): String {
        val orderStatusText: String
        btnBuilder.getPrintBtn()?.let {
            btnList.add(it)
        }
        if (orderDetails.orderType == OrderDetails.yourselfPickUp) {
            //自取待取餐，有打印和結賬
            orderStatusText = "待取餐"
            btnBuilder.getClosingBtn()?.let {
                btnList.add(it)
            }
            tv_order_state.setTextColor(getCustomColor(R.color.order_state3_color))
        } else {
            // 外賣有打印
            // 如果是第三方物流，不顯示結賬
            // 如果是本店配送，有結賬按鈕
            if (orderDetails.isDelete == OrderDetails.thirdPartyDistribution) {
                //如果是第三方物流，不顯示結賬按鈕
            } else {
                btnBuilder.getAssignDeliveryBtn()?.let {
                    btnList.add(it)
                }
                btnBuilder.getClosingBtn()?.let {
                    btnList.add(it)
                }
            }
            orderStatusText = "派送中"
            tv_order_state.setTextColor(getCustomColor(R.color.order_state2_color))
        }
        return orderStatusText
    }

    /**
     * 製作中
     */
    private fun initMakingState(btnList: ArrayList<BtnBuilder.BtnBean>, orderDetails: OrderDetails.DataBean): String {
//        btnBuilder.getSureBtn()?.let {
//            btnList.add(it)
//        }
//        tv_order_state.setTextColor(getCustomColor(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)
//                }
//            }
//        }
        btnBuilder.getPrintBtn()?.let {
            btnList.add(it)
        }
        if (orderDetails.orderType == OrderDetails.yourselfPickUp) {
            //製作中的自取，應該製作完成、打印、取消訂單
            btnBuilder.getProductionCompletedBtn()?.let {
                btnList.add(it)
            }
            tv_order_state.setTextColor(getCustomColor(R.color.order_state0_color))
        } else {
            //製作中的外賣，應該有打印、取消物流、取消訂單
            if (orderDetails.isDelete == OrderDetails.thirdPartyDistribution) {
                btnBuilder.getLogisticsBtn()?.let {
                    btnList.add(it)
                }
                if (isTimeOut && orderDetails.companyType == OrderDetails.lalamoveDistribution) {
                    //已超時，添加追加貼士的按鈕
                    btnBuilder.getAdditionalServiceChargeBtn()?.let {
                        btnList.add(it)
                    }
                }
            } else {
                if (orderDetails.companyType == OrderDetails.lalamoveDistribution) {
                    btnBuilder.getTransportationBtn()?.let {
                        btnList.add(it)
                    }
                }
                btnBuilder.getAssignDeliveryBtn()?.let {
                    btnList.add(it)
                }
            }
            tv_order_state.setTextColor(getCustomColor(R.color.order_state1_color))
        }
        btnBuilder.getCancelBtn()?.let {
            btnList.add(it)
        }
        return "製作中"
    }

    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(UserContext.newInstance().memberId.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) {
                            //價格在範圍內
                            confirmOrderDefaultParameters(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) {
        AppDialog.getInstance().showTipDialog(mContext,"金額範圍和對應的運輸工具不符，是否修改運輸工具", { ->
            //要修改運輸工具，彈出彈窗讓用戶選擇
            showSelectTransportation(it, orderDetails, isPrint)
        }, {  ->
            //不修改運輸工具，使用默認的
            for (value in it) {
                if (value.status == 1) {
                    confirmOrderDefaultParameters(orderDetails, value.type.toString(), isPrint)
                    break
                }
            }
        })
    }

    private fun PageViewModel.showSelectTransportation(transportationBeans: List<TransportationBean.DataX.Transportation>, orderDetails: OrderDetails.DataBean, isPrint: Boolean) {
        //獲取實際金額
        showLoading()
        getActualAmount(orderId, UserContext.newInstance().memberId, 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 {
                            confirmOrderDefaultParameters(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()
                }
                AmountError.toString() -> {
                    ToastUtils.show(this@OrderDetailsActivity, verifiAmountTip)
                }
                else -> {
                    if (TextUtil.isNotEmptyOrNullOrUndefined(msg.errorMsg)) {
                        ToastUtils.show(this@OrderDetailsActivity, msg.errorMsg)
                    }
                    cancelDialogForLoading()
                }
            }
        }
        set(value) {}

    /**
     * 確認訂單
     */
    private fun confirmOrder(orderDetails: OrderDetails.DataBean, trafficType: String = "", isPrint: Boolean = true) {
        showLoading()
        val status = 2
        pageViewModel.confirmOrder(orderDetails, status, trafficType, restaurantId, if (isBookingOrder) false else isPrint, if (isBookingOrder) false else isPrint, listener)
    }

    /**
     * 取消訂單，獲取取消原因
     */
    private fun PageViewModel.cancelOrder(orderDetails: OrderDetails.DataBean) {
        //獲取取消原因讓用戶選擇
        showLoading()
        getCancelReason(RestaurantInfoManager.newInstance().brandId, 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) {
        AppDialog.getInstance().showWaringDialog(mContext,"是否確認取消訂單？") { ->
            showLoading()
            if (orderDetails.isDelete == 0) {
                //是第三方物流單，先取消物流，再取消訂單
                cancelLogistics(restaurantId, orderId, reasonId, reasonDesc) {
                    cancelOrder(UserContext.newInstance().memberId.toString(), UserContext.newInstance().memberName, orderId, reasonId, reasonDesc) {
                        cancelDialogForLoading()
                        if (it) {
                            finish()
                            ToastUtils.show(this@OrderDetailsActivity, "訂單已取消")
                        } else {
                            ToastUtils.show(this@OrderDetailsActivity, "取消訂單失敗")
                        }
                    }
                }
            } else {
                //取消訂單
                cancelOrder(UserContext.newInstance().memberId.toString(), UserContext.newInstance().memberName, orderId, reasonId, reasonDesc) {
                    cancelDialogForLoading()
                    if (it) {
                        finish()
                        ToastUtils.show(this@OrderDetailsActivity, "訂單已取消")
                    } else {
                        ToastUtils.show(this@OrderDetailsActivity, "取消訂單失敗")
                    }
                }
            }
        }
    }

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

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

    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()
    }
}
