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

import android.app.Dialog
import android.content.Context
import android.util.Log
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.toast.ToastUtils
import com.gingersoft.gsa.cloud.base.widget.DialogUtils
import com.gingersoft.gsa.cloud.print.bean.OrderDetails
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog
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.DeliveryBean
import com.gingersoft.gsa.other_order_mode.data.model.bean.OrderList
import com.gingersoft.gsa.other_order_mode.data.model.bean.ThirdItem
import com.gingersoft.gsa.other_order_mode.data.model.bean.UpdateOrderBean
import com.gingersoft.gsa.other_order_mode.ui.adapter.DeliveryAdapter
import com.jess.arms.utils.ArmsUtils
import kotlinx.coroutines.launch

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


    private fun showLoading(context: Context, message: String? = null) {
        if (message != null)
            LoadingDialog.showDialogForLoading(context, message, true)
        else
            LoadingDialog.showDialogForLoading(context)
    }

    fun cancelDialogForLoading() {
        LoadingDialog.cancelDialogForLoading()
    }


    companion object {
        var fragmentStatus = arrayOf("0,1,2,3", "0,1", "2", "3", "3")
        var fragmentType = arrayOf("0", "0", "0", "2", "7")
    }

    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

    /**
     * 獲取訂單
     */
    fun getOrderList(context: Context, position: Int, page: String, isLoadMore: Boolean, listener: (String) -> Unit) {
        launch({
            repository.requestOrderList(GsaCloudApplication.getRestaurantId(context).toString(), fragmentStatus[position], fragmentType[position], page, orderNo, phone).apply {
                loadInfo(listener, isLoadMore, position)
            }
        }, {
            //出錯

        })
    }

    private fun OrderList.loadInfo(listener: (String) -> Unit, isLoadMore: Boolean, position: Int) {
        listener.invoke("加載完成")
        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!! == "1"
                }
                if (myData.size == 1) {
                    otherInfo.value = myData[0]
                } else {
                    otherInfo.value = myData[myData.size - 1]
                }
                //移除掉最後一個對象
                myData.removeAt(myData.size - 1)
                //如果是加載更多
                Log.e("eee", "加載更多$isLoadMore")
                if (isLoadMore) {
                    if (mOrderList[position].value != null) {
                        mOrderList[position].value!!.addAll(myData)
                        mOrderList[position].postValue(mOrderList[position].value)
                    }
                } else {
                    mOrderList[position].value = myData
                }
            } else {

            }
        }
    }


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

    /**
     * 修改餐廳營業狀態
     */
    fun setRestaurantState(context: Context, state: Boolean) {
        launch({
            Log.e("eee", "點擊狀態$state")
            if (state) {
                updateRestOpenStatus(state, context)
            } else {
                //暫停接單，彈窗向用戶確認是否關閉
                object : DialogUtils(context, R.layout.other_order_pause_orders) {
                    override fun initLayout(hepler: ViewHepler, dialog: Dialog) {
                        hepler.getView<TextView>(R.id.tv_dialog_confirm).setOnClickListener {
                            it.isClickable = false
                            launch({
                                updateRestOpenStatus(state, context).let {
                                    dialog.dismiss()
                                }
                            }, {

                            })
                        }
                        hepler.getView<TextView>(R.id.tv_dialog_cancel).setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                }.createDialogView().show()
            }
        }, {

        })
    }

    /**
     * 修改餐廳營業狀態
     */
    suspend fun updateRestOpenStatus(state: Boolean, context: Context) {
        repository.updateRestOpenStatus(state, GsaCloudApplication.getRestaurantId(context).toString()).apply {
            if (isSuccess()) {
                restaurantState.value = state
            }
        }
    }

    /**
     * 根據訂單id獲取訂單詳細信息
     */
    fun getOrderInfo(orderId: String, listener: (OrderDetails?) -> Unit) {
        launch({
            repository.getOrderInfo(orderId).apply {
                listener.invoke(this)
            }
        }, {
            //出錯
            listener.invoke(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
                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 (deliveryBean != null && deliveryBean!!.data.isNotEmpty()) {
                        selectorDelivery(listener, context, data, status, isPush)
                    } else {
                        ToastUtils.show(context, "沒有送貨員信息")
                    }
                } else if (status == 4) {
                    //結賬，彈窗確認是否結賬
                    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)
                                    }
                                }, {

                                })
                            }
                            hepler.getView<TextView>(R.id.tv_dialog_cancel).setOnClickListener {
                                dialog.dismiss()
                                listener.invoke(false)
                            }
                        }
                    }.createDialogView().show()
                } else {
                    showLoading(context)
                    // 確認訂單
                    val third = true
                    if (third) {
                        // 如果是第三方物流,調用第三方接口
                        thirdSend(data, orderDetails, status, isPush, data.order_type, context, listener)
                    } else {
                        updateOrderAndPrint(data, status, isPush, orderDetails, context, listener)
                    }
                }
            } else {
                // 自取的確認訂單
                repository.updateSelfOrderStatus(data.Id.toString(), status.toString(), GsaCloudApplication.getRestaurantId(context).toString()).apply {
                    listener.invoke(success)
                }
            }
        }, {

        })
    }

    private suspend fun updateOrderAndPrint(data: OrderList.DataBeanX.DataBean, status: Int, isPush: Int, orderDetails: OrderDetails, context: Context, listener: (Boolean) -> Unit) {
        updateOrderStatus(data.Id.toString(), "", status, "", "", isPush, data.order_type).apply {
            if (status == 0 || status == 1 || status == 2) {
                //確認送單
                if (this.success) {
                    //打印
                    //初始化用於打印的view
                    if (orderDetails.data != null) {
                        //訂單信息和廚房單
                        orderDetails.data!![0].order_type = data.order_type
                        orderDetails.data!![0].orderPayType = data.orderPayType
                        MyOrderManage.setDataBean(orderDetails.data!![0])
                        CC.obtainBuilder("Component.Print")
                                .addParam("type", 5)
                                .setActionName("printActivity")
                                .build()
                                .callAsyncCallbackOnMainThread { _, result ->
                                    Log.e("error", "是否成功打印：" + result.isSuccess)
                                    MyOrderManage.setDataBean(null)
                                }
                    } else {
                        ToastUtils.show(context, "沒有訂單內容,打印失敗")
                    }
                    listener.invoke(true)
                } else {
                    ToastUtils.show(context, "送單失敗")
                }
            }
        }
    }

    /**
     * 第三方派送
     */
    private suspend fun thirdSend(data: OrderList.DataBeanX.DataBean, orderDetails: OrderDetails, status: Int, isPush: Int, orderType: Int, context: Context, listener: (Boolean) -> Unit) {
        val third = ThirdItem()
        orderDetails.data?.get(0)?.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(data.Id.toString(), third).apply {
            if (success) {
                cancelDialogForLoading()
                updateOrderAndPrint(data, status, isPush, orderDetails, context, listener)
            } else {
                ToastUtils.show(context, "訂單派送失敗")
            }
        }
    }

    suspend fun updateOrderStatus(orderId: String, selfOrderId: String?, status: Int, mobile: String?, sender: String?, isPush: Int, orderType: Int): UpdateOrderBean {
        return repository.updateOrderStatus(orderId, selfOrderId, status, mobile, sender, isPush, orderType)
    }

    /**
     * 選擇派送員
     */
    private fun selectorDelivery(listener: (Boolean) -> Unit, context: Context, data: OrderList.DataBeanX.DataBean, status: Int, isPush: Int) {
        //顯示選擇派送員
        listener.invoke(false)//關閉彈窗。但是不刷新頁面
        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(context, 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({
                            updateOrderStatus(data.Id.toString(), "", status, deliveryBean!!.data[deliveryAdapter.selectIndex].mobile, deliveryBean!!.data[deliveryAdapter.selectIndex].userName, isPush, data.order_type).apply {
                                if (this.success) {
                                    dialog?.dismiss()
                                    //回調
                                    listener.invoke(success)//刷新頁面
                                    ToastUtils.show(context, "訂單開始派送")
                                } else {
                                    ToastUtils.show(context, "訂單派送失敗")
                                }
                            }
                        }, {

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

    /**
     * 獲取配送員信息
     */
    fun getDeliveryInfo(context: Context) {
        launch({
            repository.getDeliveryInfo(GsaCloudApplication.getRestaurantId(context).toString(), GsaCloudApplication.getMemberId(context).toString()).apply {
                deliveryBean = this
            }
        }, {

        })
    }

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

}