package com.gingersoft.gsa.other_order_mode.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
import com.gingersoft.gsa.other_order_mode.R
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.other_order_mode.ui.activity.OrderDetailsActivity
import com.gingersoft.gsa.other_order_mode.ui.adapter.OtherOrdersAdapter
import com.gingersoft.gsa.other_order_mode.ui.base.BaseFragment
import com.gingersoft.gsa.other_order_mode.util.InjectorUtil
import com.gingersoft.gsa.other_order_mode.util.OtherOrderUtils
import com.gingersoft.gsa.other_order_mode.util.setState
import kotlinx.android.synthetic.main.fragment_other_order.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.String as String1

/**
 * A placeholder fragment containing a simple view.
 */
class PlaceholderFragment : BaseFragment(R.layout.fragment_other_order) {

    private lateinit var pageViewModel: PageViewModel
    private var page = 1

    private val restaurantId by lazy { GsaCloudApplication.getRestaurantId(activity) }
    private val memberId by lazy { GsaCloudApplication.getMemberId(activity) }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        pageViewModel = ViewModelProvider(activity?.viewModelStore!!, InjectorUtil.getWeatherModelFactory())[PageViewModel::class.java].apply {
            // 綁定狀態，如果這個值發生變化
            refreshState.observe(viewLifecycleOwner, Observer {
                if (arguments?.getInt(INDEX) == it) {
                    page = 1
                    getOrderList(this, false)
                }
            })
        }

        // 初始化recyclerview
        rv_other_order.layoutManager = LinearLayoutManager(activity)
        val adapter = OtherOrdersAdapter(activity!!)

        adapter.setOnItemClickListenter { data ->
            // 點擊查詢食品詳情
            val intent = Intent(activity, OrderDetailsActivity::class.java)
            intent.putExtra("orderId", data.Id.toString())
            intent.putExtra("orderType", data.order_type)
            intent.putExtra("orderStatus", data.STATUS)
            intent.putExtra("orderPayType", data.orderPayType)
            intent.putExtra("isRead", data.isRead)
            startActivity(intent)


//            showLoading()
//            pageViewModel.getShipanyAndOrderInfo(data.curStat, GsaCloudApplication.getRestaurantId(context).toString(), data.Id.toString()) { it1 ->
//                cancelDialogForLoading()
//                //顯示彈窗
//                if (this@PlaceholderFragment.context != null && it1 != null) {
//                    OtherOrderUtils.showOrderDetailsDialog(this@PlaceholderFragment.context!!, it1, data.STATUS, data.order_type) { view, _, dialog ->
//                        when (view.id) {
//                            R.id.btn_assign_shipping -> {
//                                //修改訂單狀態
//                                pageViewModel.updateOrderStatus(this@PlaceholderFragment.context!!, data, it1) {
//                                    dialog.dismiss()
//                                    if (it) {
//                                        // 關閉彈窗，並刷新當前頁面
//                                        refresh()
//                                    }
//                                }
//                            }
//                            R.id.btn_cancel_order -> {
//                                //取消訂單，先判斷有沒有物流
//                                if (it1.data!![0].isDelete == 0) {
//                                    //第三方物流單
//                                    //彈出彈窗詢問是否確認取消
//                                    AppDialog.showWaringDialog(context, "是否確認取消第三方派送？") { v, dialog ->
//                                        when (v.id) {
//                                            R.id.tv_dialog_confirm -> {
//                                                //取消物流
//                                                showLoading()
//                                                pageViewModel.cancelLogistics(GsaCloudApplication.getRestaurantId(context).toString(), data.Id.toString()) {
//                                                    ToastUtils.show(context, it)
//                                                    cancelDialogForLoading()
//                                                    refresh()//刷新當前頁面
//                                                }
//                                                dialog.dismiss()
//                                            }
//                                            R.id.tv_dialog_cancel -> dialog.dismiss()
//                                        }
//                                    }
//                                } else {
//                                    //本店配送的單
//                                    pageViewModel.cancelOrder(context!!, data.Id.toString()) {
//                                        ToastUtils.show(context, if (it) {
//                                            "取消訂單成功"
//                                        } else {
//                                            "取消訂單失敗"
//                                        })
//                                        cancelDialogForLoading()
//                                        refresh()//刷新當前頁面
//                                    }
//                                }
//                                dialog.dismiss()
//                            }
//                        }
//                    }
//                } else {
//                    ToastUtils.show(context, "獲取訂單詳情失敗")
//                }
//            }
        }
        rv_other_order.adapter = adapter

        //有多少個Fragment就添加多少個監聽
        while (pageViewModel.mOrderList.size <= arguments?.getInt(INDEX)!!) {
            pageViewModel.mOrderList.add(MutableLiveData())
        }
        // 綁定監聽當前fragment的數據項
        pageViewModel.mOrderList[arguments?.getInt(INDEX)!!].observe(viewLifecycleOwner, Observer {
            refresh_layout.finishRefresh()
            refresh_layout.finishLoadMore()
            it?.let {
                layout_nodata.setState(it.size <= 0)
                adapter.setData(it)
            }
        })

        // 设置 Header 顏色
        refresh_layout.setPrimaryColorsId(R.color.color_f0, R.color.color_66)
        // 下拉刷新，加載更多
        refresh_layout.setOnRefreshListener {
            refresh()
            //重新拉取一遍送貨員信息
            pageViewModel.getDeliveryInfo(restaurantId.toString(), memberId.toString())
        }
        refresh_layout.setOnLoadMoreListener {
            page++
            getOrderList(pageViewModel, true)
        }
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    private fun refresh() {
        page = 1
        pageViewModel.orderNo = ""
        pageViewModel.phone = ""
        getOrderList(pageViewModel, false)
    }

    private fun getOrderList(pageViewModel: PageViewModel, isLoadMore: Boolean) {
        pageViewModel.getOrderList(GsaCloudApplication.getRestaurantId(activity).toString(), arguments?.getInt(INDEX) ?: 0, page.toString(), isLoadMore)
    }

    companion object {
        private const val INDEX = "index"
        @JvmStatic
        fun newInstance(position: Int): PlaceholderFragment {
            return PlaceholderFragment().apply {
                arguments = Bundle().apply {
                    putInt(INDEX, position)
                }
            }
        }
    }

}