package com.gh.gamecenter.fragment

import android.os.Bundle
import android.preference.PreferenceManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.entity.CommunityEntity
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.view.WrapContentDraweeView
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.TimeElapsedHelper
import com.gh.gamecenter.databinding.DialogWelcomeBinding
import com.gh.gamecenter.entity.WelcomeDialogEntity
import com.halo.assistant.HaloApp

class WelcomeDialogFragment : BaseDialogFragment() {

    private var mWelcomeEntity: WelcomeDialogEntity? = null
    private var mTimeHelper: TimeElapsedHelper? = null

    private var mDismissByClickImage = false

    lateinit var binding: DialogWelcomeBinding

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mWelcomeEntity = arguments?.getParcelable(TAG)
        mTimeHelper = TimeElapsedHelper(this)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = DialogWelcomeBinding.inflate(inflater, container, false)
        binding.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")

            when (mWelcomeEntity?.type) {
                EntranceConsts.HOST_ARTICLE -> {
                    DirectUtils.directToArticle(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_GAME -> {
                    DirectUtils.directToGameDetail(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_COLUMN -> {
                    DirectUtils.directToSubject(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        null,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_QUESTION -> {
                    DirectUtils.directToQuestionDetail(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_ANSWER -> {
                    DirectUtils.directToAnswerDetail(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_WEB -> {
                    DirectUtils.directToWebView(
                        requireContext(),
                        mWelcomeEntity?.link!!,
                        EntranceConsts.ENTRANCE_WELCOME
                    )
                }
                EntranceConsts.HOST_QQ -> {
                    DirectUtils.directToQqConversation(requireContext(), mWelcomeEntity?.link!!)
                }
                EntranceConsts.HOST_COMMUNITY -> {
                    DirectUtils.directToCommunity(
                        requireContext(),
                        CommunityEntity(mWelcomeEntity?.link!!, mWelcomeEntity?.text!!)
                    )
                }
//                else -> DialogUtils.showLowVersionDialog(context)
                else -> DirectUtils.directToLinkPage(
                    requireContext(), mWelcomeEntity
                        ?: WelcomeDialogEntity(), EntranceConsts.ENTRANCE_WELCOME, ""
                )
            }

            mDismissByClickImage = true

            dismissAllowingStateLoss()
        }

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

        binding.ivCloseBackup.setOnClickListener {
            dismissAllowingStateLoss()
        }
        binding.ivClose.setOnClickListener {
            dismissAllowingStateLoss()
        }
        ImageUtils.displayWithoutMemoryCache(binding.ivOpeningCover, mWelcomeEntity?.icon)
        return binding.root
    }

    override fun dismissAllowingStateLoss() {
        try {
            mDismissByClickImage = false
            super.dismissAllowingStateLoss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun dismiss() {
        try {
            mDismissByClickImage = false
            super.dismiss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

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

    override fun onDestroy() {
        val type = if (mDismissByClickImage) "点击图片" else "点击关闭"

        MtaHelper.onEventWithTime("启动弹窗", mTimeHelper?.elapsedTime!!, type, "No parameter.")

        PreferenceManager.getDefaultSharedPreferences(context?.applicationContext).edit().apply {
            putString(Constants.SP_LAST_OPENING_ID, mWelcomeEntity?.id)
            putLong(Constants.SP_LAST_OPENING_TIME, mWelcomeEntity?.time!!)
        }.apply()

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

    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")
        }
    }

}