package com.halo.assistant.fragment.user

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.viewModels
import com.gh.common.util.DirectUtils
import com.gh.common.util.NewLogUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.R
import com.gh.gamecenter.ShellActivity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.FragmentRealNameBinding
import org.json.JSONObject

class RealNameInfoFragment : ToolbarFragment() {

    private var mHasBackdoor: Boolean = false // 是否留有不实名完成也自动开始下载的后门
    private var mIsForcedToCertificate: Boolean = false
    private val mViewModel: RealNameInfoViewModel by viewModels()
    private var mProgressDialog: Dialog? = null
    private var mGameId = "" // 游戏id，下载游戏->弹窗实名提示->前往实名认证->传递游戏id

    private val mBinding: FragmentRealNameBinding by lazy {
        FragmentRealNameBinding.inflate(
            layoutInflater
        )
    }

    override fun getLayoutId(): Int = 0
    override fun getInflatedLayout(): View = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().updateStatusBarColor(R.color.background_white, R.color.background_white)
        mIsForcedToCertificate =
            arguments?.getBoolean(EntranceConsts.KEY_IS_FORCED_TO_CERTIFICATE) ?: false
        mHasBackdoor =
            arguments?.getBoolean(EntranceConsts.KEY_IS_FORCED_TO_CERTIFICATE_BUT_WITH_BACKDOOR)
                ?: false
        mGameId = arguments?.getString(EntranceConsts.KEY_GAME_ID) ?: ""

        mBinding.toolbar.normalTitle.text = "实名认证"
        mBinding.toolbar.normalToolbar.setNavigationOnClickListener { requireActivity().finish() }

