package com.abbidot.tracker.ui.fragment.account

import android.content.Context
import android.content.Intent
import android.text.InputType
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.fragment.app.viewModels
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.network.exception.ErrorCode
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.base.BaseFragment
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.FragmentCreateAccountV2OneBinding
import com.abbidot.tracker.ui.activity.account.CreateAccountV2Activity
import com.abbidot.tracker.ui.activity.account.LoginV2Activity
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.UserProfileViewModel

/**
 *Created  by .yzq on 2024/8/2/002.
 * @link
 * @description:
 */
class CreateAccountV2OneFragment : BaseFragment<FragmentCreateAccountV2OneBinding>(
    FragmentCreateAccountV2OneBinding::inflate
) {
    private val mRegisterViewModel: UserProfileViewModel by viewModels()
    private lateinit var mCreateAccountV2Activity: CreateAccountV2Activity

    companion object {
        @JvmStatic
        fun newInstance(context: Context) = CreateAccountV2OneFragment().apply {
            mContext = context
        }
    }

    override fun initData() {
        super.initData()
        mCreateAccountV2Activity = activity as CreateAccountV2Activity
        mViewBinding.apply {
            ilCreateAccountV2Email.let {
                it.tvInputNameTitle.setText(R.string.txt_email_address)
                it.etInputContent.setHint(R.string.login_txt_email)
                it.etInputContent.setText(mCreateAccountV2Activity.mUserEmail)
                it.etInputContent.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext!!,
                    it.rlEtInputLayout,
                    tvEmailErrorTipCreateAccountV2,
                    it.etInputContent
                ) { s ->
                    s.let { str ->
                        val hasUpperCase = str.any { c ->
                            c.isUpperCase()
                        }
                        if (hasUpperCase) {
                            it.etInputContent.setText(str.lowercase())
                            it.etInputContent.setSelection(str.length)
                        }
                    }
                }
            }

            val privacyAndTerms = getString(R.string.txt_read_and_accept)
            setSpannableClick(
                ilCreateAccountV2PolicyTermsCheck.tvLoginAgreePrivacyContent,
                privacyAndTerms.substringBeforeLast("Te"),
                privacyAndTerms.substringAfterLast("&")
            )

            setOnClickListenerViews(btnCreateAccountV2Continue)
        }
    }

    private fun setSpannableClick(textView: TextView, str1: String, str2: String) {
        try {
            textView.apply {
                val span1 = SpannableString(str1)
                span1.setSpan(object : ClickableSpan() {
                    override fun onClick(v: View) {
                        ViewUtil.instance.goPrivacyPolicy(mCreateAccountV2Activity)
                    }
                }, 7, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                val span2 = SpannableString(str2)
                span2.setSpan(object : ClickableSpan() {
                    override fun onClick(v: View) {
                        ViewUtil.instance.goServiceContract(mCreateAccountV2Activity)
                    }
                }, 1, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

                val spannableStringBuilder = SpannableStringBuilder()
                spannableStringBuilder.append(span1)
                spannableStringBuilder.append(span2)
                text = spannableStringBuilder
                movementMethod = LinkMovementMethod.getInstance()
            }
        } catch (e: Exception) {
            LogUtil.e("解析同意隐私政策错误${e.message}")
        }
    }

    override fun liveDataObserve() {
        mRegisterViewModel.mGetEmailCodeLiveData.observe(viewLifecycleOwner) {
            mViewBinding.btnCreateAccountV2Continue.isEnabled = true
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        mCreateAccountV2Activity.switchFragment(1)
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    exceptionCode?.let { code ->
                        if (code == ErrorCode.USER_HAS_EXIST.toString()) {
                            ViewUtil.instance.showDialog(
                                mContext!!,
                                R.string.txt_account_exists_log_in,
                                object : BaseDialog.OnDialogOkListener {
                                    override fun onOkClick(dialog: BaseDialog<*>) {
                                        dialog.dismiss()
                                        val intent = Intent(mContext, LoginV2Activity::class.java)
                                        val email =
                                            mViewBinding.ilCreateAccountV2Email.etInputContent.text.toString()
                                        intent.putExtra(MMKVKey.Email, email)
                                        startActivityFinish(mActivity!!, intent)
                                    }
                                },
                                okTextResId = R.string.txt_sure
                            )
                        }
                    }
                }
            })
            mCreateAccountV2Activity.isInterceptNetErrorCodeTip = false
        }
    }

    private fun continueClick() {
        mViewBinding.apply {
            val email = ilCreateAccountV2Email.etInputContent.text.toString()
            if (TextUtils.isEmpty(email) || !Utils.isValidEmail(email)) {
                ViewUtil.instance.setInputViewErrorShow(
                    mContext!!,
                    ilCreateAccountV2Email.rlEtInputLayout,
                    tvEmailErrorTipCreateAccountV2
                )
                return
            }

            if (!ilCreateAccountV2PolicyTermsCheck.cbLoginAgreePrivacyCheckbox.isChecked) {
                showToast(R.string.register_txt_agree, gravity = Gravity.CENTER)
                return
            }

            mCreateAccountV2Activity.setToEmail(email)

            btnCreateAccountV2Continue.isEnabled = false
            mCreateAccountV2Activity.isInterceptNetErrorCodeTip = true
            mCreateAccountV2Activity.hideInputMethod(root)
            mRegisterViewModel.getEmailCode(mCreateAccountV2Activity, email, 1)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnCreateAccountV2Continue -> {
                    continueClick()
                }
            }
        }
    }
}