package com.gingersoft.gsa.delivery_pick_mode.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
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.other.TextUtil
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.delivery_pick_mode.R
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.delivery_pick_mode.ui.activity.OrderDetailsActivity
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.OtherOrdersAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.base.BaseFragment
import com.gingersoft.gsa.delivery_pick_mode.util.InjectorUtil
import com.gingersoft.gsa.delivery_pick_mode.util.setState
import kotlinx.android.synthetic.main.fragment_other_order.*

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

    private val pageViewModel by lazy { ViewModelProvider(activity?.viewModelStore!!, InjectorUtil.getWeatherModelFactory())[PageViewModel::class.java] }
    private var page = 1

    private val restaurantId by lazy { GsaCloudApplication.getRestaurantId() }
    private val memberId by lazy { GsaCloudApplication.getMemberId() }
    private lateinit var adapter: OtherOrdersAdapter
    private var position = 0

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        position = arguments?.getInt(INDEX) ?: 0
        pageViewModel.apply {
            // 綁定狀態，如果這個值發生變化
            refreshState.observe(viewLifecycleOwner, Observer {
                Log.e("CSDN_LQR0", "頁面pageindex$it" + "當前頁面$position")
                if (position == it) {
                    page = 1
                    getOrderList(false)
                }
            })

            //有多少個Fragment就添加多少個監聽
            while (mOrderList.size <= position) {
                mOrderList.add(MutableLiveData())
            }

            // 綁定監聽當前fragment的數據項
            mOrderList[position].observe(viewLifecycleOwner, Observer {
                cancelDialogForLoading()
                refresh_layout.finishRefresh()
                refresh_layout.finishLoadMore()

                it?.let {
                    layout_nodata.setState(it.size <= 0)
                    adapter.setData(it)
                }
            })

            orderList.observe(viewLifecycleOwner, Observer {
                refresh_layout.finishRefresh()
                refresh_layout.finishLoadMore()
                it?.let {
                    if (!it.isSuccess()) {
                        if (TextUtil.isNotEmptyOrNullOrUndefined(it.errMsg)) {
                            //訂單未請求成功才調用
                            ToastUtils.show(activity, it.errMsg)
                        } else {
                            ToastUtils.show(activity, "獲取訂單列表失敗")
                        }
                    }
                }
            })

            appointmentType.observe(viewLifecycleOwner, Observer {
                if (position <= 1) {
                    //判斷小於1是因為只有 前兩個狀態才有預約單
                    refresh()
                }
            })
        }
        // 初始化recyclerview
        initRecyclerView()
        initRefresh()
    }

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

    private fun initRefresh() {
        // 设置 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(true)
        }
    }

    private fun initRecyclerView() {
        rv_other_order.layoutManager = LinearLayoutManager(activity)
        adapter = OtherOrdersAdapter(activity!!, pageViewModel.timeOut * 60 * 1000)
        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)
            //傳遞是否是預約單
            if (position <= 1) {
                if (pageViewModel.appointmentType.value == 1) {
                    //預約單
                    intent.putExtra("isBookingOrder", true)
                }
            }

            //已指派物流 並且 狀態為未接單  才判斷是否超時
            if (data.isDelete == 0 && data.curStat < 2) {
                if (pageViewModel.timeOut == 0) {
                    //為0時沒配置，不顯示追加服務費按鈕
                    intent.putExtra("isTimeOut", false)
                } else {
                    intent.putExtra("isTimeOut", data.timeSecond < pageViewModel.timeOut * 60 * 1000)
                }
            }
            startActivityForResult(intent, 1001)
        }
        rv_other_order.adapter = adapter
    }


    private fun refresh() {
        if (position == pageViewModel.refreshState.value) {
            showLoading("獲取數據中...")
            page = 1
            pageViewModel.orderNo = ""
            pageViewModel.phone = ""
            getOrderList(false)
        }
    }

    private fun getOrderList(isLoadMore: Boolean) {
        pageViewModel.getOrderList(restaurantId.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)
                }
            }
        }
    }

}