package com.cheng.bole.ui.fragment.mine.order.list

import android.os.Bundle
import com.cheng.bole.R
import com.cheng.bole.databinding.FragmentOrderListBinding
import com.cheng.bole.event.OrderEvent
import com.cheng.bole.ui.activity.PublicActivity
import com.cheng.bole.ui.fragment.mine.order.cert.CertificateFragment
import com.cheng.bole.ui.fragment.mine.order.invoice.InvoiceFragment
import com.example.base.common.RxBus
import com.example.base.ui.BaseFragment
import com.example.base.widget.EmptyView
import com.example.base.widget.PageStatus

class OrderListFragment : BaseFragment<FragmentOrderListBinding, OrderListViewModel>() {
    private val status by lazy { arguments?.getString("status") ?: "" }

    private val mAdapter by lazy { OrderAdapter() }
    private val mEmptyView by lazy { EmptyView(requireContext()) }

    companion object {
        fun newInstance(status: String): OrderListFragment {
            val args = Bundle()
            args.putString("status", status)
            val fragment = OrderListFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView() {
        super.initView()

        binding.mRecyclerView.adapter = mAdapter
        mEmptyView.setNoDataLogo(R.mipmap.ic_empty_order)
        mEmptyView.setNoDataText("暂无订单")
        mAdapter.setEmptyView(mEmptyView)
    }

    override fun initData() {
        super.initData()
        mViewModel.getOrderList(status)
    }

    override fun initListener() {
        super.initListener()
        binding.mRefreshLayout.setOnRefreshListener {
            mViewModel.getOrderList(status)
        }

        mAdapter.setOnItemChildClickListener { _, view, i ->
            val item = mAdapter.getItem(i)
            when (view.id) {
                R.id.btn_invoice -> {
                    PublicActivity.start(requireContext(), InvoiceFragment::class.java, Pair("item", item))
                }

                R.id.btn_certificate -> {
                    PublicActivity.start(requireContext(), CertificateFragment::class.java, Pair("orderId", item.id))
                }
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.orderLiveData.observe(this) {
            mAdapter.setList(it)
            if (it.isNotEmpty()) {
                mEmptyView.setStatus(PageStatus.GONG)
            } else {
                mEmptyView.setStatus(PageStatus.NO_DATA)
            }
            binding.mRefreshLayout.finishRefresh()
        }

        val orderEvent = RxBus.defaultInstance.toObservable(OrderEvent::class.java).subscribe {
            binding.mRefreshLayout.autoRefresh()
        }
        addDisposable(orderEvent)
    }
}