package com.gh.gamecenter.setting.view.security

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.therouter.TheRouter
import com.gh.gamecenter.common.BuildConfig
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.IDialogUtilsProvider
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.setting.R
import com.gh.gamecenter.setting.databinding.FragmentBindPhoneBinding
import com.lightgame.utils.Utils
import com.therouter.router.Autowired

class BindPhoneFragment : ToolbarFragment() {

    private var mFromLogin = false
    private var mChangePhone = false

    private lateinit var mViewModel: BindPhoneViewModel
    private val mBinding by lazy { FragmentBindPhoneBinding.inflate(layoutInflater) }
    private var mDialog: Dialog? = null

    @Autowired(name = com.therouter.router.KEY_DESCRIPTION)
    var routeSource: String = ""

    override fun handleMessage(msg: Message) {
        if (msg.what == 0) { // 验证码倒计时
            var arg1 = msg.arg1
            arg1--
            if (arg1 >= 0) {
                val message = Message()
                message.what = 0
                message.arg1 = arg1
                mBaseHandler.sendMessageDelayed(message, 1000)
                mBinding.bindPhoneCaptcha.text = arg1.toString() + "s"
            } else {
                mBinding.bindPhoneCaptcha.run {
                    text = "重新获取"
                    setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
                    isEnabled = true
                }
            }
        }
    }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mFromLogin = requireArguments().getBoolean(EntranceConsts.KEY_FROM_LOGIN)
        mChangePhone = requireArguments().getBoolean(EntranceConsts.KEY_CHANGE_PHONE)
        routeSource = requireArguments().getString(com.therouter.router.KEY_DESCRIPTION, "")

        (requireActivity() as? ToolBarActivity)?.hideToolbar(mFromLogin)

        mViewModel = viewModelProvider()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        arrayListOf(
            mBinding.bindPhoneSkip,
            mBinding.bindPhoneCaptcha,
            mBinding.bindPhoneBtn
        ).forEach {
            it.setOnClickListener(this)
        }

        mBinding.bindPhoneSkip.goneIf(!mFromLogin)
        mBinding.bindPhoneTitle.text =
            if (mChangePhone) requireContext().resources.getString(R.string.bind_phone_title2)
            else requireContext().resources.getString(R.string.bind_phone_title1)
        mBinding.bindPhoneDesc.text = if (mChangePhone) {
            val phoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
            "当前手机号：" + phoneNum.substring(0, 3) + "******" + phoneNum.substring(9, 11)
        } else {
            requireContext().resources.getString(R.string.bind_phone_desc)
        }

        // 设置EditText文本输入监听
        setTextChangedListener()

        mViewModel.nextLiveData.observe(viewLifecycleOwner, Observer {
            mBinding.bindPhonePasswordContainer.visibility = View.VISIBLE
            if (BuildConfig.DEBUG || BuildConfig.BUILD_TIME != 0L) {
                if (!SPUtils.getBoolean(Constants.SP_HAS_COMPLETE_INVITE_CODE)) {
                    mBinding.bindPhoneInviteContainer.visibility = View.VISIBLE
                }
            }
            mBinding.bindPhonePassEt.showKeyBoard()
            mBinding.bindPhoneBtn.run {
                alpha = 0.6f
                isEnabled = false
                text = "完成"
            }

            Utils.toast(requireContext(), "验证码短信已发送，请注意查收")
            // 启动验证码倒计时
            val message = Message()
            message.what = 0
            message.arg1 = 60 // 倒数时间

            mBaseHandler.sendMessage(message)
            mBinding.bindPhoneCaptcha.setTextColor(com.gh.gamecenter.common.R.color.hint.toColor(requireContext()))
            mBinding.bindPhoneCaptcha.isEnabled = false
        })

