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

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
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.OrderListAdapter
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

    //當前fragment是第幾頁
    private var position = 0

    private lateinit var adapter: OrderListAdapter

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //獲取當前頁數
        position = arguments?.getInt(INDEX) ?: 0
        pageViewModel.apply {
            showLoading.observe(viewLifecycleOwner, Observer {
                if (it) {
                    showLoading("加載中...")
                } else {
                    cancelDialogForLoading()
                }
                refresh_layout.finishRefresh()
                refresh_layout.finishLoadMore()
            })
            // 綁定狀態，如果這個值發生變化，並且是當前頁，就去獲取訂單列表
//            refreshState.observe(viewLifecycleOwner, Observer {
//                if (position == it) {
//                    page = 1
//                    getOrderList()
//                }
//            })
            // 綁定監聽當前fragment的數據項
//            mFragmentData[position].observe(viewLifecycleOwner, Observer {
//                it?.let {
//                    layout_nodata.setState(it.size <= 0)
//                    adapter.setData(it)
//                }
//            })
            newOrderList.observe(viewLifecycleOwner, Observer {
                it?.let {
                    layout_nodata.setState(it.size <= 0)
                    adapter.setData(it)
                }
            })
            //切換預約單狀態監聽
            appointmentType.observe(viewLifecycleOwner, Observer {
                if (position <= 1) {
                    //判斷小於1是因為只有 前兩個狀態才有預約單
                    refresh()
                }
            })
        }
        // 初始化recyclerview
        initRecyclerView()
        //初始化下拉刷新
        initRefresh()
    }

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

    private fun initRecyclerView() {
        rv_other_order.layoutManager = LinearLayoutManager(activity)
        adapter = OrderListAdapter(requireActivity(), pageViewModel.timeOut * 60 * 1000)
        adapter.setOnItemClickListener { data ->
            // 點擊查詢食品詳情
            val intent = Intent(activity, OrderDetailsActivity::class.java)
            intent.putExtra("orderId", data.id.toString())
            intent.putExtra("orderType", data.orderType)
            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.curStatNumber < 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() {
        pageViewModel.showLoading.postValue(true)
        page = 1
        pageViewModel.phone = ""
        getOrderList()
    }

    private fun getOrderList() {
        pageViewModel.getNewOrderList(page, PageViewModel.fragmentStatus[position], PageViewModel.fragmentType[position])
    }

    companion object {
        private const val INDEX = "index"

        @JvmStatic
        fun newInstance(position: Int): PlaceholderFragment {
            return PlaceholderFragment().apply {
                arguments = Bundle().apply {
                    putInt(INDEX, position)
                }
            }
        }
    }

}