package com.yidian.shenghuoquan.buserorder.ui.widget

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.bcommon.constant.XBirdPageConstants
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.bcommon.widget.CommonHintDialog
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.adapter.OrderDetailCommodityListAdapter
import com.yidian.shenghuoquan.buserorder.databinding.BorderViewOrderCommodityInfoBinding
import com.yidian.shenghuoquan.buserorder.dto.OrderDetailDto
import com.yidian.shenghuoquan.buserorder.manager.OrderStatus
import com.yidian.shenghuoquan.buserorder.viewmodel.OrderCommodityInfoViewModel
import com.yidian.xpage.XPageManager

/**
 * author: yinjiacheng
 * date: 2021/8/21 22:19
 * description: 订单商品信息
 */
class OrderCommodityInfoView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
  ConstraintLayout(context, attrs, defStyle) {

  private val binding =
    DataBindingUtil.inflate<BorderViewOrderCommodityInfoBinding>(
      LayoutInflater.from(getContext()),
      R.layout.border_view_order_commodity_info,
      this,
      true
    )
  private val adapter by lazy { OrderDetailCommodityListAdapter(null) }
  private val vm by lazy { OrderCommodityInfoViewModel() }
  private var callback: OnOrderCommodityInfoCallback? = null

  init {
    initRecycleView()
    registerUIEvent()
  }

  private fun initRecycleView() {
    binding.rvCommodityList.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    binding.rvCommodityList.adapter = adapter
    binding.rvCommodityList.addItemDecoration(OrderDetailCommodityListAdapter.OrderDetailCommodityListItemDecoration())
  }

  /**
   * 注册UI事件监听
   */
  private fun registerUIEvent() {
    // 监听点击申请退款 弹窗二次确认
    vm.applyRefund.observe(context as LifecycleOwner, {
      CommonHintDialog(context, "您是要申请退款吗？", arrayListOf("取消", "确定"), object : CommonHintDialog.OnHintOptionCallback {
        override fun onLeftOption() {

        }

        override fun onRightOption() {
          // 确认申请退款
          vm.requestApplyRefund(it)
        }

      }, null, R.color.color_FD7823).show()
    })
    // 监听申请退款接口请求结果
    vm.applyRefundResult.observe(context as LifecycleOwner, {
      if (it) {
        ToastUtils.showShortSafe("已申请退款")
        // 回调申请退款成功
        callback?.onApplyRefundSuccess()
      }
    })
    // 监听点击联系卖家
    vm.contractSeller.observe(context as LifecycleOwner, { phone ->
      // 先判断权限
      RxPermissions(context as FragmentActivity).request(Manifest.permission.CALL_PHONE).subscribe { granted ->
        if (granted) {
          val intent = Intent(Intent.ACTION_DIAL)
          intent.data = Uri.parse("tel:$phone")
          context.startActivity(intent)
        } else {
          ToastUtils.showShortSafe("请在设置里同意相关权限")
        }
      }
      // 回调联系卖家
      callback?.onContractSeller()
    })
    // 监听点击跳转活动详情页
    vm.gotoMarketingDetail.observe(context as LifecycleOwner, {
      val pageUrl = XBirdPageConstants.FIGHT_ORDER_EVENT_DETAILS + "?marketing_id=${it}"
      XPageManager.push(XRouterPathConstants.COMMON_WEB_VIEW_ACTIVITY, hashMapOf(Pair(XBirdPageConstants.PAGE_URL, pageUrl)))
      // 回调跳转活动详情
      callback?.onGotoMarketingDetail()
    })
  }

  /**
   * 设置商品信息
   * @param status 订单状态 确认订单时固定传ORDER_STATUS_WAIT_PAY
   * @param info 商品信息
   */
  fun setCommodityInfo(status: OrderStatus, info: OrderDetailDto, callback: OnOrderCommodityInfoCallback?) {
    binding.vm = vm
    binding.status = status
    binding.data = info
    this.callback = callback
    adapter.updateData(info.mergeOrderItemList)
  }

  interface OnOrderCommodityInfoCallback {
    /**
     * 跳转活动详情
     */
    fun onGotoMarketingDetail()

    /**
     * 申请退款成功
     */
    fun onApplyRefundSuccess()

    /**
     * 联系卖家
     */
    fun onContractSeller()
  }
}
