package com.gh.gamecenter.subject.rows

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.CheckedTextView
import android.widget.LinearLayout
import androidx.core.view.children
import androidx.core.view.updateLayoutParams
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.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.UrlFilterUtils
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.subject.SubjectListFragment

class SubjectRowsFragment : BaseFragment<Any>() {

    private lateinit var mLabelsContainer: LinearLayout

    private lateinit var mSettingEntity: SubjectSettingEntity
    private lateinit var mSubjectData: SubjectData

    private lateinit var mListFragment: SubjectListFragment

    private val mFilterMap = HashMap<String, String>()

    // 统计用的大小筛选选中文案
    private var mSelectedFilterSize = SubjectSettingEntity.Size(text = "全部大小")

    private lateinit var filterView: ConfigFilterView

    override fun getLayoutId(): Int {
        return R.layout.fragment_subject_rows
    }

    override fun initView(view: View) {
        super.initView(view)
        mSettingEntity = arguments?.getParcelable(EntranceConsts.KEY_SUBJECT_SETTING_DATA)
            ?: return
        mSubjectData = arguments?.getParcelable(EntranceConsts.KEY_SUBJECT_DATA) ?: return

        val labels = mSettingEntity.typeEntity.labels
        for (label in labels) {
            label.label.add(0, label.name)
        }

        mLabelsContainer = view.findViewById(R.id.rows_labels_container)

        createLabelsLayout()
        createFilterLayout()

        mListFragment =
            childFragmentManager.findFragmentByTag(SubjectListFragment::class.java.name) as? SubjectListFragment
                ?: SubjectListFragment()
        mListFragment.arguments = (arguments?.clone() as? Bundle)?.apply { remove(EntranceConsts.KEY_SUBJECT_SETTING_DATA) }
        childFragmentManager.beginTransaction()
            .replace(R.id.rows_list_container, mListFragment, SubjectListFragment::class.java.name)
            .commitAllowingStateLoss()
    }

    @SuppressLint("InflateParams")
    private fun createLabelsLayout() {
        val inflater = LayoutInflater.from(context)
        mSettingEntity.typeEntity.labels.forEachIndexed { index, labels ->
            val labelsItem = inflater.inflate(R.layout.subject_rows_label, mLabelsContainer, false)
            val labelContainer = labelsItem.findViewById<LinearLayout>(R.id.label_container)
            labelsItem.updateLayoutParams<MarginLayoutParams> {
                topMargin = if (index == 0) 0 else 12F.dip2px()
            }
            for (labelIndex in 0 until labels.label.size) {
                val labelName = labels.label[labelIndex]
                val labelItem =
                    inflater.inflate(R.layout.subject_rows_label_item, labelContainer, false)
                val label = labelItem.findViewById<CheckedTextView>(R.id.label)
                label.updateLayoutParams<MarginLayoutParams> {
                    leftMargin = if (labelIndex == 0) 0 else 8F.dip2px()
                }
                if (labelIndex == 0) {
                    label.isChecked = true
                    label.setTypeface(Typeface.DEFAULT, Typeface.BOLD)
                } else {
                    label.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
                }
                label.text = labelName
                label.setOnClickListener {
                    mFilterMap[labels.name] = if (labelIndex == 0) {
                        ""
                    } else {
                        labelName
                    }
                    selectLabel(labelContainer, label)
                    updateListFragment()
                }
                labelContainer.addView(labelItem)
            }
            mLabelsContainer.addView(labelsItem)
        }
    }

    private fun selectLabel(labelContainer: LinearLayout, label: CheckedTextView) {
        for (i in 0 until labelContainer.childCount) {
            val view = labelContainer.getChildAt(i)
            if (view is CheckedTextView && view.isChecked) {
                view.isChecked = false
                view.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
            }
        }
        label.isChecked = true
        label.setTypeface(Typeface.DEFAULT, Typeface.BOLD)
    }

