package com.yidian.shenghuoquan.bsetting.ui.login

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.constant.AppConfig
import com.yidian.bcommon.constant.HawkConfig
import com.yidian.bcommon.constant.XRouterPathConstants.Companion.LOGIN_LIFE_CIRCLE
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.extensions.hide
import com.yidian.bcommon.extensions.show
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
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.bcommon.widget.EditTextInputCallback
import com.yidian.bcommon.widget.PhoneNumberTextWatcher
import com.yidian.shenghuoquan.bsetting.R
import com.yidian.shenghuoquan.bsetting.databinding.ActivityLoginBinding
import com.yidian.shenghuoquan.bsetting.http.SettingRemoteDataSource
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager
import com.yidian.yac.core.zap.ZapTicket
import org.json.JSONObject
import timber.log.Timber

/**
 * 登录页
 */
class LoginLifeCircleActivity : BaseActivity<ActivityLoginBinding>(), View.OnFocusChangeListener {

  private lateinit var mCountDownTimerUtils: CountDownTimerUtils
  private var mobileFinish = false
  private var codeFinish = false
  private var protocolAgree = false

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

  override fun getXPageName(): String {
    return LOGIN_LIFE_CIRCLE
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    initView()
    setOnListener()
  }

  private fun initView() {
    cleanLocalStorage()
    setLoginButtonStatus(false)
    mCountDownTimerUtils = CountDownTimerUtils(viewBind.tvGetCode, 60000, 1000)
  }

  private fun setOnListener() {
    // 获取验证码
    viewBind.tvGetCode.setOnClickListener {
      val mobile = viewBind.etMobileNo.text.toString().replace(" ", "")
      if (mobile.length == 11) {
        requestSmsCode(mobile)
      } else {
        ToastUtil.showToast(this, "请输入11位手机号")
      }
    }
    // 手机号输入监听
    viewBind.etMobileNo.addTextChangedListener(PhoneNumberTextWatcher(viewBind.etMobileNo, object : EditTextInputCallback {
      override fun inputCallback(s: String) {
        if (s.isNotEmpty()) {
          viewBind.ivClearMobile.show()
        } else {
          viewBind.ivClearMobile.hide()
        }
        if (s.length == 13) {
          mobileFinish = true
          changeLoginButtonStatus()
        } else if (mobileFinish) {
          mobileFinish = false
          changeLoginButtonStatus()
        }
      }
    }))
    // 手机号输入框焦点监听
    viewBind.etMobileNo.onFocusChangeListener = this
    // 清空输入的手机号
    viewBind.ivClearMobile.setOnClickListener {
      viewBind.etCode.setText("")
      viewBind.etMobileNo.setText("")
      viewBind.etMobileNo.requestFocus()
    }
    // 验证码输入监听
    viewBind.etCode.addTextChangedListener(object : TextWatcherAdapter() {
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s?.length == 6) {
          codeFinish = true
          changeLoginButtonStatus()
        } else if (codeFinish) {
          codeFinish = false
          changeLoginButtonStatus()
        }
      }
    })
    // 验证码输入框焦点监听
    viewBind.etCode.onFocusChangeListener = this
    // 点击登录
    viewBind.tvLogin.setOnClickListener {
      requestMobileLogin()
    }
    // 同意用户协议和隐私协议的勾选框
    viewBind.cbProtocol.setOnCheckedChangeListener { _, isChecked ->
      protocolAgree = isChecked
      changeLoginButtonStatus()
    }
    // 用户协议
    viewBind.tvProtocol.setOnClickListener {
      PublicWebViewActivity.startWebViewActivity(this, AppConfig.userProtocol)
    }
    // 隐私政策
    viewBind.tvPrivacy.setOnClickListener {
      PublicWebViewActivity.startWebViewActivity(this, AppConfig.privacyPolicy)
    }
  }

  /**
   * 请求手机号登录
   */
  private fun requestMobileLogin() {
    val mobile = viewBind.etMobileNo.text.toString().replace(" ", "")
    val code = viewBind.etCode.text.toString()
    val paramsMap = HashMap<String, String?>()
    paramsMap["mobile"] = mobile
    paramsMap["code"] = code
    SettingRemoteDataSource.getMobileLogin(paramsMap) {
      it?.let {
        val loginResponse = it
        Hawk.put(HawkConfig.LoginStatus, true)
        Hawk.put(HawkConfig.UserId, loginResponse.user_id)
        Hawk.put(HawkConfig.Mobile, loginResponse.mobile)
        Hawk.put(HawkConfig.Nickname, loginResponse.nick_name)
        Hawk.put(HawkConfig.Avatar, loginResponse.avatar)
        // 登录成功后请求生活号列表接口
        ZapTicket(ZapServiceNameConstants.LifeNumberListService).withAction(ZapServiceActionConstants.ActionRequestList)
          .onResult { result ->
            // 请求生活号列表成功，关闭启动页
            if (result.result as Boolean) {
              Timber.tag("测试登录").e("登录成功，请求生活号列表")
              XPageManager.pop(null)
            }
          }.ship()
      }
    }
  }

  private fun changeLoginButtonStatus() {
    if (mobileFinish && codeFinish && protocolAgree) {
      setLoginButtonStatus(true)
    } else {
      setLoginButtonStatus(false)
    }
  }

  private fun setLoginButtonStatus(flag: Boolean) {
    if (flag) {
      viewBind.tvLogin.alpha = 1.0f
      viewBind.tvLogin.isEnabled = true
    } else {
      viewBind.tvLogin.alpha = 0.32f
      viewBind.tvLogin.isEnabled = false
    }
  }

  /**
   * 清理本地保存的数据
   */
  private fun cleanLocalStorage() {
    // 登录状态
    Hawk.put(HawkConfig.LoginStatus, false)
    // 生活号id
    StorageUtil.deleteLifeAccountId()
    // 通过服务 清除内存中的认证数据
    ZapTicket(ZapServiceNameConstants.LifeNumberListService)
      .withAction(ZapServiceActionConstants.ActionClearAuthenticationData)
      .ship()
  }

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

  override fun onFocusChange(v: View?, hasFocus: Boolean) {
    if (hasFocus) {
      // 获取焦点
      if (v == viewBind.etMobileNo) {
        viewBind.viewDividerMobile.setBackgroundColor(ContextCompat.getColor(this, R.color.color_333333))
      } else {
        viewBind.viewDividerPassword.setBackgroundColor(ContextCompat.getColor(this, R.color.color_333333))
      }
    } else {
      // 失去焦点
      if (v == viewBind.etMobileNo) {
        viewBind.viewDividerMobile.setBackgroundColor(ContextCompat.getColor(this, R.color.color_FFF2F2F2))
      } else {
        viewBind.viewDividerPassword.setBackgroundColor(ContextCompat.getColor(this, R.color.color_FFF2F2F2))
      }
    }
  }

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


}
