package com.adealink.weparty.account.login

import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.text.buildSpannedString
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.AppBase
import com.adealink.frame.base.Rlt
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.ext.safeSetSpan
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.DisplayUtil
import com.adealink.frame.util.copyToClipBoard
import com.adealink.frame.util.onClick
import com.adealink.weparty.App
import com.adealink.weparty.account.R
import com.adealink.weparty.account.constant.AccountLoginAuthCancelError
import com.adealink.weparty.account.databinding.DialogLoginBinding
import com.adealink.weparty.account.login.data.ThirdType
import com.adealink.weparty.account.login.viewmodel.LoginViewModel
import com.adealink.weparty.account.viewModel.AccountViewModelFactory
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.dialogfragment.BaseDialogFragment
import com.adealink.weparty.commonui.drawabletoolbox.DrawableBuilder
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.setContinueClicksListener
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.ColorClickSpan
import com.adealink.weparty.debug.Debug
import com.adealink.weparty.module.account.Account
import com.adealink.weparty.module.webview.Web
import com.adealink.weparty.url.UrlConfig
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.adealink.weparty.util.applyImmersive
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Account.LoginDialog.PATH], desc = "登录页面")
class LoginDialog : BaseDialogFragment(R.layout.dialog_login) {

    private val binding by viewBinding(DialogLoginBinding::bind)
    private val loginViewModel by activityViewModels<LoginViewModel> { AccountViewModelFactory() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, APP_R.style.FullScreenDialogTheme)
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        activity?.let { act ->
            QMUIStatusBarHelper.setStatusBarLightMode(act)
            act.applyImmersive { top ->
                binding.btnClose.updateLayoutParams<ConstraintLayout.LayoutParams> {
                    topMargin = top + 12.dp()
                }
            }
            binding.userAgreementTv.updateLayoutParams<ConstraintLayout.LayoutParams> {
                bottomMargin = 36.dp()
            }
        }

        binding.btnClose.onClick {
            dismiss()
        }
        binding.appIconIv.setContinueClicksListener() {
            copyDeviceId()
        }

        binding.phoneLoginBtn.onClick {
            activity?.let { act ->
                Router.build(act, Account.Phone.LOGIN).start()
            }
        }
        binding.googleLoginBtn.onClick(wait = 1000) {
            login(ThirdType.GOOGLE)
        }
        initUserAgreement()
        initTestLogin()
    }

    override fun onStart() {
        super.onStart()
        resetDialogAttributes()
    }

    private fun resetDialogAttributes() {
        val dialog = dialog ?: return
        val window = dialog.window ?: return
        window.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val attr = window.attributes
        attr.gravity = Gravity.CENTER
        attr.dimAmount = 0f
        window.attributes = attr
    }

    private fun initTestLogin() {
        val googleBtnBg = DrawableBuilder()
            .rectangle()
            .solidColor(getCompatColor(APP_R.color.white))
            .cornerRadius(DisplayUtil.dp2px(27f))
            .build()
        binding.testLoginBtn.background = googleBtnBg
        binding.testLoginBtn.visibility = when (AppBase.isRelease) {
            true -> View.GONE
            else -> View.VISIBLE
        }
        binding.testLoginBtn.onClick {
            showLoading()
            loginViewModel.testAuthLogin()
        }
        if (AppBase.isRelease) {
            binding.tvDebug.visibility = View.GONE
        } else {
            binding.tvDebug.visibility = View.VISIBLE
            activity?.let { act ->
                binding.tvDebug.onClick {
                    Router.build(act, Debug.Debug.PATH).start()
                }
            }
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        loginViewModel.countdownTime.observeWithoutCache(this) { time ->
            dismissLoading()
        }
        loginViewModel.loginLD.observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            val authType = rlt.authType
            when (val result = rlt.result) {
                is Rlt.Success -> {
                    (activity as? BaseLoginActivity)?.handleLoginSuccess(
                        result.data,
                        authType,
                    )
                }

                is Rlt.Failed -> {
                    when (result.error) {
                        //取消授权
                        is AccountLoginAuthCancelError -> {
                            return@observe
                        }
                    }
                    showToast(result)
                }
            }
        }
    }

    private fun login(authType: ThirdType) {
        showLoading()
        activity?.let { act ->
            loginViewModel.startAuthLogin(authType, act)
        }
    }

    override fun showLoading() {
        (activity as? BaseActivity)?.showLoading()
    }

    override fun dismissLoading() {
        (activity as? BaseActivity)?.dismissLoading()
    }

    private fun initUserAgreement() {
        binding.userAgreementTv.movementMethod = LinkMovementMethod.getInstance()
        val serviceTerms = getCompatString(R.string.account_service_terms)
        val privacyPolicyStr = getCompatString(R.string.account_privacy_policy)
        val agreementString =
            getCompatString(R.string.account_user_agreement_tips_new)

        val agreementBuilder = buildSpannedString {
            append(agreementString)
            append(
                buildSpannedString {
                    append(serviceTerms).apply {
                        safeSetSpan(
                            StyleSpan(Typeface.BOLD),
                            0,
                            serviceTerms.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                        safeSetSpan(
                            object : ColorClickSpan(APP_R.color.white) {
                                override fun onClick(widget: View) {
                                    activity?.let { act ->
                                        Router.build(act, Web.FullScreen.PATH)
                                            .putExtra(
                                                Web.Common.EXTRA_URL,
                                                UrlConfig.serviceTerms
                                            )
                                            .putExtra(Web.Common.EXTRA_SHOW_TOPBAR, true)
                                            .start()
                                    }
                                }
                            },
                            0,
                            serviceTerms.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                        safeSetSpan(
                            UnderlineSpan(),
                            0,
                            serviceTerms.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                    }
                }
            )
            append(",")
            append(
                buildSpannedString {
                    append(privacyPolicyStr).apply {
                        safeSetSpan(
                            StyleSpan(Typeface.BOLD),
                            0,
                            privacyPolicyStr.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                        safeSetSpan(
                            object : ColorClickSpan(APP_R.color.white) {
                                override fun onClick(widget: View) {
                                    super.onClick(widget)
                                    activity?.let { act ->
                                        Router.build(act, Web.FullScreen.PATH)
                                            .putExtra(
                                                Web.Common.EXTRA_URL,
                                                UrlConfig.privacyPolicy
                                            )
                                            .putExtra(Web.Common.EXTRA_SHOW_TOPBAR, true)
                                            .start()
                                    }
                                }
                            },
                            0,
                            privacyPolicyStr.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                        safeSetSpan(
                            UnderlineSpan(),
                            0,
                            privacyPolicyStr.length,
                            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                        )
                    }
                }
            )
        }

        binding.userAgreementTv.text = agreementBuilder
    }

    private fun copyDeviceId() {
        copyDeviceIdToClipBoard()
        showToast(R.string.account_copy_device_id_success)
    }

    private fun copyDeviceIdToClipBoard() {
        CoroutineScope(Dispatcher.UI).launch {
            var deviceId = App.instance.deviceIdService.getMemOldDeviceId()
            if (deviceId.isEmpty()) {
                deviceId = App.instance.deviceIdService.getOldDeviceId()
            }
            copyToClipBoard(deviceId, deviceId)
        }
    }
}