package com.gh.gamecenter.subject.tile

import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.FragmentSubjectTiledBinding
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.base.fragment.ToolbarController
import com.gh.gamecenter.subject.SubjectListFragment
import com.google.android.material.appbar.AppBarLayout
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class SubjectTileFragment : BaseFragment<Any>() {

    private lateinit var mSubjectData: SubjectData
    private lateinit var mSettingsEntity: SubjectSettingEntity

    private lateinit var mSelectedTypeName: String

    private val mBinding by lazy { FragmentSubjectTiledBinding.inflate(layoutInflater) }

    private var mIsTouchScreen: Boolean = false

    override fun getLayoutId() = 0
    override fun getInflatedLayout() = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化数据
        mSubjectData = arguments?.getParcelable(EntranceConsts.KEY_SUBJECT_DATA) ?: return
        mSettingsEntity =
            arguments?.getParcelable(SubjectSettingEntity::class.java.simpleName) ?: return

        mSelectedTypeName = "全部"
        mSubjectData.filter = UrlFilterUtils.getFilterQuery("type", "全部")
        mSubjectData.sort = UrlFilterUtils.getFilterQuery("position", "1")

        mBinding.subjectFilterContainer.visibility =
            if (mSettingsEntity.filter == "on") View.VISIBLE else View.GONE

        // 初始化顶部类型列表
        val layoutManager = object : GridLayoutManager(context, 4) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mBinding.subjectTypeList.isNestedScrollingEnabled = false
        mBinding.subjectTypeList.layoutManager = layoutManager
        mBinding.subjectTabbarHottest.setOnClickListener(this)
        mBinding.subjectTabbarNewest.setOnClickListener(this)

        if (mSettingsEntity.typeEntity.content.size > 1) {
            val adapter = SubjectTypeListAdapter(requireContext(), mItemClickListener = {
                mSelectedTypeName = it
                if (it == "全部") {
                    // 全部的时候添加头图
                    mSubjectData.filter = UrlFilterUtils.getFilterQuery("tags", it, "type", it)
                } else {
                    mSubjectData.filter = UrlFilterUtils.getFilterQuery("tags", it)
                }
                loadData()
            }, mGameType = mSettingsEntity.typeEntity.content)
            mBinding.subjectTypeList.adapter = adapter
        }

        // Appbar 交互
        mBinding.subjectAppbar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (!TextUtils.isEmpty(mSubjectData.subjectName) && activity is ToolbarController) {
                val totalScrollRange = appBarLayout.totalScrollRange
                if (abs(verticalOffset) < totalScrollRange / 2) {
                    (activity as ToolbarController).setNavigationTitle(mSubjectData.subjectName)
                } else if (abs(verticalOffset) == totalScrollRange && totalScrollRange != 0) {
                    (activity as ToolbarController).setNavigationTitle(
                        StringUtils.buildString(
                            mSubjectData.subjectName,
                            "-",
                            mSelectedTypeName,
                            "↑"
                        )
                    )
                }
            }
        })

        loadData()
    }

    // Appbar 交互
    fun onTouchEvent(motionEvent: MotionEvent) {
        when (motionEvent.action) {
            MotionEvent.ACTION_DOWN -> mIsTouchScreen = true
            MotionEvent.ACTION_UP -> mIsTouchScreen = false
        }
    }

    // Appbar 交互
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(reuse: EBReuse) {
        if (OPEN_APPBAR == reuse.type && !mIsTouchScreen) {
            mBinding.subjectAppbar.setExpanded(true, true)
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.subject_tabbar_hottest -> {
                mBinding.subjectTabbarHottest.isChecked = true
                mBinding.subjectTabbarNewest.isChecked = false
                mSubjectData.sort = UrlFilterUtils.getFilterQuery("position", "1")
                loadData()
            }
            R.id.subject_tabbar_newest -> {
                mBinding.subjectTabbarHottest.isChecked = false
                mBinding.subjectTabbarNewest.isChecked = true
                mSubjectData.sort = UrlFilterUtils.getFilterQuery("publish", "-1")
                loadData()
            }
        }
    }

    fun loadData() {
        val transaction = childFragmentManager.beginTransaction()
        hideFragments(transaction)
        alterFragment(transaction, mSubjectData.filter + mSubjectData.sort)
        transaction.commitAllowingStateLoss()
    }

    private fun alterFragment(
        transaction: androidx.fragment.app.FragmentTransaction,
        fmTag: String
    ) {
        var fragmentByTag: androidx.fragment.app.Fragment? =
            childFragmentManager.findFragmentByTag(fmTag)
        try {
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag)
            } else {
                fragmentByTag = SubjectListFragment()
                val bundle = arguments ?: Bundle()
                bundle.putParcelable(EntranceConsts.KEY_SUBJECT_DATA, mSubjectData)
                fragmentByTag.arguments = bundle
                transaction.add(R.id.subject_content_rl, fragmentByTag, fmTag)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        private const val OPEN_APPBAR = "openAppBar"
    }

}