package com.yidian.shenghuoquan.bmanagercenter.personnel.ui

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.constant.XRouterPathConstants.Companion.PERSONAL_MANAGER_CHANGE
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.extensions.clickAntiShake
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
import com.yidian.bcommon.widget.EditTextInputCallback
import com.yidian.bcommon.widget.PhoneNumberTextWatcher
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.bcommon.bean.HintOptionBean
import com.yidian.shenghuoquan.bmanagercenter.databinding.ActivityManagerChangeBinding
import com.yidian.shenghuoquan.bmanagercenter.personnel.http.PersonalRemoteDataSource
import com.yidian.shenghuoquan.bmanagercenter.personnel.http.callback.IPersonalChangeAccountCallBack
import com.yidian.shenghuoquan.bmanagercenter.personnel.http.callback.IPersonalCheckSmsCodeCallBack
import com.yidian.bcommon.widget.dialog.HintDialog
import com.yidian.bcommon.utils.CountDownTimerUtils
import com.yidian.bcommon.utils.StorageUtil
import com.yidian.bcommon.utils.TextWatcherAdapter
import com.yidian.bcommon.webview.PublicWebViewActivity
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket
import org.json.JSONObject

/**
 * 人员管理 —— 管理员变更
 */
class ManagerChangeActivity : BaseActivity<ActivityManagerChangeBinding>() {

  private var mobileMatchSuccess: Boolean = false
  private var verificationSteps: Int = 1 // 当前验证步骤 1：旧账号，2：新账号
  private var managerOldMobile: String = "" // 旧手机号
  private var managerNewMobile: String = "" // 新手机号
  private lateinit var mCountDownTimerUtils: CountDownTimerUtils
  private var newMobileFinish = false // 手机号输入完成
  private var oldCodeFinish = false   // 验证码输入完成
  private var newCodeFinish = false   // 验证码输入完成

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

  override fun getXPageName(): String {
    return PERSONAL_MANAGER_CHANGE
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    getIntentData(intent)
    initView()
    initClick()
  }

  private fun getIntentData(intent: Intent?) {
    val paramsMap = intent?.getSerializableExtra(XRouterPathConstants.ParamsKey)
    if (paramsMap != null) {
      paramsMap as HashMap<*, *>
      managerOldMobile = paramsMap["mobile"] as String
    }
  }

  private fun initView() {
    initTitleBar(viewBind.include.toolbar, viewBind.include.tvTitle, "管理员变更")
    // 设置旧手机号
    if (managerOldMobile.isNotBlank()) {
      viewBind.ncvMobile.setOriginalNumber(managerOldMobile)
    }
    // 按钮不可点
    setChangeButtonStatus(false)
    // 初始化用户协议
    initUserProtocol()
    // 初始化倒计时
    mCountDownTimerUtils = CountDownTimerUtils(viewBind.tvGetCode, 60000, 1000)
  }

