package com.yidian.shenghuoquan.broot.ui

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.*
import com.yidian.bcommon.constant.XRouterPathConstants.Companion.FLASH
import com.yidian.bcommon.app.YdBaseApplication
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.constant.HawkConfig
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.extensions.continuousClick
import com.yidian.bcommon.services.AppUpgradeService
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
import com.yidian.bcommon.utils.ToastUtils
import com.yidian.bcommon.webview.PublicWebViewActivity
import com.yidian.shenghuoquan.broot.BaseInitConfig
import com.yidian.shenghuoquan.broot.R
import com.yidian.shenghuoquan.broot.databinding.ActivityFlashBinding
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket
import timber.log.Timber

/**
 * 启动页
 */
class FlashActivity : BaseActivity<ActivityFlashBinding>() {

  private var privacyDialog: AlertDialog? = null

  override fun createViewBinding(): ActivityFlashBinding {
    return ActivityFlashBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return FLASH
  }

  override fun onResume() {
    super.onResume()
    checkPrivacyIsAgreed()
  }

  /**
   * 检查隐私协议是否同意
   */
  private fun checkPrivacyIsAgreed() {
    val isAgree = Hawk.get(HawkConfig.ProtocolIsAgree, false)
    if (isAgree) {
      toLoginOrHome()
    } else {
      showPrivacyDialog()
    }
  }

  /**
   * 进登录页或首页
   */
  private fun toLoginOrHome() {
    // 先执行剩余的初始化任务
    BaseInitConfig.performInitialization(YdBaseApplication.context)
    // 判断往哪里走
    val loginStatus = Hawk.get(HawkConfig.LoginStatus, false)
    if (loginStatus) {
      // 已登录请求生活号列表
      ZapTicket(ZapServiceNameConstants.LifeNumberListService).withAction(ZapServiceActionConstants.ActionRequestList)
        .onResult { result ->
          // 请求生活号列表成功，关闭启动页
          if (result.result as Boolean) {
            Timber.tag("测试启动").e("请求成功，可以关闭启动页")
            XPageManager.pop(null)
          }
        }.ship()
    } else {
      // 跳转登录
      XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
      finish()
      // 检查app更新
      ZapTicket(AppUpgradeService.SERVICE_NAME).withAction(AppUpgradeService.ACTION_CHECK_APP_UPGRADE).ship()
    }
  }

  /**
   * 显示隐私弹框
   */
  private fun showPrivacyDialog() {
    val builder = AlertDialog.Builder(this, R.style.NoTitleDialog)
    val updateDialog = View.inflate(this, R.layout.dialog_privacy, null)
    val tvContent = updateDialog.findViewById<TextView>(R.id.tv_privacy_tips)
    val btnCancel = updateDialog.findViewById<TextView>(R.id.tv_cancel)
    val btnEnsure = updateDialog.findViewById<TextView>(R.id.tv_sure)
    builder.setView(updateDialog)
    builder.setCancelable(false)
    builder.create()

    // 提示内容
    initUserProtocol(tvContent)
    // 取消按钮
    btnCancel.setOnClickListener {
      dismissPrivacyDialog()
      this.finish()
    }
    // 确定按钮
    btnEnsure.setOnClickListener {
      dismissPrivacyDialog()
      // 同意则执行剩余的初始化并进入登录或首页
      Hawk.put(HawkConfig.ProtocolIsAgree, true)
      toLoginOrHome()
    }
    // 内容连续点击多次，触发环境切换页面
    tvContent.continuousClick {
      ToastUtils.showShortSafe("进行环境切换")
      startActivity(Intent(this, TestActivity::class.java))
    }
    builder.show()
  }

  private fun initUserProtocol(textView: TextView) {
    val span = SpannableString(resources.getString(R.string.privacy_tips))
    span.setSpan(object : ClickableSpan() {
      override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.color = Color.parseColor("#1852F1");
        ds.isUnderlineText = false;// 去掉下划线
      }

      override fun onClick(widget: View) {
        val intent = Intent(this@FlashActivity, PublicWebViewActivity::class.java)
        intent.putExtra("url", AppConfig.userProtocol)
        startActivity(intent)
      }
    }, 19, 25, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    span.setSpan(object : ClickableSpan() {
      override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        ds.color = Color.parseColor("#1852F1");
        ds.isUnderlineText = false;// 去掉下划线
        ds.clearShadowLayer();//清除阴影
      }

      override fun onClick(widget: View) {
        val intent = Intent(this@FlashActivity, PublicWebViewActivity::class.java)
        intent.putExtra("url", AppConfig.privacyPolicy)
        startActivity(intent)
      }
    }, 26, 32, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.setLinkTextColor(Color.TRANSPARENT)
    textView.setHintTextColor(resources.getColor(R.color.transparent)) //设置点击后的颜色为透明，否则会一直出现高亮
    textView.append(span)
    textView.movementMethod = LinkMovementMethod.getInstance() //开始响应点击事件
  }

  /**
   * 关闭弹框
   */
  private fun dismissPrivacyDialog() {
    if (privacyDialog != null && privacyDialog!!.isShowing) {
      privacyDialog!!.dismiss()
      privacyDialog = null
    }
  }

  override fun onPause() {
    super.onPause()
    dismissPrivacyDialog()
  }

}
