package com.gh.gamecenter.servers

import android.annotation.SuppressLint
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.databinding.FragmentGameServersPublishBinding
import com.gh.gamecenter.entity.ServersGameCategory
import com.gh.gamecenter.eventbus.EBNetworkState
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class GameServersPublishFragment : LazyFragment() {

    private var mBinding: FragmentGameServersPublishBinding? = null
    private lateinit var mContentFragment: GameServersContentFragment

    private val mCategoryList = ArrayList<ServersGameCategory>()

    private var mDay: String? = null
    private var mHour: String? = null
    private var mTags: String? = null
    private val mType = "开服"

    override fun getRealLayoutId(): Int {
        return R.layout.fragment_game_servers_publish
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        mBinding = FragmentGameServersPublishBinding.bind(inflatedView)
    }

    override fun initRealView() {
        super.initRealView()

        mBinding?.run {
            serverStatus.text = "游戏分类"
            serverTime.text = "开服时间"
            serverStatus.setOnClickListener {
                showCategoryPopupWindow(it as CheckedTextView, callback = { tags ->
                    mTags = tags
                    mContentFragment.filterData(mDay, mHour, mType, mTags)
                })
            }
            serverTime.setOnClickListener {
                showServersTimePopupWindow(it as CheckedTextView, callback = { day, hour ->
                    mDay = day
                    mHour = hour
                    mContentFragment.filterData(mDay, mHour, mType, mTags)
                })
            }
        }

        val bundle = arguments
        bundle?.putString(EntranceConsts.KEY_TYPE, "开服")
        mContentFragment =
            childFragmentManager.findFragmentByTag(GameServersContentFragment::class.java.name) as? GameServersContentFragment
                ?: GameServersContentFragment()
        mContentFragment.arguments = bundle
        childFragmentManager.beginTransaction()
            .replace(R.id.layout_fragment_content, mContentFragment, GameServersContentFragment::class.java.name)
            .commitAllowingStateLoss()

        loadServerFilterTag()
    }

    @SuppressLint("CheckResult")
    private fun loadServerFilterTag() {
        RetrofitManager.getInstance().api
            .serverFilterTag
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<List<ServersGameCategory>>() {
                override fun onSuccess(data: List<ServersGameCategory>) {
                    if (mCategoryList.isEmpty()) mCategoryList.addAll(data)
                }
            })
    }

    private fun showCategoryPopupWindow(v: CheckedTextView, callback: (String?) -> Unit) {
        v.isChecked = true
        v.setTextColor(R.color.theme_font.toColor(requireContext()))

        val inflater = LayoutInflater.from(context)
        val layout = inflater.inflate(R.layout.popup_server_category, null)
        val popupWindow = PopupWindow(
            layout,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        val reset = layout.findViewById<TextView>(R.id.reset)
        val complete = layout.findViewById<TextView>(R.id.complete)
        val contentContainer = layout.findViewById<LinearLayout>(R.id.content_container)

        reset.background = DrawableView.getStrokeDrawable(R.color.text_body, context = requireContext())
        complete.background = DrawableView.getOvalDrawable(R.color.theme, context = requireContext())

        contentContainer.removeAllViews()
        for (entity in mCategoryList) {
            val view = inflater.inflate(R.layout.popup_server_category_item, null)
            view.findViewById<TextView>(R.id.category_name).text = entity.name
            val labelsContainer = view.findViewById<ViewGroup>(R.id.labels_container)
            for (name in entity.label) {
                val label = CheckedTextView(context)
                val layoutParams = LinearLayout.LayoutParams(71f.dip2px(), 28f.dip2px())
                layoutParams.setMargins(0, 0, 12F.dip2px(), 0)
                label.layoutParams = layoutParams
                label.gravity = Gravity.CENTER
                label.textSize = 13F
                label.text = name
                label.background =
                    DrawableView.getOvalSelectorStyle(R.color.background, R.color.text_e6f3ff, requireContext())
                label.setTextColor(
                    DrawableView.getSelectorColorStyle(
                        R.color.text_title,
                        R.color.theme_font,
                        requireContext()
                    )
                )
                label.isSingleLine = true
                labelsContainer.addView(label)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    label.textAlignment = View.TEXT_ALIGNMENT_CENTER
                }
                if (mTags?.contains(name) == true) {
                    label.isChecked = true
                }
                label.setOnClickListener {
                    if (!label.isChecked) {
                        for (index in 0 until labelsContainer.childCount) {
                            (labelsContainer.getChildAt(index) as CheckedTextView).isChecked = false
                        }
                    }
                    label.isChecked = !label.isChecked
                }
            }
            contentContainer.addView(view)
        }

        contentContainer.setOnClickListener {
            popupWindow.dismiss()
        }
        layout.setOnClickListener {
            popupWindow.dismiss()
        }
        reset.setOnClickListener {
            for (i in 0 until contentContainer.childCount) {
                val view = contentContainer.getChildAt(i)
                val labelsContainer = view.findViewById<ViewGroup>(R.id.labels_container)
                for (j in 0 until labelsContainer.childCount) {
                    (labelsContainer.getChildAt(j) as CheckedTextView).isChecked = false
                }
            }
        }
        complete.setOnClickListener {
            var tags = ""
            for (i in 0 until contentContainer.childCount) {
                val view = contentContainer.getChildAt(i)
                val labelsContainer = view.findViewById<ViewGroup>(R.id.labels_container)
                for (j in 0 until labelsContainer.childCount) {
                    val label = labelsContainer.getChildAt(j) as CheckedTextView
                    if (label.isChecked) {
                        tags += ("-" + label.text)
                    }
                }
            }

            if (tags.isNotEmpty()) {
                callback.invoke(tags.removeRange(0, 1))
            } else {
                callback.invoke(null)
            }
            popupWindow.dismiss()
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true

        popupWindow.setOnDismissListener {
            v.isChecked = false
            if (mTags.isNullOrEmpty()) v.setTextColor(R.color.text_title.toColor(requireContext()))
        }
        popupWindow.showAsDropDown(mBinding?.divider)
    }

    // day, hour
    private fun showServersTimePopupWindow(v: CheckedTextView, callback: (String?, String?) -> Unit) {
        v.isChecked = true
        v.setTextColor(R.color.theme_font.toColor(requireContext()))

        val inflater = LayoutInflater.from(v.context)
        val layout = inflater.inflate(R.layout.popup_server_time, null)
        val popupWindow = PopupWindow(
            layout,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        val today = layout.findViewById<CheckedTextView>(R.id.today)
        val tomorrow = layout.findViewById<CheckedTextView>(R.id.tomorrow)
        val after = layout.findViewById<CheckedTextView>(R.id.after)
        val hourContainer = layout.findViewById<LinearLayout>(R.id.hour_container)
        val hourScrollView = layout.findViewById<View>(R.id.hour_scrollview)

        today.text = "今日开服"
        tomorrow.text = "明日开服"
        after.text = "后续开服"

        if (v.text == "开服时间" || v.text.contains("今日")) {
            today.isChecked = true
            hourScrollView.visibility = View.VISIBLE

        }
        if (v.text.contains("明日")) {
            tomorrow.isChecked = true
            hourScrollView.visibility = View.VISIBLE
        }
        if (v.text == "后续开服") {
            after.isChecked = true
        }

        // add hour content
        for (i in 0 until 24 + 1) {
            // position = 0: all
            val hour = TextView(v.context)
            hour.textSize = 14F
            hour.setTextColor(R.color.text_title.toColor(requireContext()))
            hour.gravity = Gravity.CENTER_VERTICAL
            hour.setPadding(24F.dip2px(), 0, 0, 0)
            hourContainer.addView(hour, ViewGroup.LayoutParams.MATCH_PARENT, 43F.dip2px())

            if (i >= 0) {
                hour.text = if (i >= 10) "$i:00" else "0$i:00"
            }

            hour.setOnClickListener {
                if (today.isChecked) {
                    if (i >= 0) {
                        callback.invoke("today", i.toString())
                        v.text = (today.text.toString() + " " + hour.text.toString())
                    } else {
                        callback.invoke("today", null)
                        v.text = hour.text.toString()
                    }
                } else {
                    if (i >= 0) {
                        callback.invoke("tomorrow", i.toString())
                        v.text = (tomorrow.text.toString() + " " + hour.text.toString())
                    } else {
                        callback.invoke("tomorrow", null)
                        v.text = hour.text.toString()
                    }
                }
                popupWindow.dismiss()
            }
        }

        today.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_title, R.color.theme_font, requireContext()))
        tomorrow.setTextColor(
            DrawableView.getSelectorColorStyle(
                R.color.text_title,
                R.color.theme_font,
                requireContext()
            )
        )
        after.setTextColor(DrawableView.getSelectorColorStyle(R.color.text_title, R.color.theme_font, requireContext()))

        layout.setOnClickListener {
            popupWindow.dismiss()
        }
        after.setOnClickListener {
            v.text = after.text
            callback.invoke("after", null)
            popupWindow.dismiss()
        }
        today.setOnClickListener {
            hourScrollView.visibility = View.VISIBLE
            today.isChecked = true
            tomorrow.isChecked = !today.isChecked
            after.isChecked = !today.isChecked
        }
        tomorrow.setOnClickListener {
            hourScrollView.visibility = View.VISIBLE
            tomorrow.isChecked = true
            today.isChecked = !tomorrow.isChecked
            after.isChecked = !tomorrow.isChecked
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true

        popupWindow.setOnDismissListener {
            v.isChecked = false
            if (mDay.isNullOrEmpty()) v.setTextColor(R.color.text_title.toColor(requireContext()))
        }
        popupWindow.showAsDropDown(mBinding?.divider)
    }

    fun resetFilter() {
        mDay = null
        mHour = null
        mTags = null
        mBinding?.run {
            serverTime.text = "开服时间"
            serverTime.setTextColor(R.color.text_title.toColor(requireContext()))
            serverStatus.setTextColor(R.color.text_title.toColor(requireContext()))
        }
        mContentFragment.filterData(mDay, mHour, mType, mTags)
    }

    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(busNetworkState: EBNetworkState) {
        if (busNetworkState.isNetworkConnected && mCategoryList.isEmpty()) {
            loadServerFilterTag()
        }
    }
}