package com.yidian.shenghuoquan.newscontent.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.common.*
import com.yidian.common.XRouterPathConstants.Companion.FLASH
import com.yidian.common.base.BaseActivity
import com.yidian.common.services.AppUpgradeService
import com.yidian.common.webview.PublicWebViewActivity
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.databinding.ActivityFlashBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.callback.IGetLifeAccountListCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.LifeAccountItemBean
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountIdentityActivity
import com.yidian.shenghuoquan.newscontent.ui.center.MerchantCenterActivity
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket

class FlashActivity : BaseActivity<ActivityFlashBinding>(), IGetLifeAccountListCallback {

  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()
//    }
    showPrivacyDialog()
  }

  /**
   * 进登录页或首页
   */
  private fun toLoginOrHome() {
    // 先执行剩余的初始化任务
    BaseInitConfig.performInitialization(YdBaseApplication.context)
    // 判断往哪里走
    val loginStatus = Hawk.get(HawkConfig.LoginStatus, false)
    if (loginStatus) {
      // 已登录 请求生活号列表
      ApiService.getLifeAccountList(this)
    } else {
      // 未登录 跳转登录
      // 此处没有使用XPage打开页面 原因：不能设置flag
      startActivity(Intent(this, LoginLifeCircleActivity::class.java))
      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()
    }
    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.privacyPolicyStatement)
        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()
  }

  override fun getLifeAccountListSuccess(result: ArrayList<LifeAccountItemBean.Response>?) {
    when (result?.size) {
      0 -> {
        // 无生活号 进入认证流程
        XPageManager.push(XRouterPathConstants.LIFE_ACCOUNT_AUTH, null)
      }
      1 -> {
        // 关联一个生活号 进入商户管理中心
        XPageManager.push(
          XRouterPathConstants.MERCHANT_CENTER,
          hashMapOf(
            Pair(MerchantCenterActivity.EXTRA_LIFE_ACCOUNT_INFO, result[0]),
            Pair(MerchantCenterActivity.EXTRA_IS_MULTI, false)
          )
        )
      }
      else -> {
        // 关联多个生活号
        StorageUtil.getLifeAccountId()?.apply {
          // 如果本地有上次操作的生活号则遍历生活号列表进入对应生活号的管理中心
          result?.forEach {
            if (it.life_account_id == this) {
              XPageManager.push(
                XRouterPathConstants.MERCHANT_CENTER,
                hashMapOf(
                  Pair(MerchantCenterActivity.EXTRA_LIFE_ACCOUNT_INFO, it),
                  Pair(MerchantCenterActivity.EXTRA_IS_MULTI, result.size > 1)
                )
              )
            }
          }
        } ?: let {
          // 进入生活号选择页面
          XPageManager.push(
            XRouterPathConstants.LIFE_ACCOUNT_IDENTITY,
            hashMapOf(Pair(LifeAccountIdentityActivity.EXTRA_LIFE_ACCOUNT_LIST, result))
          )
        }
      }
    }
    XPageManager.pop(null)
    // 检查app更新
    ZapTicket(AppUpgradeService.SERVICE_NAME).withAction(AppUpgradeService.ACTION_CHECK_APP_UPGRADE).ship()
  }

  override fun getLifeAccountListFailure(message: String?) {

  }

}
