package com.gh.gamecenter.gamecollection.detail

import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import com.gh.gamecenter.core.runOnUiThread
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.BiCallback
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.BitmapUtils
import com.gh.gamecenter.databinding.FragmentGameCollectionPosterBinding
import com.gh.gamecenter.databinding.LayoutGameCollectionTagBinding
import com.gh.gamecenter.entity.GamesCollectionDetailEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.base.fragment.ToolbarFragment

class GameCollectionPosterFragment : ToolbarFragment() {

    private val mBinding by lazy { FragmentGameCollectionPosterBinding.inflate(layoutInflater) }
    private var mViewModel: GameCollectionPosterViewModel? = null
    private var mEntity = GamesCollectionDetailEntity()

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

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

        mViewModel = viewModelProvider()
        mEntity = arguments?.getParcelable(EntranceConsts.KEY_DATA) ?: GamesCollectionDetailEntity()

    }

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

        arrayListOf(
            mBinding.backIv,
            mBinding.userIcon,
            mBinding.userName,
            mBinding.followTv
        ).forEach {
            it.setOnClickListener(this)
        }

        mViewModel?.followLiveData?.observeNonNull(viewLifecycleOwner) {
            setFollowStatus(it)
        }

        mBinding.apply {
            mEntity.apply {
                nameTv.text = title
                userName.text = user?.name
                desTv.text = intro
                followTv.goneIf(user?.id == UserManager.getInstance().userId)
                ImageUtils.getBitmap(cover, object : BiCallback<Bitmap, Boolean> {
                    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
                    override fun onFirst(first: Bitmap) {
                        try {
                            val blurBitmap = BitmapUtils.getBlurBitmap(requireContext(), first, 16)
                            runOnUiThread {
                                posterBg.setImageBitmap(blurBitmap)
                            }
                        } catch (t: Throwable) {
                            posterBg.setImageBitmap(first)
                        }
                    }

                    override fun onSecond(second: Boolean) {}
                })

                userIcon.display(user?.border, user?.icon, user?.auth?.icon)

                tags?.forEachIndexed { index, tag ->
                    tagContainer.addView(getTagView(tag.name, index == tags!!.size - 1))
                }

                setFollowStatus(me?.isFollower == true)
            }
        }
    }

    private fun setFollowStatus(isFollow: Boolean) {
        mBinding.followTv.run {
            setBackgroundResource(if (isFollow) R.drawable.button_round_white_alpha_10 else R.drawable.button_round_white_alpha_20)
            setTextColor(
                if (isFollow) com.gh.gamecenter.common.R.color.white_alpha_60.toColor(requireContext()) else com.gh.gamecenter.common.R.color.white.toColor(
                    requireContext()
                )
            )
            text = if (isFollow) "已关注" else "关注"
        }
    }

    private fun getTagView(content: String, isLast: Boolean): View {
        return LayoutGameCollectionTagBinding.inflate(layoutInflater).apply {
            root.setPadding(0, 12F.dip2px(), 0, 0)
            divider.goneIf(isLast)
            contentTv.text = content
        }.root
    }

    override fun onClick(view: View) {
        super.onClick(view)
        when (view.id) {
            R.id.backIv -> requireActivity().finish()

            R.id.userIcon -> {
                DirectUtils.directToHomeActivity(requireContext(), mEntity.user?.id, "", "游戏单详情-封面页")
            }

            R.id.userName -> {
                DirectUtils.directToHomeActivity(requireContext(), mEntity.user?.id, "", "游戏单详情-封面页")
            }

            R.id.followTv -> {
                SensorsBridge.trackUserFollowClick(
                    userId = mEntity.user?.id ?: "",
                    userName = mEntity.user?.name ?: "",
                    buttonName = mBinding.followTv.text.toString()
                )
                ifLogin("游戏单详情-封面页") {
                    if (mBinding.followTv.text == "关注") {
                        mViewModel?.followingCommand(mEntity.user?.id ?: "", true)
                    } else {
                        DialogHelper.showDialog(
                            requireContext(),
                            "取消关注",
                            "确定要取消关注 ${mEntity.user?.name} 吗？",
                            "确定取消",
                            "暂不取消",
                            { mViewModel?.followingCommand(mEntity.user?.id ?: "", false) },
                            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
                        )
                    }
                }
            }
        }
    }
}