        if (mIsForcedToCertificate || !isRealNameInfoExist()) {
            initEditingView()
            mViewModel.certificateResultLiveData.observeNonNull(viewLifecycleOwner) { status ->
                if (status == RealNameInfoViewModel.RESULT_SUCCESS) {
                    requireActivity().setResult(
                        Activity.RESULT_OK,
                        Intent().putExtra(UserInfoEditFragment.AUTH_SUCCESS, true)
                    )
                    requireActivity().finish()
                } else if (status == RealNameInfoViewModel.RESULT_PROGRESSING) {
                    DialogHelper.showDialog(requireContext(),
                        title = "提示",
                        content = "系统繁忙，请稍后再试",
                        confirmText = "前往人工审核",
                        cancelText = "确定",
                        confirmClickCallback = {
                            startActivity(
                                ShellActivity.getIntent(
                                    requireContext(),
                                    ShellActivity.Type.MANUALLY_REAL_NAME,
                                    Bundle().apply {
                                        putString(EntranceConsts.KEY_NAME, mBinding.nameEt.text.toString())
                                        putString(EntranceConsts.KEY_ID, mBinding.idCardEt.text.toString())
                                    }
                                )
                            )
                            requireActivity().finish()
                        },
                        uiModificationCallback = {
                            it.titleTv.gravity = Gravity.CENTER
                            it.contentTv.gravity = Gravity.CENTER
                        }
                    )
                }
                mProgressDialog?.dismiss()
            }
        } else {
            initDisplayOnlyView()
        }
    }

    override fun onParentActivityFinish() {
        super.onParentActivityFinish()
        if (mHasBackdoor) {
            DownloadManager.getInstance().resumeAllInvisiblePendingTask()
        }
    }

    private fun isRealNameInfoExist(): Boolean {
        val userInfoEntity = mViewModel.getUserInfo()
        return if (userInfoEntity != null) {
            val idCard = userInfoEntity.idCard
            if (idCard != null && !TextUtils.isEmpty(idCard.name)) {
                true
            } else {
                NewLogUtils.logCertificationTriggerType(mIsForcedToCertificate)
                false
            }
        } else {
            NewLogUtils.logCertificationTriggerType(mIsForcedToCertificate)
            false
        }
    }

    private fun initEditingView() {
        val bodyString =
            "为响应《国家新闻出版署关于防止未成年沉迷网络游戏的通知》，请认真填写您的身份信息。您提供的证件信息将受到严格保护，仅用于用户实名制认证，不会用作其他用途，请放心填写。前往了解更多信息>>"
        mBinding.bodyTv.text =
            SpanBuilder(bodyString)
                .click(
                    requireContext(),
                    bodyString.length - "前往了解更多信息>>".length,
                    bodyString.length,
                    R.color.theme_font
                ) {
                    DirectUtils.directToWebView(
                        requireContext(),
                        "https://resource.ghzs.com/page/privacy_policies/Identity_information.html",
                        "(实名认证)"
                    )
                }
                .build()
        mBinding.bodyTv.movementMethod = CustomLinkMovementMethod.getInstance()

        val hintString = "特别说明：由于部分用户之前的实名信息不正确或认证失败，可能需要重新认证，请提交真实的信息进行认证即可。部分游戏仅对成年用户进行开放"
        mBinding.hintTv.text =
            SpanBuilder(hintString)
                .bold(0, 5)
                .build()

        val manualHintString = "若您提交的真实身份信息未通过认证或者您持有的为港澳台\\国外身份证件，可转交人工审核"
        mBinding.manualHintTv.text =
            SpanBuilder(manualHintString)
                .click(
                    requireContext(),
                    manualHintString.length - "人工审核".length,
                    manualHintString.length,
                    isUnderlineText = true,
                    colorRes = R.color.theme_font
                ) {
                    startActivity(
                        ShellActivity.getIntent(
                            requireContext(),
                            ShellActivity.Type.MANUALLY_REAL_NAME,
                            Bundle().apply {
                                putString(EntranceConsts.KEY_NAME, mBinding.nameEt.text.toString())
                                putString(EntranceConsts.KEY_ID, mBinding.idCardEt.text.toString())
                            }
                        )
                    )
                    requireActivity().finish()
                }
                .build()
        mBinding.manualHintTv.movementMethod = CustomLinkMovementMethod.getInstance()

        mBinding.idCardEt.filters = arrayOf(TextHelper.getFilter(18, "身份证号码最长18位"))

        mBinding.nameEt.doOnTextChanged { _, _, _, _ ->
            updateSubmitBtn()
        }
        mBinding.idCardEt.doOnTextChanged { _, _, _, _ ->
            updateSubmitBtn()
        }
        mBinding.contactTv.visibility = View.VISIBLE
        mBinding.contactTv.enlargeTouchArea()
        mBinding.contactTv.setOnClickListener {
            DirectUtils.directToQqConversation(it.context, CONTACT_QQ)
        }

        // 适配小屏幕 or 大文字手机
        if (isScreenUnableToShowAllTheContent()) {
            changeToCompatView()
        }
    }

    private fun initDisplayOnlyView() {
        val userInfoEntity = mViewModel.getUserInfo()

        mBinding.badgeContainer.visibility = View.VISIBLE
        mBinding.run {
            ConstraintSet().run {
                clone(infoContainer)
                clear(R.id.nameTv, ConstraintSet.TOP)
                connect(
                    R.id.nameTv,
                    ConstraintSet.TOP,
                    R.id.badgeContainer,
                    ConstraintSet.BOTTOM,
                    14F.dip2px()
                )
                applyTo(infoContainer)
            }
        }
        mBinding.submitBtn.visibility = View.GONE
        mBinding.reEditInfoBtn.visibleIf(userInfoEntity?.idCard?.revise == false)
        mBinding.nameEt.inputType = InputType.TYPE_NULL
        mBinding.idCardEt.inputType = InputType.TYPE_NULL

        val idCard = userInfoEntity?.idCard
        val sb = StringBuilder(idCard?.name?.substring(0, 1) ?: "")
        for (i in 0 until idCard?.name!!.length - 1) {
            sb.append("*")
        }
        mBinding.nameEt.setText(sb.toString())
        mBinding.idCardEt.setText(
            idCard.id?.replace(
                "(\\d)\\d{16}([0-9,X-Y])".toRegex(),
                "$1****************$2"
            )
        )

        mBinding.reEditInfoBtn.setOnClickListener {
            startActivity(
                ShellActivity.getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO).apply {
                    putExtra(EntranceConsts.KEY_IS_FORCED_TO_CERTIFICATE, true)
                }
            )
            requireActivity().finish()
        }
    }

    private fun updateSubmitBtn() {
        val validationPair =
            isInputValid(mBinding.nameEt.text.toString(), mBinding.idCardEt.text.toString())

        mBinding.submitBtn.isEnabled = validationPair.first
        if (validationPair.first) {
            mBinding.submitBtn.alpha = 1F
            mBinding.submitBtn.setOnClickListener {
                val o = JSONObject()
                o.put("id", mBinding.idCardEt.text.toString())
                o.put("name", mBinding.nameEt.text.toString())
                mViewModel.postCertification(o.toString(), mGameId, mIsForcedToCertificate)
                mProgressDialog = DialogHelper.getProgressDialog(requireContext(), "提交中")
                    .apply {
                        show()
                    }
            }
        } else {
            mBinding.submitBtn.alpha = 0.4F
        }
        mBinding.errorHintTv.text = validationPair.second
    }

    private fun isInputValid(name: String, idCard: String): Pair<Boolean, String> {
        if (TextUtils.isEmpty(name)) {
            return Pair(false, "请输入姓名")
        }
        if (TextUtils.isEmpty(idCard)) {
            return Pair(false, "请输入身份证号码")
        }
        if (idCard.length < 18) {
            return Pair(false, "必须使用18位的身份证号码")
        }
        return Pair(true, "")
    }

    /**
     * 屏幕高度小于等于 1080 (16:9) 的设备看作无法显示完整内容
     */
    private fun isScreenUnableToShowAllTheContent(): Boolean {
        return DisplayUtils.getScreenHeight() <= 1920
    }

    private fun changeToCompatView() {
        mBinding.bodyTv.setLineSpacing(0F, 1F)
        mBinding.hintTv.setLineSpacing(0F, 1F)
        mBinding.manualHintTv.setLineSpacing(0F, 1F)

        // 把空隙缩窄
        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.nameTv, ConstraintSet.TOP)
            connect(
                R.id.nameTv,
                ConstraintSet.TOP,
                R.id.hintTv,
                ConstraintSet.BOTTOM,
                4F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)

        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.idCardTv, ConstraintSet.TOP)
            connect(
                R.id.idCardTv,
                ConstraintSet.TOP,
                R.id.nameEt,
                ConstraintSet.BOTTOM,
                4F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)

        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.nameEt, ConstraintSet.TOP)
            connect(
                R.id.nameEt,
                ConstraintSet.TOP,
                R.id.nameTv,
                ConstraintSet.BOTTOM,
                4F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)

        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.idCardEt, ConstraintSet.TOP)
            connect(
                R.id.idCardEt,
                ConstraintSet.TOP,
                R.id.idCardTv,
                ConstraintSet.BOTTOM,
                4F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)

        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.hintTv, ConstraintSet.TOP)
            connect(
                R.id.hintTv,
                ConstraintSet.TOP,
                R.id.bodyTv,
                ConstraintSet.BOTTOM,
                4F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)

        // 把按钮上移
        ConstraintSet().apply {
            clone(mBinding.infoContainer)
            clear(R.id.submitBtn, ConstraintSet.TOP)
            connect(
                R.id.submitBtn,
                ConstraintSet.TOP,
                R.id.idCardEt,
                ConstraintSet.BOTTOM,
                24F.dip2px()
            )
        }.applyTo(mBinding.infoContainer)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        requireActivity().updateStatusBarColor(R.color.background_white, R.color.background_white)
        mBinding.toolbar.run {
            normalToolbar.setBackgroundColor(R.color.background_white.toColor(requireContext()))
            backBtn.setImageResource(R.drawable.ic_bar_back)
            normalTitle.setTextColor(R.color.text_title.toColor(requireContext()))
        }
    }

    companion object {
        const val CONTACT_QQ = "800177318"
    }

}