package com.gh.gamecenter.gamedetail.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.WebActivity
import com.gh.gamecenter.common.base.fragment.BaseDraggableDialogFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.databinding.DialogGameDetailMoreBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.GameDetailViewModel

class GameDetailMoreDialog : BaseDraggableDialogFragment() {

    private lateinit var binding: DialogGameDetailMoreBinding
    private var mShortId = ""

    private var mGameEntity: GameEntity? = null
    private var mShowConcernIcon = false
    private var mIsConcerned = false
    private val mViewModel: GameDetailViewModel by lazy { viewModelProviderFromParent() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireArguments().run {
            mGameEntity = getParcelable(KEY_GAME)
            mShortId = getString(KEY_SHORT_ID) ?: ""
            mShowConcernIcon = getBoolean(KEY_SHOW_CONCERN_ICON)
            mIsConcerned = getBoolean(KEY_IS_CONCERNED)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DialogGameDetailMoreBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mGameEntity?.let {
            binding.gameIconView.displayGameIcon(it)
            binding.gameNameTv.text = it.name
        }

        updateConcernView()
        mViewModel.concernLiveData.observeNonNull(this) { response ->
            mIsConcerned = response.isConcern
            updateConcernView()
        }

        binding.shareWechatTv.setOnClickListener {
            getShareUtils().wechatShare()
            MtaHelper.onEvent("内容分享", "微信好友", mGameEntity?.name)
        }
        binding.sharePyquanTv.setOnClickListener {
            getShareUtils().wechatMomentsShare()
            MtaHelper.onEvent("内容分享", "微信朋友圈", mGameEntity?.name)
        }
        binding.shareQqTv.setOnClickListener {
            getShareUtils().qqShare()
            MtaHelper.onEvent("内容分享", "QQ好友", mGameEntity?.name)
        }
        binding.shareQqzoneTv.setOnClickListener {
            getShareUtils().qZoneShare()
            MtaHelper.onEvent("内容分享", "QQ空间", mGameEntity?.name)
        }
        binding.shareWeiboTv.setOnClickListener {
            getShareUtils().sinaWeiboShare()
            MtaHelper.onEvent("内容分享", "新浪微博", mGameEntity?.name)
        }
        binding.shareSmsTv.setOnClickListener {
            getShareUtils().shortMessageShare()
            MtaHelper.onEvent("内容分享", "短信", mGameEntity?.name)
        }
        binding.copyLinkTv.setOnClickListener {
            getShareUtils().copyLink(getShareUrl())
            MtaHelper.onEvent("内容分享", "复制链接", mGameEntity?.name)
        }
        binding.feedbackTv.setOnClickListener {
            DirectUtils.directToHelpAndFeedback(requireContext())
            com.halo.assistant.HaloApp.put(Constants.GAME_NAME, mGameEntity?.name)
            MtaHelper.onEvent("游戏详情_新", "问题反馈按钮", mGameEntity?.name ?: "")
        }
        binding.copyrightTv.setOnClickListener {
            requireContext().startActivity(
                WebActivity.getWebIntent(
                    requireContext(),
                    requireContext().getString(R.string.copyright_title),
                    requireContext().getString(R.string.copyright_rules_url)
                )
            )
            MtaHelper.onEvent("游戏详情_新", "版权申诉按钮", mGameEntity?.name ?: "")
        }
        binding.cancelTv.setOnClickListener {
            dismissAllowingStateLoss()
        }
    }

    private fun getShareUtils(): ShareUtils {
        val url = getShareUrl()
        val shareUtils = ShareUtils.getInstance(requireContext())
        var shareEntrance: ShareUtils.ShareEntrance = ShareUtils.ShareEntrance.game
        val tagList = mGameEntity?.getTag() ?: arrayListOf()
        for (s in tagList) {
            if ("官方版" != s) {
                shareEntrance = ShareUtils.ShareEntrance.plugin
            }
        }
        shareUtils.shareParamsDetail(
            requireActivity(), url, mGameEntity?.icon ?: "",
            mGameEntity?.name ?: "",
            mGameEntity?.brief ?: "", shareEntrance, mGameEntity?.id ?: ""
        )
        return shareUtils
    }

    private fun getShareUrl(): String {
        return requireContext().getString(R.string.share_game_url, mShortId)
    }

    private fun updateConcernView() {
        if (mShowConcernIcon) {
            binding.concernTv.visibility = View.VISIBLE
            if (mIsConcerned) {
                binding.concernTv.text = "取消关注"
                binding.concernTv.setDrawableTop(R.drawable.ic_gamedetail_menu_followed)
                binding.concernTv.setOnClickListener {
                    ifLogin("游戏详情-[关注]") {
                        DialogHelper.showCancelDialog(requireContext(), {
                            mViewModel.concernCommand(false)
                        })
                    }
                }
            } else {
                binding.concernTv.text = "关注游戏"
                binding.concernTv.setDrawableTop(R.drawable.ic_gamedetail_menu_follow)
                binding.concernTv.setOnClickListener {
                    ifLogin("游戏详情-[关注]") {
                        mViewModel.concernCommand(true)
                    }
                }
            }
        }
    }

    override fun getRootView(): View = binding.root
    override fun getDragCloseView(): View = binding.dragClose

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        binding.container.background = R.drawable.game_detail_more_dialog_background.toDrawable(requireContext())
        binding.gameNameTv.setTextColor(R.color.text_title.toColor(requireContext()))
        binding.handleView.background = R.drawable.download_dialog_close_hint.toDrawable(requireContext())
        binding.dividerLine1.setBackgroundColor(R.color.divider.toColor(requireContext()))
        binding.dividerLine2.setBackgroundColor(R.color.divider.toColor(requireContext()))
        (binding.shareContainer.getChildAt(0) as LinearLayout).children.forEach {
            if (it is TextView) {
                it.setTextColor(R.color.text_subtitle.toColor(requireContext()))
            }
        }
        binding.copyLinkTv.run {
            setTextColor(R.color.text_subtitle.toColor(requireContext()))
            setDrawableTop(R.drawable.icon_gamedetail_copy_link)
        }
        binding.feedbackTv.run {
            setTextColor(R.color.text_subtitle.toColor(requireContext()))
            setDrawableTop(R.drawable.icon_gamedetail_feedback)
        }
        binding.copyrightTv.run {
            setTextColor(R.color.text_subtitle.toColor(requireContext()))
            setDrawableTop(R.drawable.icon_gamedetail_copyright)
        }
        binding.cancelTv.run {
            background = R.drawable.button_round_gray_light.toDrawable(requireContext())
            setTextColor(R.color.text_subtitle.toColor(requireContext()))
        }
    }

    companion object {
        const val KEY_SHOW_CONCERN_ICON = "displayed_concern_icon"
        const val KEY_IS_CONCERNED = "concerned"
        private const val KEY_GAME = "game"
        private const val KEY_SHORT_ID = "short_id"

        @JvmStatic
        fun showMoreDialog(
            activity: AppCompatActivity,
            gameEntity: GameEntity?,
            shortId: String,
            showConcernIcon: Boolean = false,
            isConcerned: Boolean = false,
        ) {
            if (gameEntity == null) return
            GameDetailMoreDialog().apply {
                arguments = Bundle().apply {
                    putParcelable(KEY_GAME, gameEntity)
                    putString(KEY_SHORT_ID, shortId)
                    putBoolean(KEY_SHOW_CONCERN_ICON, showConcernIcon)
                    putBoolean(KEY_IS_CONCERNED, isConcerned)
                }
            }.show(activity.supportFragmentManager, GameDetailMoreDialog::class.java.name)
        }
    }
}