package com.yidian.shenghuoquan.bmanagercenter.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.CompoundButton
import androidx.constraintlayout.widget.ConstraintLayout
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.webview.PublicWebViewActivity
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.databinding.ViewPrivacyAgreementBinding

/**
 * author: yinjiacheng
 * date: 6/24/21 3:32 AM
 * description: 用户协议、隐私政策
 */
class PrivacyAgreementView @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyle: Int = 0
) : ConstraintLayout(context, attrs, defStyle), View.OnClickListener, CompoundButton.OnCheckedChangeListener {

  private val viewBinding: ViewPrivacyAgreementBinding =
    ViewPrivacyAgreementBinding.bind(
      View.inflate(
        getContext(),
        R.layout.view_privacy_agreement,
        this
      )
    )

  private var callback: OnPrivacyAgreementCallback? = null

  init {
    viewBinding.tvPrivacyPolicy.setOnClickListener(this)
    viewBinding.tvUserAgreement.setOnClickListener(this)
    viewBinding.cbAgree.setOnCheckedChangeListener(this)
  }

  override fun onClick(v: View?) {
    val id = v?.id
    if (id == R.id.tv_privacy_policy) {
      // 隐私政策
      PublicWebViewActivity.startWebViewActivity(context, AppConfig.privacyPolicy)
    } else if (id == R.id.tv_user_agreement) {
      // 用户协议
      PublicWebViewActivity.startWebViewActivity(context, AppConfig.userProtocol)
    }
  }

  /**
   * 获取当前是否选中
   */
  fun getCheckState(): Boolean {
    return viewBinding.cbAgree.isChecked
  }

  override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
    if (buttonView?.isPressed == false) return
    callback?.onCheckPrivacyAgreement(isChecked)
  }

  fun setOnPrivacyAgreementCallback(callback: OnPrivacyAgreementCallback) {
    this.callback = callback
  }

  interface OnPrivacyAgreementCallback {
    /**
     * 选择用户协议和隐私政策
     */
    fun onCheckPrivacyAgreement(isCheck: Boolean)
  }
}
