package com.adealink.weparty.order

import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.module.order.Order
import com.adealink.weparty.module.order.data.OrderDetailInfo
import com.adealink.weparty.order.adapter.UserOrderListItemViewBinder
import com.adealink.weparty.order.data.UserOrderListItemData
import com.adealink.weparty.order.databinding.ActivityUserOrderListBinding
import com.adealink.weparty.order.dialog.EvaluateOrderDialog
import com.adealink.weparty.order.viewmodel.OrderViewModelFactory
import com.adealink.weparty.order.viewmodel.UserOrderViewModel
import com.adealink.weparty.util.applyImmersive
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Order.List.PATH], desc = "用户订单列表")
class UserOrderListActivity : BaseActivity(), UserOrderListItemViewBinder.OrderListListener {

    companion object {
        private const val TAG = "UserOrderListActivity"
    }

    private val binding by viewBinding(ActivityUserOrderListBinding::inflate)

    private val viewModel by viewModels<UserOrderViewModel> { OrderViewModelFactory() }

    private val listAdapter by fastLazy { MultiTypeListAdapter<UserOrderListItemData>() }

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
        applyImmersive { top ->
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }

        binding.vRefresh.setEnableRefresh(true)
        binding.vRefresh.setEnableLoadMore(true)
        binding.vRefresh.setEnableAutoLoadMore(true)
        binding.vRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.pullOrderList()
            }


            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.loadMoreOrderList()
            }
        })

        listAdapter.register(UserOrderListItemViewBinder(this))
        binding.rvOrder.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        binding.rvOrder.adapter = listAdapter
        binding.rvOrder.addItemDecoration(
            VerticalSpaceItemDecoration(
                10.dp(),
                firstSpaceHeight = 10.dp()
            )
        )
    }

    override fun loadData() {
        super.loadData()
        viewModel.pullOrderList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.orderListLD.observe(this) {
            listAdapter.submitList(it)
            if (it.isNullOrEmpty()) {
                binding.rvOrder.gone()
                binding.vErrorView.show(
                    errorEmptyResId = APP_R.drawable.common_order_list_empty_ic,
                    title = APP_R.string.commonui_list_empty
                )
            } else {
                binding.rvOrder.show()
                binding.vErrorView.gone()
            }
        }
        viewModel.orderListRltLD.observe(this) { rlt ->
            binding.vRefresh.finishRefresh()
            binding.vRefresh.finishLoadMore()
            binding.vRefresh.setEnableLoadMore(viewModel.hasMoreData())
            showFailedToast(rlt)
        }
    }

    override fun showOrderDetail(data: OrderDetailInfo) {
        Router.build(this, Order.Detail.PATH)
            .putExtra(Order.Detail.EXTRA_ORDER_DETAIL, data)
            .start()
    }

    override fun cancelOrder(item: UserOrderListItemData, position: Int) {
        fun cancelOrderInner() {
            showLoading()
            viewModel.cancelOrder(item.data).observe(this) { rlt ->
                dismissLoading()
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success -> {
                        item.data = rlt.data
                        listAdapter.notifyItemChanged(position)
                    }
                }
            }
        }
        CommonDialog.Builder()
            .message(getCompatString(APP_R.string.common_user_cancel_order_tips))
            .positiveText(getCompatString(APP_R.string.commonui_confirm))
            .setShowDefaultCancel(true)
            .onPositive {
                cancelOrderInner()
            }
            .show(supportFragmentManager)
    }

    override fun completeOrder(item: UserOrderListItemData, position: Int) {
        fun completeOrderInner() {
            showLoading()
            viewModel.completeOrder(item.data).observe(this) { rlt ->
                dismissLoading()
                when (rlt) {
                    is Rlt.Failed -> {
                        showFailedToast(rlt)
                    }

                    is Rlt.Success -> {
                        item.data = rlt.data
                        listAdapter.notifyItemChanged(position)
                    }
                }
            }
        }
        CommonDialog.Builder()
            .title(getCompatString(APP_R.string.common_user_complete_order_tips))
            .positiveText(getCompatString(APP_R.string.commonui_confirm))
            .setShowDefaultCancel(true)
            .onPositive {
                completeOrderInner()
            }
            .show(supportFragmentManager)
    }

    override fun evaluateOrder(item: UserOrderListItemData, position: Int) {
        EvaluateOrderDialog().apply {
            setOrderInfo(item.data)
            setListener(object : EvaluateOrderDialog.OnEvaluateListener {
                override fun onEvaluate(star: Float, comment: String) {
                    item.data.star = star
                    listAdapter.notifyItemChanged(position)
                }
            })
        }.show(supportFragmentManager, "EvaluateOrderDialog")
    }


}