package com.yidian.shenghuoquan.buserorder.ui

import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
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.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.adapter.PickupPointListAdapter
import com.yidian.shenghuoquan.buserorder.databinding.BorderActivitySelectPickupPointBinding
import com.yidian.shenghuoquan.buserorder.dto.PickupPointListDto
import com.yidian.shenghuoquan.buserorder.viewmodel.SelectPickupPointViewModel
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageViewProtocol
import com.yidian.yac.core.zap.ZapTicket
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * author: yinjiacheng
 * date: 2021/8/24 14:02
 * description: 选择自提点页
 */
class SelectPickupPointActivity : BaseMvvmActivity<BorderActivitySelectPickupPointBinding, SelectPickupPointViewModel>(),
  XPageViewProtocol {

  override val layoutId = R.layout.border_activity_select_pickup_point
  override val vm: SelectPickupPointViewModel by viewModels()
  private val adapter by lazy { PickupPointListAdapter(null) }
  private val params by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      it as HashMap<*, *>
    }
  }
  private var location = false

  /**
   * 搜索关键字
   */
  private var keyWords: String? = null

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

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    XEventManager.register(this)
  }

  override fun onDestroy() {
    super.onDestroy()
    XEventManager.unRegister(this)
  }

  override fun initView() {
    initRecyclerView()
    initSmartRefresh()
    registerUIEvent()
    requestPickupPoint(SelectPickupPointViewModel.LoadType.SEARCH)
  }

  private fun initRecyclerView() {
    binding.rvPickupPointList.adapter = adapter
    binding.rvPickupPointList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
    binding.rvPickupPointList.addItemDecoration(PickupPointListAdapter.PickupPointListItemDecoration())
  }

  private fun initSmartRefresh() {
    // 禁止上拉加载更多
    binding.rlPickupPointList.setEnableLoadMore(false)
    binding.rlPickupPointList.setOnRefreshListener {
      requestPickupPoint(SelectPickupPointViewModel.LoadType.REFRESH)
    }
  }

  /**
   * 注册UI事件监听
   */
  private fun registerUIEvent() {
    vm.pickupPointListSearch.observe(this, {
      updateData(it)
    })
    vm.pickupPointListRefresh.observe(this, {
      binding.rlPickupPointList.finishRefresh(it != null)
      updateData(it)
    })
  }

  /**
   * 更新数据
   */
  private fun updateData(data: PickupPointListDto?) {
    if (data == null) return
    // 标记当前选中的自提点
    adapter.setSelectedId(params?.get(IntentConstants.KEY_EXTRA_PICKUP_POINT_ID)?.let { id -> id as Long })
    // 是否有位置信息 控制距离显示
    adapter.setLocation(location)
    adapter.updateData(data.list)
  }

  /**
   * 请求自提点列表 先调用C端客户端信息服务获取经纬度
   */
  private fun requestPickupPoint(type: SelectPickupPointViewModel.LoadType) {
    // 获取C端经纬度信息
    ZapTicket(ZapServiceNameConstants.ClientInfoService)
      .withAction(ZapServiceActionConstants.ActionGetCurrentLocation)
      .onResult { xResult ->
        val result = xResult.result as JSONObject
        val longitude = result.optDouble("longitude")
        val latitude = result.optDouble("latitude")
        location = longitude != 0.0 && latitude != 0.0
        // 是否有位置信息 控制附近自提点显示
        binding.location = location
        vm.requestPickupPointList(params?.get(IntentConstants.KEY_EXTRA_MARKETING_ID) as String, longitude, latitude, keyWords, type)
      }.ship()
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.SEARCH_PICKUP_POINT_CANCEL -> {
        keyWords = null
        // 取消搜索自提点 请求附近自提点
        requestPickupPoint(SelectPickupPointViewModel.LoadType.SEARCH)
      }
      XEventConfig.SEARCH_PICKUP_POINT_START -> {
        keyWords = event.body as String
        // 开始搜索自提点
        requestPickupPoint(SelectPickupPointViewModel.LoadType.SEARCH)
      }
    }
  }
}
