package com.gingersoft.gsa.other_order_mode.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
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 com.ethanhua.skeleton.Skeleton
import com.ethanhua.skeleton.ViewSkeletonScreen
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.print.bean.OrderDetails
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
import com.gingersoft.gsa.other_order_mode.R
import com.gingersoft.gsa.other_order_mode.data.model.bean.BtnBuilder
import com.gingersoft.gsa.other_order_mode.databinding.ActivityOrderDetailsBinding
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel.Companion.Closing
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel.Companion.DeliveryPrint
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel.Companion.OrderDelivery
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel.Companion.PrintCode
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel.Companion.SendCode
import com.gingersoft.gsa.other_order_mode.ui.adapter.FoodListAdapter
import com.gingersoft.gsa.other_order_mode.ui.adapter.OrderDetailsAdapter
import com.gingersoft.gsa.other_order_mode.ui.base.BaseActivity
import com.gingersoft.gsa.other_order_mode.util.InjectorUtil
import com.gingersoft.gsa.other_order_mode.util.showWaringDialog
import com.qmuiteam.qmui.widget.QMUITopBar
import kotlinx.android.synthetic.main.activity_order_details.*

class OrderDetailsActivity : BaseActivity() {

    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
    lateinit var skeletonScreen: ViewSkeletonScreen

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_details)

        val rootView = findViewById<View>(R.id.scroll_order_info)
        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
        orderType = intent.getIntExtra("orderType", 0)//訂單類型
        orderPayType = intent.getIntExtra("orderPayType", 0)//訂單支付方式
        isRead = intent.getIntExtra("isRead", -1)//是否已讀訂單

        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(this@OrderDetailsActivity))
        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) {
        orderDetails.observe(this@OrderDetailsActivity, Observer {
            skeletonScreen.hide()//隱藏骨架屏
            if (it?.data != null && it.data!!.isNotEmpty()) {
                val orderDetails = it.data!![0]
                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 -> {//製作中
                        btnList.add(BtnBuilder().getPrintBtn())
                        if (orderDetails.order_type == 7) {
                            //製作中的自取，應該製作完成、打印、取消訂單
                            btnList.add(BtnBuilder().getProductionCompletedBtn())
                            tv_order_state.setTextColor(resources.getColor(R.color.order_state0_color))
                        } else {
                            //製作中的外賣，應該有打印、取消物流、取消訂單
                            if (orderDetails.isDelete == 0) {
                                btnList.add(BtnBuilder().getLogisticsBtn())
                            } else {
                                btnList.add(BtnBuilder().getAssignDeliveryBtn())
                            }
                            tv_order_state.setTextColor(resources.getColor(R.color.order_state1_color))
                        }
                        orderStatusText = "製作中"
//                        if (orderDetails.isDelete != 0) {
                        //不是第三方物流才顯示取消訂單
                        btnList.add(BtnBuilder().getCancelBtn())
//                        }
                    }
                    3 -> {//外賣是送貨中，自取是待取餐
                        btnList.add(BtnBuilder().getPrintBtn())
                        if (orderDetails.order_type == 7) {
                            //自取待取餐，有打印和結賬
                            orderStatusText = "待取餐"
                            btnList.add(BtnBuilder().getClosingBtn())
                            tv_order_state.setTextColor(resources.getColor(R.color.order_state3_color))
                        } else {
                            // 外賣有打印
                            // 如果是第三方物流，不顯示結賬
                            // 如果是本店配送，有結賬按鈕
                            if (orderDetails.isDelete == 0) {
                                //如果是第三方物流，不顯示結賬按鈕
                            } else {
                                btnList.add(BtnBuilder().getAssignDeliveryBtn())
                                btnList.add(BtnBuilder().getClosingBtn())
                            }
                            orderStatusText = "派送中"
                            tv_order_state.setTextColor(resources.getColor(R.color.order_state2_color))
                        }
                    }
                    else -> {//待確認訂單
                        btnList.add(BtnBuilder().getSureBtn())
                        btnList.add(BtnBuilder().getCancelBtn())
                        orderStatusText = "待確認"
                        tv_order_state.setTextColor(resources.getColor(R.color.order_state0_color))
                    }
                }
                if (orderDetails.orderPayType == 2 && orderDetails.payName != null) {
                    binding.patMethod = orderDetails.payName
                }
                binding.orderStatus = type + orderStatusText

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

                if (btnList.size <= 3) {
                    rv_order_details_btn.layoutManager = GridLayoutManager(this@OrderDetailsActivity, btnList.size)
                } else {
                    rv_order_details_btn.layoutManager = GridLayoutManager(this@OrderDetailsActivity, 3)
                }
                val orderBtnAdapter = OrderDetailsAdapter(btnList)
                rv_order_details_btn.adapter = orderBtnAdapter

//--------------------------------------------------------------不同按鈕點擊事件----------------------------------------------------------------------------------------
                orderBtnAdapter.setOnItemClickListener { adapter, view, position ->
                    when (btnList[position].type) {
                        BtnBuilder.logisticsBtn ->
                            //取消第三方物流  彈出彈窗詢問是否確認取消
                            cancelLogistics(orderDetails)
                        BtnBuilder.assignDeliveryBtn ->
                            //指派送貨
                            selectorDelivery(this@OrderDetailsActivity, orderDetails, 3) { status, isSuccess -> finish() }
                        BtnBuilder.cancelBtn ->
                            //取消訂單
                            cancelOrder(orderDetails)
                        BtnBuilder.closingBtn -> {
                            //如果是在線支付的訂單，就直接修改訂單狀態
                            if (orderPayType != 1) {
                                gsUpdateOrderStatus(orderDetails, orderDetails.order_type, orderDetails.payName) { status, 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)
                            }
                        }
                        else -> {
                            showLoading()
                            updateOrderStatusByBtn(btnList[position].type, orderDetails, GsaCloudApplication.getRestaurantId(this@OrderDetailsActivity).toString()) { status, isSuccess ->
                                cancelDialogForLoading()
                                when (status) {
                                    DeliveryPrint -> {//訂單已確認，是否打印成功
                                        finish()
                                        ToastUtils.show(this@OrderDetailsActivity, if (isSuccess) {
                                            "打印成功"
                                        } else {
                                            "打印失敗"
                                        })
                                    }
                                    PrintCode -> {
                                        ToastUtils.show(this@OrderDetailsActivity, if (isSuccess) {
                                            "打印成功"
                                        } else {
                                            "打印失敗"
                                        })
                                    }
                                    SendCode -> {
                                        ToastUtils.show(this@OrderDetailsActivity, if (isSuccess) {
                                            "已成功指派"
                                        } else {
                                            "指派送貨失敗"
                                        })
                                        if(isSuccess){
                                            finish()
                                        }
                                    }
                                    OrderDelivery -> {
                                        //已確認訂單，重新刷新當前頁面
                                        if (isSuccess) {
                                            finish()
                                            ToastUtils.show(this@OrderDetailsActivity, "訂單已確認")
                                        } else {
                                            ToastUtils.show(this@OrderDetailsActivity, "訂單確認失敗")
                                        }
//                                        getOrderDetails(orderId, binding)
                                    }
                                    Closing -> {
                                        ToastUtils.show(this@OrderDetailsActivity, if (isSuccess) {
                                            "結賬成功"
                                        } else {
                                            "結賬失敗"
                                        })
                                    }
                                    PageViewModel.ProductionComplete -> {
                                        if (isSuccess) {
                                            finish()
                                        }
                                        ToastUtils.show(this@OrderDetailsActivity, if (isSuccess) {
                                            "製作完成"
                                        } else {
                                            "修改訂單狀態失敗"
                                        })
//                                        getOrderDetails(orderId, binding)
                                    }
                                    else -> {
                                        cancelDialogForLoading()
//                                        ToastUtils.show(this@OrderDetailsActivity, "修改訂單狀態失敗")
                                    }
                                }
                            }
                        }
                    }

                }
            } else {
                ToastUtils.show(this@OrderDetailsActivity, "獲取訂單詳情失敗")
                finish()
            }
        })
        getShipanyAndOrderInfo(GsaCloudApplication.getRestaurantId(this@OrderDetailsActivity).toString(), orderId)
    }

    /**
     * 取消訂單，獲取取消原因
     */
    private fun PageViewModel.cancelOrder(orderDetails: OrderDetails.DataBean) {
        //獲取取消原因讓用戶選擇
        showLoading()
        getCancelReason(GsaCloudApplication.getRestaurantId(this@OrderDetailsActivity).toString(), "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(GsaCloudApplication.getRestaurantId(this@OrderDetailsActivity).toString(), orderId, reasonId, reasonDesc) {
                    cancelOrder(GsaCloudApplication.getMemberId(this@OrderDetailsActivity).toString(), GsaCloudApplication.getMemberName(this@OrderDetailsActivity), orderId, reasonId, reasonDesc) {
                        cancelDialogForLoading()
                        if (it) {
                            finish()
                            ToastUtils.show(this@OrderDetailsActivity, "取消訂單成功")
                        } else {
                            ToastUtils.show(this@OrderDetailsActivity, "取消訂單失敗")
                        }
                    }
                }
            } else {
                //取消訂單
                cancelOrder(GsaCloudApplication.getMemberId(this@OrderDetailsActivity).toString(), GsaCloudApplication.getMemberName(this@OrderDetailsActivity), 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.getRestaurantId(this@OrderDetailsActivity).toString(), "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(GsaCloudApplication.getRestaurantId(this@OrderDetailsActivity).toString(), 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()
            }
        }
    }
}
