package com.abbidot.tracker.ui.activity.account

import android.content.Intent
import android.graphics.Paint
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityLoginV2Binding
import com.abbidot.tracker.ui.activity.set.FirstPermissionsActivity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.LoginViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginV2Activity : BaseActivity<ActivityLoginV2Binding>(ActivityLoginV2Binding::inflate) {

    private val mLoginViewModel: LoginViewModel by viewModels()
    private val mTrackerViewModel: TrackerInfoViewModel by viewModels()

    private var isShowPassword = false
    private var isCurrentPostEven = false

    override fun getTopBar() = mViewBinding.loginV2TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")
        mViewBinding.apply {
            root.setBackgroundResource(R.drawable.icon_login_v2_bg)

            var userEmail = ""
            intent.extras?.apply {
                userEmail = getString(MMKVKey.Email, "")
            }
            ilLoginV2EmailAddress.let {
                it.tvInputNameTitle.setText(R.string.txt_email_address)
                it.etInputContent.setHint(R.string.login_txt_email)
                it.etInputContent.setText(userEmail)
                it.etInputContent.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvEmailErrorTipLogin, it.etInputContent
                )
            }
            ilLoginV2Password.let {
                it.tvInputNameTitle.setText(R.string.login_txt_password)
                it.etInputContent.setHint(R.string.login_txt_password)
                ViewUtil.instance.setShowAndHidePassword(
                    it.etInputContent, it.ivInputRepresentImage
                )
                val filters = arrayOf<InputFilter>(InputFilter.LengthFilter(60))
                it.etInputContent.filters = filters
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvPasswordErrorTipLogin, it.etInputContent
                )
            }
            //添加下划线
            tvLoginV2ForgotPassword.paintFlags = Paint.UNDERLINE_TEXT_FLAG
            tvLoginV2Signup.paintFlags = Paint.UNDERLINE_TEXT_FLAG

            setOnClickListenerViews(
                ilLoginV2EmailAddress.etInputContent,
                tvLoginV2Signup,
                tvLoginV2ForgotPassword,
                ilLoginV2Password.ivInputRepresentImage,
                btnLoginV2Login
            )

            if (AppUtils.isDebug()) {
                //不需要MD5加密登录
                btnLoginV2Login.setOnLongClickListener {
                    loginClick(false)
                    true
                }
            }

            setListenKeyboardChange(750)
        }
    }

    override fun liveDataObserve() {
        XEventBus.observe(this, EventName.FinishActivity) {
            if (!isCurrentPostEven) finish()
        }

        mLoginViewModel.mLoginLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        isCurrentPostEven = true
                        Util.dealLoginSuccessData(mContext, this)

                        showToast(R.string.txt_login_successful, gravity = Gravity.CENTER)
                        loginSuccessGo()
                        //登录成功，把保存的设备存本地
//                        mTrackerViewModel.getDeviceList(this@LoginV2Activity, 1)
                    }
                }
            })
            setButtonEnabled(
                mViewBinding.btnLoginV2Login, ConstantInt.Type1
            )
        }

        //获取设备列表
        mTrackerViewModel.getDeviceListLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.let { list ->
                        lifecycleScope.launch {
                            val isBindDevice = MMKVUtil.getInt(MMKVKey.isBindDevice)
                            val isBindPet = MMKVUtil.getInt(MMKVKey.isBindPet)
                            if (isBindDevice == ConstantInt.isBind && isBindPet == ConstantInt.NoBind) {
                                if (list.size > 0) {
                                    MMKVUtil.putString(MMKVKey.FirstDeviceId, list[0].deviceId)
                                    MMKVUtil.putString(
                                        MMKVKey.FirstDeviceOutId, list[0].deviceOutId
                                    )
                                }
                            }
                            withContext(Dispatchers.IO) {
                                //保存本地数据库
                                for (device in list) {
                                    if (!TextUtils.isEmpty(device.deviceOutId) && null != device.pet) {
                                        MyDatabase.deviceDao().insert(device)
                                    }
                                }
                            }

                            showToast(R.string.txt_login_successful, gravity = Gravity.CENTER)

                            loginSuccessGo()
                        }
                    }
                }
            }, isShowNoDataTip = false)
        }
    }

    private fun loginSuccessGo() {
        val hasPermissions = Util.checkNeedPermissionsEnabled(mContext)
        mViewBinding.btnLoginV2Login.postDelayed({
            if (hasPermissions) {
                startActivityFinish(Util.checkBindDeviceAndPetGoActivity(mContext))
            } else {
                startActivityFinish(Intent(mContext, FirstPermissionsActivity::class.java))
            }
        }, 1000)
    }

    private fun loginClick(isMd5: Boolean = true) {
        mViewBinding.apply {
            var email = ilLoginV2EmailAddress.etInputContent.text.toString()
            var password = ilLoginV2Password.etInputContent.text.toString()
            var isSure = true

            when (email) {
                "98" -> {
                    email = "983577727@qq.com"
                    password = "123456"
                }

                "2" -> {
                    email = "abbidot02@gmail.com"
                    password = "123456"
                }

                "123" -> {
                    email = "123456@qq.com"
                    password = "123456"
                }
            }

            if (TextUtils.isEmpty(email) || !Utils.isValidEmail(email)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilLoginV2EmailAddress.rlEtInputLayout, tvEmailErrorTipLogin
                )
            }
            if (TextUtils.isEmpty(password)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilLoginV2Password.rlEtInputLayout, tvPasswordErrorTipLogin
                )
            }
            if (!isSure) return

            if (isMd5) {
                setButtonEnabled(btnLoginV2Login, ConstantInt.Type0)
                password = Utils.get32Md5Value(password)
            }

            mLoginViewModel.login(this@LoginV2Activity, email, password)
        }
    }

    private fun goForgotPassword() {
        Intent(mContext, ForgotPasswordV2Activity::class.java).apply {
            val email = mViewBinding.ilLoginV2EmailAddress.etInputContent.text.toString()
            putExtra(MMKVKey.Email, email)
            startActivity(this)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                tvLoginV2Signup -> startActivity(
                    Intent(
                        mContext, CreateAccountV2Activity::class.java
                    )
                )

                tvLoginV2ForgotPassword -> goForgotPassword()

                ilLoginV2Password.ivInputRepresentImage -> {
                    isShowPassword = !isShowPassword
                    ViewUtil.instance.showAndHidePasswordClick(
                        ilLoginV2Password.etInputContent,
                        ilLoginV2Password.ivInputRepresentImage,
                        isShowPassword
                    )
                }

                btnLoginV2Login -> loginClick()
                ilLoginV2EmailAddress.etInputContent -> {
                    LogUtil.e("ilLoginV2EmailAddress")
                    v.requestFocus()
                    showInputMethod(v)
                }
            }
        }
    }
}