package com.yidian.shenghuoquan.buserorder.ui

import android.content.Intent
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.adapter.OrderConfirmCommodityListAdapter
import com.yidian.shenghuoquan.buserorder.databinding.BorderActivityConfirmOrderBinding
import com.yidian.shenghuoquan.buserorder.dto.PickupPoint
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import timber.log.Timber
import com.pingplusplus.android.Pingpp
import com.pingplusplus.android.Pingpp.REQUEST_CODE_PAYMENT
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.shenghuoquan.buserorder.viewmodel.ConfirmOrderViewModel
import com.yidian.xpage.XPageViewProtocol


/**
 * 确认订单
 */
class ConfirmOrderActivity : BaseMvvmActivity<BorderActivityConfirmOrderBinding, ConfirmOrderViewModel>(), XPageViewProtocol {

  private var marketingId: String? = null// 活动id

  private val adapter by lazy { OrderConfirmCommodityListAdapter() }

  override val layoutId: Int = R.layout.border_activity_confirm_order

  override val vm: ConfirmOrderViewModel by viewModels()

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

  override fun initView() {
    XEventManager.register(this)
    subscribeUiEvent()
    initList()
    getIntentData(intent)
  }

  private fun initList() {
    binding.rvGoodsList.adapter = adapter
  }

  private fun getIntentData(intent: Intent?) {
    val params = intent?.getSerializableExtra(XRouterPathConstants.ParamsKey)
    if (params != null) {
      // 注意接收h5传过来的JSONObject
      params as HashMap<String, Any?>
      // 解析h5传递的参数
      parsingParameters(JSONObject(params))
    }
  }

  private fun parsingParameters(jsonObject: JSONObject) {
//    // 解析本地json数据
//    val jsonStr = JsonUtils.file2JsonStr(this, "order.json")
//    jsonStr?.let {
//      val jsonObject = JSONObject(it)
//      Timber.tag("确认订单").e("订单请求参数JSON：${jsonObject}")
//      marketingId = jsonObject.optInt("marketing_id").toString()
//      requestConfirmOrder(jsonObject)
//    }

    Timber.tag("确认订单").e("订单请求参数JSON：${jsonObject}")
    marketingId = jsonObject.optInt("marketing_id").toString()
    requestConfirmOrder(jsonObject)
  }

  /**
   * 请求确认订单
   */
  private fun requestConfirmOrder(jsonObject: JSONObject) {
    vm.requestConfirmOrderInfo(jsonObject)
  }

  private fun subscribeUiEvent() {
    vm.goodsSuccessEvent.observe(this, {
      adapter.setList(it)
    })
    vm.chooseCouponEvent.observe(this) {
      // 将最新的优惠券列表传递过去
      val map = HashMap<String, Any?>()
      map[IntentConstants.KEY_EXTRA_COUPON_LIST] = it
      XPageManager.push(XRouterPathConstants.CHOOSE_VOUCHER_ACTIVITY, map)
    }
    vm.choosePointEvent.observe(this) {
      // 将选择的自提点id传递过去
      marketingId?.let { id ->
        val map = HashMap<String, Any?>()
        map[IntentConstants.KEY_EXTRA_PICKUP_POINT_ID] = it
        map[IntentConstants.KEY_EXTRA_MARKETING_ID] = id
        XPageManager.push(XRouterPathConstants.PICKUP_POINT_ACTIVITY, map)
      }
    }
    vm.toOrderDetailEvent.observe(this) {
      val map = HashMap<String, Any?>()
      map[IntentConstants.KEY_EXTRA_ORDER_ID] = it
      XPageManager.push(XRouterPathConstants.ORDER_DETAIL_ACTIVITY, map)
    }
    vm.toPaymentEvent.observe(this) {
      Pingpp.createPayment(this, it)
      Timber.tag("确认订单").e("支付charge：$it")
    }

  }

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

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.CONFIRM_ORDER_CHOOSE_POINT_SUCCESS -> {
        // 选择自提点成功
        val point = event.body as PickupPoint
        vm.choosePickUpPointSuccess(point)
      }
      XEventConfig.CONFIRM_ORDER_CHOOSE_COUPON_SUCCESS -> {
        // 选择优惠券成功
        val indexList = event.body as List<Int>
        vm.chooseVoucherSuccess(indexList)
      }
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    //支付页面返回处理
    if (requestCode == REQUEST_CODE_PAYMENT) {
      if (resultCode == RESULT_OK) {
        data?.extras?.let {
          val result = it.getString("pay_result")
          /* 处理返回值
           * "success" - 支付成功
           * "fail"    - 支付失败
           * "cancel"  - 取消支付
           * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
           * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
           */
          val errorMsg = it.getString("error_msg") // 错误信息
          val extraMsg = it.getString("extra_msg") // 错误信息
          if (result.equals("success")) {
            vm.paymentSuccess()
          } else {
            Timber.tag("确认订单").e("支付失败，错误原因：$errorMsg \n $extraMsg")
            ToastUtils.showShortSafe("支付失败，错误原因：$errorMsg \n $extraMsg")
          }
        }
      }
    }
  }

}
