package com.gh.gamecenter.subject.tile

import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.common.view.ConfigFilterView
import com.gh.common.view.ConfigFilterView.SortType
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.base.fragment.ToolbarController
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.databinding.FragmentSubjectTiledBinding
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.subject.SubjectListFragment
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

    private var mMaxSize = ""
    private var mMinSize = ""
    private var mSelectedFilterSize = SubjectSettingEntity.Size(text = "全部大小")

    private val finalFilter: String
        get() {
            var filter = if (mSelectedTypeName == "全部") {
                // 全部的时候添加头图
                UrlFilterUtils.getFilterQuery("tags", mSelectedTypeName, "type", mSelectedTypeName)
            } else {
                UrlFilterUtils.getFilterQuery("tags", mSelectedTypeName)
            }
            if (mMinSize.isNotEmpty() && mMinSize != "-1") {
                filter += ",${UrlFilterUtils.getFilterQuery("min_size", mMinSize)}"
            }
            if (mMaxSize.isNotEmpty() && mMaxSize != "-1") {
                filter += ",${UrlFilterUtils.getFilterQuery("max_size", mMaxSize)}"
            }

            return filter
        }

    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(EntranceConsts.KEY_SUBJECT_SETTING_DATA) ?: return

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

        mBinding.subjectTypeList.goneIf(mSettingsEntity.typeEntity.content.size <= 1) {
            // 初始化顶部类型列表
            val layoutManager = object : GridLayoutManager(context, 4) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            mBinding.subjectTypeList.isNestedScrollingEnabled = false
            mBinding.subjectTypeList.layoutManager = layoutManager
            mBinding.subjectTypeList.addItemDecoration(GridSpacingItemDecoration(4, 8F.dip2px(), false))
            val adapter = SubjectTypeListAdapter(requireContext(), mItemClickListener = {
                mSelectedTypeName = it
                mSubjectData.filter = finalFilter
                mSubjectData.tag = it
                loadData()
            }, mGameType = mSettingsEntity.typeEntity.content)
            mBinding.subjectTypeList.adapter = adapter
        }

        mBinding.filterView.goneIf(!mSettingsEntity.isFilterEnabled) {
            mBinding.filterView.run {
                initSubjectFilterView(mSettingsEntity)
                setOnConfigSetupListener(object :
                    ConfigFilterView.OnConfigFilterSetupListener {
                    override fun onShowSortSize() {}

                    override fun onSetupSortSize(sortSize: SubjectSettingEntity.Size) {
                        mMinSize = sortSize.min.toString()
                        mMaxSize = sortSize.max.toString()
                        mSelectedFilterSize = sortSize
                        mSubjectData.filter = finalFilter
                        loadData()
                    }

                    override fun onSetupSortType(sortType: SortType) {
                        val clickTv = when (sortType) {
                            SortType.RATING -> ratingTv
                            SortType.NEWEST -> newestTv
                            SortType.UPDATE -> updateTv
                            else -> recommendedTv
                        }

                        val sort = when (clickTv.text) {
                            "更新" -> UrlFilterUtils.getFilterQuery("update_time", "-1")
                            "最新" -> UrlFilterUtils.getFilterQuery("publish", "-1")
                            "评分" -> UrlFilterUtils.getFilterQuery("star", "-1")
                            else -> UrlFilterUtils.getFilterQuery("position", "1")
                        }

                        if (mSubjectData.sort != sort) {
                            mSubjectData.sort = sort
                            loadData()
                        }
                    }
                })
            }
        }

        // 是否为专题合集详情子页面
        val isColumnCollection = arguments?.getBoolean(EntranceConsts.KEY_IS_COLUMN_COLLECTION) ?: false
        if (!isColumnCollection) {
            // Appbar 交互
            mBinding.subjectAppbar.addOnOffsetChangedListener { 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)
        }
    }

    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?.clone() as? Bundle ?: Bundle()
                bundle.remove(EntranceConsts.KEY_SUBJECT_SETTING_DATA)
                bundle.putParcelable(EntranceConsts.KEY_SUBJECT_DATA, mSubjectData)
                bundle.putString(EntranceConsts.KEY_SUBJECT_SORT_SIZE, mSelectedFilterSize.text)
                fragmentByTag.arguments = bundle
                transaction.add(R.id.subject_content_rl, fragmentByTag, fmTag)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (mBinding.filterView.isVisible) {
            mBinding.filterView.updateAllTextView()
        }
    }

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

}