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 com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.databinding.BorderViewOrderPickupPointInfoBinding
import com.yidian.shenghuoquan.buserorder.dto.PlaceList
import com.yidian.shenghuoquan.buserorder.viewmodel.OrderPickupPointViewModel

/**
 * author: yinjiacheng
 * date: 2021/8/21 13:45
 * description: 订单自提点信息
 */
class OrderPickupPointInfoView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
  ConstraintLayout(context, attrs, defStyle) {

  private val binding =
    DataBindingUtil.inflate<BorderViewOrderPickupPointInfoBinding>(
      LayoutInflater.from(getContext()),
      R.layout.border_view_order_pickup_point_info,
      this,
      true
    )
  private val vm by lazy { OrderPickupPointViewModel() }
  private var callback: OnOrderPickupPointInfoCallback? = null

  init {
    registerUIEvent()
  }

  /**
   * 注册UI事件监听
   */
  private fun registerUIEvent() {
    // 监听点击联系自提点
    vm.contractPickupPoint.observe(context as LifecycleOwner, { phone ->
      if (phone.isNullOrEmpty()) return@observe
      // 先判断权限
      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?.onContractPickupPoint()
    })
  }

  /**
   * 设置自提点
   * @param info 自提点信息
   */
  fun setPickupPoint(info: PlaceList?, callback: OnOrderPickupPointInfoCallback?) {
    binding.vm = vm
    binding.data = info
    this.callback = callback
  }

  interface OnOrderPickupPointInfoCallback {
    /**
     * 联系自提点
     */
    fun onContractPickupPoint()
  }
}
