package com.yidian.shenghuoquan.newscontent.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.common.AppConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.XRouterPathConstants.Companion.PERSONAL_MANAGER_CHANGE
import com.yidian.common.base.BaseActivity
import com.yidian.common.extensions.initTitleBar
import com.yidian.common.widget.EditTextInputCallback
import com.yidian.common.widget.PhoneNumberTextWatcher
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.bean.HintOptionBean
import com.yidian.shenghuoquan.newscontent.databinding.ActivityManagerChangeBinding
import com.yidian.shenghuoquan.newscontent.personnel.http.PersonalRemoteDataSource
import com.yidian.shenghuoquan.newscontent.personnel.http.callback.IPersonalChangeAccountCallBack
import com.yidian.shenghuoquan.newscontent.personnel.http.callback.IPersonalCheckSmsCodeCallBack
import com.yidian.shenghuoquan.newscontent.personnel.http.callback.IPersonalGetSmsCodeCallBack
import com.yidian.shenghuoquan.newscontent.ui.ProtocolActivity
import com.yidian.shenghuoquan.newscontent.ui.dialog.HintDialog
import com.yidian.shenghuoquan.newscontent.utils.CountDownTimerUtils
import com.yidian.shenghuoquan.newscontent.utils.TextWatcherAdapter
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager

/**
 * 人员管理 —— 管理员变更
 */
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.setOnClickListener {
      when (verificationSteps) {
        1 -> {
          if (mobileMatchSuccess) {
            requestSmsCode(managerOldMobile)
          } else {
            ToastUtil.showToast(this, "请输入正确的旧账号")
          }
        }
        2 -> {
          val mobile = viewBind.etNewMobile.text.toString().replace(" ", "")
          if (mobile.length == 13) {
            requestSmsCode(mobile)
          } else {
            ToastUtil.showToast(this, "请输入11位手机号")
          }
        }
      }
    }

    // 更换账号
    viewBind.tvChangeAccount.setOnClickListener {
      // 更换账号，进行验证码校验
      val code = viewBind.etOldCode.text.toString()
      val paramsMap = HashMap<String, String?>()
      paramsMap["mobile"] = managerOldMobile
      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.setOnClickListener {
      // 确认更换
      managerNewMobile = viewBind.etNewMobile.text.toString().replace(" ", "")
      val code = viewBind.etNewCode.text.toString()
      val paramsMap = HashMap<String, String?>()
      paramsMap["mobile"] = managerNewMobile
      paramsMap["code"] = code
      // todo 生活号id待赋值
      paramsMap["life_account_id"] = ""
      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) {
          // todo 待修改为用户协议
          val urlMap = HashMap<String, String>()
          urlMap[ProtocolActivity.ProtocolUrlKey] = AppConfig.privacyPolicyStatement
          XPageManager.push(XRouterPathConstants.PROTOCOL, urlMap)
        }
      }, 28, 33, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
      it.setSpan(object : ClickableSpan() {
        override fun onClick(widget: View) {
          // todo 待修改为隐私政策
          val urlMap = HashMap<String, String>()
          urlMap[ProtocolActivity.ProtocolUrlKey] = AppConfig.privacyPolicyStatement
          XPageManager.push(XRouterPathConstants.PROTOCOL, urlMap)
        }
      }, 33, 39, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    viewBind.tvRegisterTips.movementMethod = LinkMovementMethod.getInstance()
    viewBind.tvRegisterTips.text = builder
  }

  /**
   * 获取验证码
   */
  private fun requestSmsCode(mobile: String) {
    val paramsMap = HashMap<String, String?>()
    paramsMap["mobile"] = mobile
    PersonalRemoteDataSource.getSmsCode(getSmsCodeCallBack, paramsMap)
  }

  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 getSmsCodeCallBack = object : IPersonalGetSmsCodeCallBack {

    override fun getSmsCodeSuccess() {
      // 开始倒计时
      mCountDownTimerUtils.start()
    }
  }

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