package com.gh.gamecenter.fragment

import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.RelativeLayout
import com.gh.common.util.DirectUtils
import com.gh.common.util.LogUtils
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.common.view.WrapContentDraweeView
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.DialogWelcomeBinding
import com.gh.gamecenter.feature.entity.WelcomeDialogEntity
import com.halo.assistant.HaloApp

class WelcomeDialogFragment : BaseDialogFragment() {

    private var mWelcomeEntity: WelcomeDialogEntity? = null

    private lateinit var mBinding: DialogWelcomeBinding

    private var mDismissListener: (() -> Unit)? = null

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

        mWelcomeEntity = arguments?.getParcelable(TAG)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // the content
        val root = RelativeLayout(activity)
        root.layoutParams =
            ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

        // creating the fullscreen dialog
        val dialog = Dialog(requireActivity())
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(root)
        dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        return dialog
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = DialogWelcomeBinding.inflate(inflater, container, false)

        mBinding.ivOpeningCover.setOnClickListener {
            HaloApp.put(Constants.WELCOME_DIALOG_ID, mWelcomeEntity?.id)
            HaloApp.put(Constants.WELCOME_DIALOG_LINK_TITLE, mWelcomeEntity?.text)
            LogUtils.uploadWelcomeDialog(
                "click",
                mWelcomeEntity?.id,
                mWelcomeEntity?.id,
                mWelcomeEntity?.type,
                mWelcomeEntity?.text
            )
            SensorsBridge.trackEvent("HomeDialogClick")

            mWelcomeEntity?.let {
                DirectUtils.directToLinkPage(requireContext(), it, EntranceConsts.ENTRANCE_WELCOME, "", "首页弹窗")
            }

            dismissAllowingStateLoss()
        }

        mBinding.ivOpeningCover.setFixedWidth(300)
        mBinding.ivOpeningCover.registerLoadingCallback(object : WrapContentDraweeView.LoadingCallback {
            override fun loaded() {
                mBinding.root.post {
                    if (mBinding.ivOpeningCover.measuredHeight > mBinding.root.resources.displayMetrics.heightPixels * .8) {
                        mBinding.ivCloseBackup.visibility = View.VISIBLE
                    } else {
                        mBinding.ivClose.visibility = View.VISIBLE
                    }
                }

                mBinding.ivOpeningCover.registerLoadingCallback(null)
            }
        })

        mBinding.ivCloseBackup.setOnClickListener {
            dismissAllowingStateLoss()
        }
        mBinding.ivClose.setOnClickListener { mBinding.ivCloseBackup.performClick() }
        ImageUtils.displayWithoutMemoryCache(mBinding.ivOpeningCover, mWelcomeEntity?.icon)

        return mBinding.root
    }

    override fun dismissAllowingStateLoss() {
        tryWithDefaultCatch {
            super.dismissAllowingStateLoss()
        }
    }

    override fun dismiss() {
        tryWithDefaultCatch {
            super.dismiss()
        }
    }

    fun setOnDismissListener(dismissListener: () -> Unit) {
        mDismissListener = dismissListener
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)

        // 首页弹窗记录 id
        val sp = PreferenceManager.getDefaultSharedPreferences(context?.applicationContext)

        SPUtils.setString(sp, Constants.SP_LAST_OPENING_ID, mWelcomeEntity?.id)
        SPUtils.setLong(sp, Constants.SP_LAST_OPENING_TIME, mWelcomeEntity?.time ?: 0L)

        mDismissListener?.invoke()
        LogUtils.uploadWelcomeDialog(
            "close",
            mWelcomeEntity?.id,
            mWelcomeEntity?.id,
            mWelcomeEntity?.type,
            mWelcomeEntity?.text
        )
    }

    companion object {
        const val TAG = "welcome_dialog"

        @JvmStatic
        fun getInstance(welcomeEntity: WelcomeDialogEntity?) = WelcomeDialogFragment().apply {
            arguments = Bundle()
            arguments?.putParcelable(TAG, welcomeEntity)
            LogUtils.uploadWelcomeDialog(
                "show",
                welcomeEntity?.id,
                welcomeEntity?.id,
                welcomeEntity?.type,
                welcomeEntity?.text
            )

            SensorsBridge.trackEvent("HomeDialogShow")
        }
    }

}