  private fun initClick() {
    // 手机号匹配的监听
    viewBind.ncvMobile.setOnNumberMatchListener {
      mobileMatchSuccess = true
    }
    // 旧账号的验证码输入监听
    viewBind.etOldCode.addTextChangedListener(object : TextWatcherAdapter() {
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s?.length == 6) {
          oldCodeFinish = true
          updateChangeButton()
        } else if (oldCodeFinish) {
          oldCodeFinish = false
          updateChangeButton()
        }
      }
    })
    // 发送验证码
    viewBind.tvGetCode.clickAntiShake {
      when (verificationSteps) {
        1 -> {
          if (mobileMatchSuccess) {
            requestSmsCode(managerOldMobile)
          } else {
            ToastUtil.showToast(this, "请输入正确的旧账号")
          }
        }
        2 -> {
          val mobile = viewBind.etNewMobile.text.toString().replace(" ", "")
          if (mobile.length == 11) {
            requestSmsCode(mobile)
          } else {
            ToastUtil.showToast(this, "请输入11位手机号")
          }
        }
      }
    }

    // 更换账号
    viewBind.tvChangeAccount.clickAntiShake {
      // 更换账号，进行验证码校验
      val code = viewBind.etOldCode.text.toString()
      val paramsMap = HashMap<String, String?>()
      paramsMap["mobile"] = managerOldMobile.replace(" ", "")
      paramsMap["code"] = code
      PersonalRemoteDataSource.getCheckSmsCode(getCheckOldSmsCodeCallBack, paramsMap)
    }

    // 新账号输入监听
    viewBind.etNewMobile.addTextChangedListener(PhoneNumberTextWatcher(viewBind.etNewMobile, object : EditTextInputCallback {
      override fun inputCallback(s: String) {
        if (s.length == 13) {
          newMobileFinish = true
          updateConfirmButton()
        } else if (newMobileFinish) {
          newMobileFinish = false
          updateConfirmButton()
        }
      }
    }))

    // 新账号的验证码输入监听
    viewBind.etNewCode.addTextChangedListener(object : TextWatcherAdapter() {
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s?.length == 6) {
          newCodeFinish = true
          updateConfirmButton()
        } else if (newCodeFinish) {
          newCodeFinish = false
          updateConfirmButton()
        }
      }
    })

    // 确认更换
    viewBind.tvConfirmChange.clickAntiShake {
      // 确认更换
      managerNewMobile = viewBind.etNewMobile.text.toString().replace(" ", "")
      val code = viewBind.etNewCode.text.toString()
      val paramsMap = HashMap<String, String?>()
      paramsMap["mobile"] = managerNewMobile.replace(" ", "")
      paramsMap["code"] = code
      paramsMap["life_account_id"] = StorageUtil.getLifeAccountId()
      PersonalRemoteDataSource.getChangeManager(getChangeAccountCallBack, paramsMap)
    }

  }

  private fun initUserProtocol() {
    val builder = SpannableStringBuilder().also {
      it.append(resources.getString(R.string.manager_register_tips))
      it.setSpan(ForegroundColorSpan(Color.parseColor("#1852F1")), 28, 39, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
      it.setSpan(object : ClickableSpan() {
        override fun onClick(widget: View) {
          PublicWebViewActivity.startWebViewActivity(this@ManagerChangeActivity, AppConfig.userProtocol)
        }
      }, 28, 33, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
      it.setSpan(object : ClickableSpan() {
        override fun onClick(widget: View) {
          PublicWebViewActivity.startWebViewActivity(this@ManagerChangeActivity, AppConfig.privacyPolicy)
        }
      }, 33, 39, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    viewBind.tvRegisterTips.movementMethod = LinkMovementMethod.getInstance()
    viewBind.tvRegisterTips.text = builder
  }

  /**
   * 请求短信验证码
   */
  private fun requestSmsCode(mobile: String) {
    val jsonObject = JSONObject()
    jsonObject.put("mobile", mobile)
    jsonObject.put("scene", "enterprise")
    ZapTicket(ZapServiceNameConstants.GeneralAbilityService)
      .withAction(ZapServiceActionConstants.ActionRequestSmsCode)
      .withServiceParams(jsonObject)
      .onResult { result ->
        // 请求成功开始倒计时
        if (result.result as Boolean) {
          mCountDownTimerUtils.start()
        }
      }
      .ship()
  }

  private fun updateChangeButton() {
    if (mobileMatchSuccess && oldCodeFinish) {
      setChangeButtonStatus(true)
    } else {
      setChangeButtonStatus(false)
    }
  }

  private fun updateConfirmButton() {
    if (newMobileFinish && newCodeFinish) {
      setChangeButtonStatus(true)
    } else {
      setChangeButtonStatus(false)
    }
  }

  private fun setChangeButtonStatus(flag: Boolean) {
    when (verificationSteps) {
      1 -> {
        if (flag) {
          viewBind.tvChangeAccount.alpha = 1.0f
          viewBind.tvChangeAccount.isEnabled = true
        } else {
          viewBind.tvChangeAccount.alpha = 0.32f
          viewBind.tvChangeAccount.isEnabled = false
        }
      }
      2 -> {
        if (flag) {
          viewBind.tvConfirmChange.alpha = 1.0f
          viewBind.tvConfirmChange.isEnabled = true
        } else {
          viewBind.tvConfirmChange.alpha = 0.32f
          viewBind.tvConfirmChange.isEnabled = false
        }
      }
    }

  }

  private val getCheckOldSmsCodeCallBack = object : IPersonalCheckSmsCodeCallBack {

    override fun checkSmsCodeSuccess() {
      toNextStep()
    }
  }

  private fun toNextStep() {
    // 更新页面为验证新账号
    verificationSteps = 2
    viewBind.tvSerialNumber1.background = ContextCompat.getDrawable(this@ManagerChangeActivity, R.drawable.shape_gray_circle_bg)
    viewBind.tvSerialNumber1.setTextColor(ContextCompat.getColor(this@ManagerChangeActivity, R.color.color_666666))
    viewBind.tvSerialNumber2.background = ContextCompat.getDrawable(this@ManagerChangeActivity, R.drawable.shape_blue_circle_bg)
    viewBind.tvSerialNumber2.setTextColor(ContextCompat.getColor(this@ManagerChangeActivity, R.color.color_1852F1))
    viewBind.ncvMobile.visibility = View.GONE
    viewBind.etNewMobile.visibility = View.VISIBLE
    viewBind.etOldCode.visibility = View.GONE
    viewBind.etNewCode.visibility = View.VISIBLE
    // 充值获取验证码
    mCountDownTimerUtils.cancel()
    mCountDownTimerUtils.onFinish()
    // 更新按钮
    viewBind.tvChangeAccount.visibility = View.GONE
    viewBind.tvConfirmChange.visibility = View.VISIBLE
    // 显示用户协议
    viewBind.llProtocol.visibility = View.VISIBLE
  }

  private val getChangeAccountCallBack = object : IPersonalChangeAccountCallBack {

    override fun changeAccountSuccess() {
      // 显示重新登录的弹框
      showLoginDialog()
    }

    override fun changeAccountFailure() {
      // 使用后台提示语即可
    }
  }

  private fun showLoginDialog() {
    val content = "“一点资讯产品部”生活号已完成管理员账号变更，请使用新账号 $managerNewMobile 登录"
    HintDialog(this@ManagerChangeActivity, content, arrayListOf(HintOptionBean("重新登录")),
      object : HintDialog.OnHintOptionCallback {
        override fun onLeftOption() {
        }

        override fun onRightOption() {
          XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
        }
      }).show()
  }

  override fun onDestroy() {
    super.onDestroy()
    mCountDownTimerUtils.cancel()
  }
}
