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

import android.content.Intent
import android.os.Bundle
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()
            })
            newOrderList.observe(viewLifecycleOwner, Observer {
                //由於會從Activity中刷新，但是fragment並不知道頁數，有可能會重置頁數，這裡就修改一下
                page = pageSize
                it?.let {
                    layout_nodata.setState(it.size <= 0)
                    adapter.setData(it)
                }
            })
        }
        // 初始化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(requireContext().applicationContext, pageViewModel.timeOut * 60 * 1000)
        adapter.setOnItemClickListener { data ->
            // 點擊查詢食品詳情
            val intent = Intent(activity, OrderDetailsActivity::class.java)
            intent.putExtra("orderId", data.id.toString())
            intent.putExtra("isRead", data.isRead)
            //傳遞是否是預約單
            if (position <= 1) {
                if (pageViewModel.appointmentType == 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)
                }
            }
        }
    }

}