package com.yidian.shenghuoquan.newscontent.ui

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.AppConfig
import com.yidian.bcommon.HawkConfig
import com.yidian.bcommon.XRouterPathConstants
import com.yidian.bcommon.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.http.HttpResult
import com.yidian.bcommon.widget.EditTextInputCallback
import com.yidian.bcommon.widget.PhoneNumberTextWatcher
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.databinding.ActivityLoginBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.callback.IGetLifeAccountListCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.IMobileLoginCallback
import com.yidian.bcommon.bean.LifeAccountItemBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.MobileLoginBean
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountAuthDataManagerV2
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountIdentityActivity
import com.yidian.shenghuoquan.newscontent.ui.center.MerchantCenterActivity
import com.yidian.shenghuoquan.newscontent.utils.CountDownTimerUtils
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.shenghuoquan.newscontent.utils.TextWatcherAdapter
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager

/**
 * Author: zhb
 * Date: 2021/5/26 16:05 PM
 * Describe:短信登陆页面
 */
class LoginLifeCircleActivity : BaseActivity<ActivityLoginBinding>(), IGetLifeAccountListCallback,
  IMobileLoginCallback, 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) {
        val paramsMap = HashMap<String, String?>()
        paramsMap["mobile"] = mobile
        paramsMap["scene"] = "login"
        ApiService.sendMsgCode(this, paramsMap)
      } 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 {
      val mobile = viewBind.etMobileNo.text.toString().replace(" ", "")
      val code = viewBind.etCode.text.toString()
      val paramsMap = HashMap<String, String?>()
      paramsMap["mobile"] = mobile
      paramsMap["code"] = code
      ApiService.mobileLogin(this, paramsMap)
    }

    viewBind.cbProtocol.setOnCheckedChangeListener { buttonView, isChecked ->
      protocolAgree = isChecked
      changeLoginButtonStatus()
    }

    viewBind.tvProtocol.setOnClickListener {
      val map = HashMap<String, String>()
      map[ProtocolActivity.ProtocolTitleKey] = resources.getString(R.string.user_protocol)
      map[ProtocolActivity.ProtocolUrlKey] = AppConfig.userProtocol
      XPageManager.push(XRouterPathConstants.PROTOCOL, map)
    }

    viewBind.tvPrivacy.setOnClickListener {
      val map = HashMap<String, String>()
      map[ProtocolActivity.ProtocolTitleKey] = resources.getString(R.string.privacy_policy_statement)
      map[ProtocolActivity.ProtocolUrlKey] = AppConfig.privacyPolicyStatement
      XPageManager.push(XRouterPathConstants.PROTOCOL, map)
    }
  }

  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()
    // 清除内存中的认证数据
    LifeAccountAuthDataManagerV2.personalAuthData.clearData()
    LifeAccountAuthDataManagerV2.merchantAuthData.clearData()
  }

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

  override fun getLifeAccountListSuccess(result: ArrayList<LifeAccountItemBean.Response>?) {
    when (result?.size) {
      0 -> {
        // 无生活号 进入认证流程
        XPageManager.push(XRouterPathConstants.LIFE_ACCOUNT_AUTH, null)
      }
      1 -> {
        // 关联一个生活号 进入商户管理中心
        // 此处处理用户已经关联一个生活号但本地无存储/app数据被清除的情况
        StorageUtil.putLifeAccountId(result[0].life_account_id)
        XPageManager.push(
          XRouterPathConstants.MERCHANT_CENTER,
          hashMapOf(
            Pair(MerchantCenterActivity.EXTRA_LIFE_ACCOUNT_INFO, result[0]),
            Pair(MerchantCenterActivity.EXTRA_IS_MULTI, false)
          )
        )
      }
      else -> {
        // 关联多个生活号 进入身份选择
        XPageManager.push(
          XRouterPathConstants.LIFE_ACCOUNT_IDENTITY,
          hashMapOf(Pair(LifeAccountIdentityActivity.EXTRA_LIFE_ACCOUNT_LIST, result))
        )
      }
    }
    XPageManager.pop(null)
  }

  override fun getLifeAccountListFailure(message: String?) {

  }

  override fun sendSmsCodeCallBack(t: HttpResult<Any?>?) {
    if (t?.code == 0) {
      mCountDownTimerUtils.start()
    }
  }

  override fun mobileLoginCallBack(t: HttpResult<MobileLoginBean.Response?>?) {
    val loginResponse = t?.result
    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)
    if (t?.code == 0) {
      // 登录成功后请求生活号列表接口
      ApiService.getLifeAccountList(this)
    }
  }

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

}