    private fun createFilterLayout() {
        if (mSettingEntity.isFilterEnabled) {
            filterView = ConfigFilterView(requireContext()).apply { initSubjectFilterView(mSettingEntity) }
            // 设置默认页面链接
            when (filterView.updateTv.text) {
                "更新" -> mSubjectData.sort = UrlFilterUtils.getFilterQuery("update_time", "-1")
                "最新" -> mSubjectData.sort = UrlFilterUtils.getFilterQuery("publish", "-1")
                "评分" -> mSubjectData.sort = UrlFilterUtils.getFilterQuery("star", "-1")
                else -> mSubjectData.sort = UrlFilterUtils.getFilterQuery("position", "1")
            }
            mLabelsContainer.addView(
                filterView,
                LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    topMargin = 8F.dip2px()
                })

            filterView.setOnConfigSetupListener(object :
                ConfigFilterView.OnConfigFilterSetupListener {
                override fun onShowSortSize() {
                    MtaHelper.onEvent("游戏专题", "筛选大小", mSubjectData.subjectName)
                }

                override fun onSetupSortSize(sortSize: SubjectSettingEntity.Size) {
                    mFilterMap["min_size"] = sortSize.min.toString()
                    mFilterMap["max_size"] = sortSize.max.toString()

                    mSelectedFilterSize = sortSize

                    updateListFragment()

                    MtaHelper.onEvent(
                        "游戏专题",
                        "筛选大小",
                        "${sortSize.text}_${mSubjectData.subjectName}"
                    )
                }

                override fun onSetupSortType(sortType: SortType) {
                    val clickTv = when (sortType) {
                        SortType.RATING -> filterView.ratingTv
                        SortType.NEWEST -> filterView.newestTv
                        SortType.UPDATE -> filterView.updateTv
                        else -> filterView.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
                        updateListFragment()
                    }
                }
            })
        } else {
            mLabelsContainer.setPadding(0, 8F.dip2px(), 0, 8F.dip2px())
        }
    }

    private fun findAllSelectedLabel(viewGroup: ViewGroup): ArrayList<String> {
        val selectedArrayList = arrayListOf<String>()
        for (view in viewGroup.children) {
            if (view is CheckedTextView && view.isChecked) {
                selectedArrayList.add(view.text.toString())
            } else if (view is ViewGroup) {
                selectedArrayList.addAll(findAllSelectedLabel(view))
            }
        }
        return selectedArrayList
    }

    private fun updateListFragment() {
        var selectedTypes = ""
        var filters = ""

        for (key in mFilterMap.keys) {
            if (key != "min_size" && key != "max_size") {
                if (!mFilterMap[key].isNullOrEmpty()) selectedTypes += (mFilterMap[key] + "-")
            }
        }
        if (selectedTypes.isNotEmpty()) {
            val resultTypes =
                selectedTypes.removeRange(selectedTypes.length - 1, selectedTypes.length)
            filters = UrlFilterUtils.getFilterQuery("tags", resultTypes)
        }

        val minSizeValue = mFilterMap["min_size"]
        if (minSizeValue != null && minSizeValue != "-1") {
            val filterMin = UrlFilterUtils.getFilterQuery("min_size", minSizeValue)
            if (filters.isNotEmpty()) {
                filters = "$filters,$filterMin"
            } else {
                filters = filterMin
            }
        }

        val maxSizeValue = mFilterMap["max_size"]
        if (maxSizeValue != null && maxSizeValue != "-1") {
            val filterMax = UrlFilterUtils.getFilterQuery("max_size", maxSizeValue)
            if (filters.isNotEmpty()) {
                filters = "$filters,$filterMax"
            } else {
                filters = filterMax
            }
        }

        if ((minSizeValue == "-1" || minSizeValue == null)
            && (maxSizeValue == "-1" || maxSizeValue == null)
        ) {
            // 显示头图（后台需要 `type:全部` 作为显示头图的依据）
            val type = if (filters.contains("tags")) {
                "不显示头图"
            } else {
                "全部"
            }
            val filterAll = UrlFilterUtils.getFilterQuery("type", type)
            filters = if (filters.isNotEmpty()) {
                "$filters,$filterAll"
            } else {
                filterAll
            }
        }

        mSubjectData.filter = filters
        mListFragment.selectedLabelList = findAllSelectedLabel(mLabelsContainer)
        mListFragment.refreshPage(mSubjectData.filter, mSubjectData.sort, mSelectedFilterSize)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (::filterView.isInitialized) {
            filterView.updateAllTextView()
        }
    }
}