package com.yidian.shenghuoquan.border.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.border.R
import com.yidian.shenghuoquan.border.databinding.BorderViewOrderPickupPointInfoBinding
import com.yidian.shenghuoquan.border.dto.PlaceList
import com.yidian.shenghuoquan.border.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() }

  init {
    registerUIEvent()
  }

  /**
   * 注册UI事件监听
   */
  private fun registerUIEvent() {
    // 监听点击联系自提点
    vm.contractPickupPoint.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("请在设置里同意相关权限")
        }
      }
    })
  }

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