        // 手机号冲突
        mViewModel.phoneBoundLiveData.observe(viewLifecycleOwner, Observer { user ->
            val phoneNum = mBinding.bindPhoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
            var hidePhoneNum = phoneNum
            if (phoneNum.length >= 11) {
                hidePhoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, 11)
            }
            startActivityForResult(
                BindPhoneActivity.getBindPhoneConflictIntent(requireContext(), hidePhoneNum, user),
                0
            )
        })

        mViewModel.finishLiveData.observe(viewLifecycleOwner, Observer { isSuccess ->
            if (isSuccess) {
                // 已完成填写邀请码
                val inviteCode = mBinding.bindPhoneInviteEt.text.toString().trim()
                if (inviteCode.isNotBlank()) {
                    SPUtils.setBoolean(Constants.SP_HAS_COMPLETE_INVITE_CODE, true)
                }

                // 更新本地用户已绑定手机的信息
                val phoneNum: String =
                    mBinding.bindPhoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                UserManager.getInstance().userInfoEntity = UserManager.getInstance().userInfoEntity?.apply {
                    loginMobile = phoneNum
                }

                // 如果当前登录方式是手机号登录，也要更新loginType
                UserManager.getInstance().loginTokenEntity?.apply {
                    if (loginType?.length == 11) loginType = phoneNum
                }

                requireActivity().finish()
            } else {
                mBinding.bindPhoneCaptchaErrorTv.visibility = View.VISIBLE
            }
        })

        mBinding.bindPhoneEt.showKeyBoard()
    }

    private fun setTextChangedListener() {
        // 手机号EditText监听
        mBinding.bindPhoneEt.setTextChangedListener { s, _, _, _ ->
            if (s.isNotEmpty()) {
                mBinding.bindPhoneBtn.isEnabled = true
                mBinding.bindPhoneBtn.alpha = 1f
            } else {
                mBinding.bindPhoneBtn.isEnabled = false
                mBinding.bindPhoneBtn.alpha = 0.4f
            }

            // 输入手机号码加空格
            val stringBuilder = StringBuilder()
            for (i in s.indices) {
                if (i != 3 && i != 8 && s[i] == ' ') {
                    continue
                } else {
                    stringBuilder.append(s[i])
                    if ((stringBuilder.length == 4 || stringBuilder.length == 9)
                        && stringBuilder[stringBuilder.length - 1] != ' '
                    ) {
                        stringBuilder.insert(stringBuilder.length - 1, ' ')
                    }
                }
            }
            if (stringBuilder.toString() != s.toString()) {
                mBinding.bindPhoneEt.setText(stringBuilder.toString())
                mBinding.bindPhoneEt.setSelection(mBinding.bindPhoneEt.text.toString().length)
            }
        }

        // 验证码EditText监听
        mBinding.bindPhonePassEt.setTextChangedListener { s, _, _, _ ->
            if (s.length > 5) {
                mBinding.bindPhoneBtn.isEnabled = true
                mBinding.bindPhoneBtn.alpha = 1f
            } else {
                mBinding.bindPhoneBtn.isEnabled = false
                mBinding.bindPhoneBtn.alpha = 0.4f
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == BindPhoneActivity.RESULT_FINISH_CODE) {
            // 回到"账户与安全"界面
            requireActivity().finish()
        } else {
            // 从手机号冲突界面回到本界面，再次弹出软键盘
            mBinding.bindPhoneEt.showKeyBoard()
        }
    }

    override fun onClick(v: View) {
        super.onClick(v)
        // 防止快速点击
        if (ClickUtils.isFastDoubleClick()) return

        when (v.id) {
            R.id.bind_phone_skip -> {
                showBindPhoneDialog()
            }

            R.id.bind_phone_captcha -> {
                val phoneNum: String =
                    mBinding.bindPhoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                if (mChangePhone) {
                    val oldPhoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
                    mViewModel.reBindPhoneOne(oldPhoneNum, phoneNum, requireContext())
                } else {
                    mViewModel.bindPhoneOne(phoneNum, requireContext())
                }
            }

            R.id.bind_phone_btn -> {
                val oldPhoneNum = UserManager.getInstance().userInfoEntity?.loginMobile ?: ""
                val phoneNum: String =
                    mBinding.bindPhoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                // 更换手机号，当输入手机号和当前手机号相同则弹出提示
                if (mChangePhone && phoneNum == oldPhoneNum) {
                    val dialogUtils = TheRouter.get(IDialogUtilsProvider::class.java)
                    dialogUtils?.showNoticeDialog(requireContext(), "", getString(R.string.change_phone_same)) {
                        mBinding.bindPhoneEt.setText("")
                    }
                    return
                }

                if (mBinding.bindPhoneBtn.text == "下一步") {
                    if (PatternUtils.isPhoneNum(phoneNum) && phoneNum.length == 11) {
                        mBinding.bindPhoneErrorTv.visibility = View.GONE

                        if (mChangePhone) {
                            mViewModel.reBindPhoneOne(oldPhoneNum, phoneNum, requireContext())
                        } else {
                            mViewModel.bindPhoneOne(phoneNum, requireContext())
                        }
                    } else {
                        mBinding.bindPhoneErrorTv.visibility = View.VISIBLE
                        return
                    }
                } else {
                    if (mChangePhone) {
                        mViewModel.reBindPhoneTwo(
                            oldPhoneNum,
                            phoneNum,
                            mBinding.bindPhonePassEt.text.toString().trim(),
                            mBinding.bindPhoneInviteEt.text.toString().trim(),
                            requireContext()
                        )
                    } else {
                        mViewModel.bindPhoneTwo(
                            phoneNum,
                            mBinding.bindPhonePassEt.text.toString().trim(),
                            mBinding.bindPhoneInviteEt.text.toString().trim(),
                            requireContext()
                        )
                    }
                }
            }
        }
    }

    private fun showBindPhoneDialog() {
        val dialogUtils = TheRouter.get(IDialogUtilsProvider::class.java)
        mDialog = dialogUtils?.showBindPhoneDialog(requireContext()) {
            activity?.finish()
        }
    }

    override fun onStop() {
        super.onStop()
        mDialog = null
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.run {
            bindPhoneEt.post {
                listOf(
                    bindPhoneEt,
                    bindPhonePassEt,
                    bindPhoneInviteEt
                ).forEach {
                    it.setHintTextColor(com.gh.gamecenter.common.R.color.text_instance.toColor(requireContext()))
                    it.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                }
            }

            bindPhoneBtn.run {
                background = com.gh.gamecenter.common.R.drawable.download_button_normal_style.toDrawable(requireContext())
                setTextColor(com.gh.gamecenter.common.R.color.text_white.toColor(requireContext()))
            }

            if (mDialog != null && mDialog!!.isShowing) {
                mDialog?.dismiss()
                showBindPhoneDialog()
            }
        }
    }

    override fun onParentActivityFinish() {
        super.onParentActivityFinish()

        // 尝试回调登录拦截器的登录成功回调
        if (mFromLogin && !TextUtils.isEmpty(routeSource)) {
            if (routeSource == RouteConsts.Action.LOGIN_SUCCESS_ACTION) {
                TheRouter.build(RouteConsts.Action.LOGIN_SUCCESS_ACTION).action()
            } else {
                TheRouter.build(routeSource).navigation(this)
            }
        }
    }
}