package com.yidian.shenghuoquan.buserorder.ui

import androidx.activity.viewModels
import com.yidian.bcommon.constant.IntentConstants
import com.yidian.bcommon.constant.XEventConfig
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.databinding.BorderActivityOrderDetailBinding
import com.yidian.shenghuoquan.buserorder.manager.OrderStatusManager
import com.yidian.shenghuoquan.buserorder.viewmodel.OrderDetailViewModel
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xpage.XPageViewProtocol
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * author: yinjiacheng
 * date: 2021/8/21 09:29
 * description: 订单详情页
 */
class OrderDetailActivity : BaseMvvmActivity<BorderActivityOrderDetailBinding, OrderDetailViewModel>(), XPageViewProtocol {

  override val layoutId: Int = R.layout.border_activity_order_detail
  override val vm: OrderDetailViewModel by viewModels()

  /**
   * 订单id
   */
  private val orderId by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let { params ->
      (params as HashMap<*, *>)[IntentConstants.KEY_EXTRA_ORDER_ID]?.let {
        it as String
      }
    }
  }

  override fun getXPageName(): String {
    return XRouterPathConstants.ORDER_DETAIL_ACTIVITY
  }

  override fun initView() {
    initSmartRefresh()
    vm.orderDetailData.observe(this, {
      // 结束刷新
      binding.rlOrderDetail.finishRefresh(it != null)
      if (it == null) return@observe
      // 获取当前订单状态
      val status = OrderStatusManager.getOrderStatus(it.orderStatus)
      // 更新UI
      binding.svOrderStatus.setOrderStatus(status, it)
      binding.pvPickupPointInfo.setPickupPoint(it.placeList)
      binding.ivConsigneeInfo.setConsigneeInfo(status, it.orderShippingInfo)
      binding.ivCommodityInfo.setCommodityInfo(status, it)
      binding.ivOrderInfo.setOrderInfo(status, it)
    })
    binding.rlOrderDetail.autoRefresh()
  }

  private fun initSmartRefresh() {
    // 禁止上拉加载更多
    binding.rlOrderDetail.setEnableLoadMore(false)
    binding.rlOrderDetail.setOnRefreshListener {
      // 请求订单详情
      orderId?.let { vm.requestOrderDetail(it) }
    }
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.APPLY_REFUND_SUCCESS -> {
        // 申请退款成功 刷新页面
        binding.rlOrderDetail.autoRefresh()
      }
    }
  }
}
