package com.gh.common.dialog

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.ScrollingMovementMethod
import android.text.style.ClickableSpan
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.fromHtml
import com.gh.gamecenter.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.DialogPrivacyProtocolBinding
import com.gh.gamecenter.entity.DialogEntity
import com.lightgame.utils.AppManager

class PrivacyPolicyDialogFragment : BaseDialogFragment() {

    private var mCallBack: ((isSuccess: Boolean) -> Unit)? = null
    private val mBinding by lazy { DialogPrivacyProtocolBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {
            dismiss()
            return
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return mBinding.root
    }

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

        mBinding.contentTv.movementMethod = ScrollingMovementMethod()

        val privacyPolicyEntity = arguments?.get(KEY_DATA) as? DialogEntity.PrivacyPolicyEntity
        if (privacyPolicyEntity == null) {
            showPreLaunchStyle()
        } else {
            showUpdatedStyle(privacyPolicyEntity)
        }
    }

    private fun showUpdatedStyle(privacyPolicyEntity: DialogEntity.PrivacyPolicyEntity) {
        mBinding.titleIv.visibility = View.VISIBLE
        mBinding.privacyTitleTv.text = "光环助手《隐私协议》更新"
        mBinding.contentTv.text = privacyPolicyEntity.content.fromHtml()

        val skipText = SpannableStringBuilder("查看隐私政策详情")
        skipText.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.text_theme)
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                val intent =
                    WebActivity.getIntent(requireContext(), context!!.getString(com.gh.gamecenter.common.R.string.privacy_policy_url), true)
                context?.startActivity(intent)
            }
        }, skipText.length - 6, skipText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        mBinding.descTv.movementMethod = CustomLinkMovementMethod()
        mBinding.descTv.text = skipText

        if (privacyPolicyEntity.alertType == "INFORM") {
            mBinding.refuseTv.visibility = View.GONE
            mBinding.agreeTv.text = "我知道了"
            mBinding.agreeTv.setOnClickListener {
                SPUtils.setString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, privacyPolicyEntity.id)
                mCallBack?.invoke(true)
                dismissAllowingStateLoss()
            }
        } else {
            mBinding.refuseTv.text = "不同意退出"
            mBinding.agreeTv.text = "同意"
            mBinding.refuseTv.setOnClickListener {
                dismissAllowingStateLoss()
                AppManager.getInstance().finishAllActivity()
            }
            mBinding.agreeTv.setOnClickListener {
                SPUtils.setString(Constants.SP_LAST_ACCEPTED_PRIVACY_DIALOG_ID, privacyPolicyEntity.id)
                mCallBack?.invoke(true)
                dismissAllowingStateLoss()
            }
        }
    }

    private fun showPreLaunchStyle() {
        val skipText = SpannableStringBuilder("查看完整版的隐私政策和用户协议")

        skipText.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.text_theme)
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                val intent =
                    WebActivity.getIntent(requireContext(), context!!.getString(com.gh.gamecenter.common.R.string.privacy_policy_url), true)
                context?.startActivity(intent)
            }
        }, skipText.length - 9, skipText.length - 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        skipText.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.text_theme)
                ds.isUnderlineText = false
            }

            override fun onClick(widget: View) {
                val intent = WebActivity.getIntent(requireContext(), context!!.getString(com.gh.gamecenter.common.R.string.disclaimer_url), true)
                context?.startActivity(intent)
            }
        }, skipText.length - 4, skipText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        mBinding.descTv.movementMethod = CustomLinkMovementMethod()
        mBinding.descTv.text = skipText

        mBinding.refuseTv.setOnClickListener {
            mCallBack?.invoke(false)
            dismissAllowingStateLoss()
        }
        mBinding.agreeTv.setOnClickListener {
            mCallBack?.invoke(true)
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(false)
        createDialog.setOnKeyListener(object : DialogInterface.OnKeyListener {
            override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true
                }
                return false
            }
        })

        val window = createDialog.window
        window?.setGravity(Gravity.CENTER)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = requireContext().resources.displayMetrics.widthPixels - 60F.dip2px()
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {
        const val KEY_DATA = "data"

        @JvmStatic
        fun show(
            activity: FragmentActivity,
            privacyPolicyEntity: DialogEntity.PrivacyPolicyEntity? = null,
            callBack: ((isSuccess: Boolean) -> Unit)?
        ) {
            var privacyDialogFragment =
                activity.supportFragmentManager.findFragmentByTag(PrivacyPolicyDialogFragment::class.java.name) as? PrivacyPolicyDialogFragment
            if (privacyDialogFragment != null) {
                privacyDialogFragment.mCallBack = callBack
                val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
                transaction.show(privacyDialogFragment)
                transaction.commit()
            } else {
                privacyDialogFragment = PrivacyPolicyDialogFragment().apply {
                    mCallBack = callBack
                }
            }
            privacyDialogFragment.arguments = Bundle().apply {
                putParcelable(KEY_DATA, privacyPolicyEntity)
            }
            privacyDialogFragment.show(
                activity.supportFragmentManager,
                PrivacyPolicyDialogFragment::class.java.name
            )
        }
    }
}