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(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        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) ?: ""

        mViewModel.sourceEntrance = arguments?.getString(EntranceConsts.KEY_SOURCE_ENTRANCE) ?: "主动进入"

        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) {
                    startActivity(ShellActivity.getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO))
                }
                mProgressDialog?.dismiss()
            }
        } else {
            initDisplayOnlyView()
        }

        SensorsBridge.trackEvent(
            "VerificationPageShow",
            "source_entrance",
            mViewModel.sourceEntrance
        )
    }

    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 = getText(R.string.realname_body_tv)
        mBinding.bodyTv.text =
            SpanBuilder(bodyString)
                .click(
                    requireContext(),
                    bodyString.length - "前往了解更多信息>>".length,
                    bodyString.length,
                    com.gh.gamecenter.common.R.color.text_theme
                ) {
                    DirectUtils.directToWebView(
                        requireContext(),
                        "https://and-static.ghzs66.com/page/privacy_policies/Identity_information.html",
                        "(实名认证)"
                    )
                }
                .build()
        mBinding.bodyTv.movementMethod = CustomLinkMovementMethod.getInstance()

        val hintString = getText(R.string.realname_hint_tv)
        mBinding.hintTv.text =
            SpanBuilder(hintString)
                .bold(0, 5)
                .build()

        val manualHintString = getText(R.string.realname_manual_hint_tv)
        mBinding.manualHintTv.text =
            SpanBuilder(manualHintString)
                .click(
                    requireContext(),
                    manualHintString.length - "人工审核".length,
                    manualHintString.length,
                    isUnderlineText = true,
                    colorRes = com.gh.gamecenter.common.R.color.text_theme
                ) {
                    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.textDotIndicator.setOnClickListener {
            mBinding.nameEt.text.insert(mBinding.nameEt.selectionStart, "\u00B7")
        }
        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.submitBtn.visibility = View.GONE
        mBinding.reEditInfoBtn.visibleIf(userInfoEntity?.idCard?.revise == false)
        mBinding.nameEt.inputType = InputType.TYPE_NULL
        mBinding.idCardEt.inputType = InputType.TYPE_NULL
        mBinding.nameEt.visibility = View.GONE
        mBinding.textDotIndicator.visibility = View.GONE
        mBinding.idCardEt.visibility = View.GONE
        mBinding.nameTv.visibility = View.GONE
        mBinding.idCardTv.visibility = View.GONE

        val idCard = userInfoEntity?.idCard!!

        if (idCard.status == 1) {
            mBinding.badgeIv.setImageResource(R.drawable.ic_realname_pending_badge)
            mBinding.badgeHintTv.text = getText(R.string.realname_pending_badge_hint)
            mBinding.badgeHintExtraTv.text = getText(R.string.realname_pending_badge_hint_extra)
        } else {
            mBinding.badgeHintTv.text = getText(R.string.realname_success_badge_hint)
            mBinding.badgeIv.setImageResource(R.drawable.ic_realname_success_badge)
            if (idCard.minor == true) {
                mBinding.badgeHintExtraTv.text = getText(R.string.realname_success_badge_hint_extra_underage)
            } else {
                mBinding.badgeHintExtraTv.text = getText(R.string.realname_success_badge_hint_extra_adult)
            }
        }

        mBinding.reEditInfoBtn.setOnClickListener {
            startActivity(
                ShellActivity.getIntent(requireContext(), ShellActivity.Type.REAL_NAME_INFO).apply {
                    putExtra(EntranceConsts.KEY_SOURCE_ENTRANCE, mViewModel.sourceEntrance)
                    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 || DisplayUtils.isUltraShortScreen(activity)
    }

    /**
     * 使用更紧凑的布局，避免一些内容不能显示，导致不能用
     */
    private fun changeToCompatView() {
        mBinding.infoContainer.setPadding(20F.dip2px(), 0, 20F.dip2px(), 0)
        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(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        mBinding.toolbar.run {
            normalToolbar.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            backBtn.setImageResource(com.gh.gamecenter.common.R.drawable.ic_bar_back)
            normalTitle.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
        }
    }

    companion object {
        const val CONTACT_QQ = "800177318"
    }

}