package com.gh.gamecenter.gamedetail.fuli.kaifu

import android.content.Context
import android.view.View
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.LazyListFragment
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.databinding.FragmentServersCalendarListBinding
import java.text.SimpleDateFormat
import java.util.*

/**
 * 开服订阅-开服表
 */
class ServersCalendarListFragment :
    LazyListFragment<ServersCalendarListViewModel.ItemData, ServersCalendarListViewModel>() {

    private var adapter: ServersCalendarListAdapter? = null

    private lateinit var viewBinding: FragmentServersCalendarListBinding

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

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        viewBinding = FragmentServersCalendarListBinding.bind(inflatedView)
    }

    override fun onRefresh() {
        super.onRefresh()
        viewBinding.topDateContainer.root.visibility = View.GONE
    }

    override fun onLoadError() {
        super.onLoadError()
        viewBinding.topDateContainer.root.visibility = View.GONE
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        viewBinding.topDateContainer.root.visibility = View.GONE
    }

    override fun provideListViewModel(): ServersCalendarListViewModel {
        return viewModelProvider()
    }

    override fun provideListAdapter(): ListAdapter<*> {
        return adapter ?: ServersCalendarListAdapter(
            requireContext(),
            mListViewModel
        ).apply {
            adapter = this
        }
    }

    override fun getItemDecoration(): RecyclerView.ItemDecoration? = null

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()

        viewBinding.subscribedGameManagementLayout.setOnClickListener {
            DirectUtils.directToServersSubscribedGameList(it.context)
        }

        mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager && !mListViewModel.obsListData.value.isNullOrEmpty()) {
                    val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()

                    // 悬挂的文案
                    viewBinding.topDateContainer.root.visibility = View.VISIBLE
                    viewBinding.topDateContainer.timeTv.text =
                        formatTime(recyclerView.context, mListViewModel.getTimeByPosition(firstVisiblePosition) * 1000)

                    // 悬挂界面移动
                    val lp = viewBinding.topDateContainer.root.layoutParams as FrameLayout.LayoutParams
                    if (firstVisiblePosition != 0
                        && mListViewModel?.getItemAtPosition(firstVisiblePosition + 1)?.time != null
                    ) {
                        val bottom = layoutManager.findViewByPosition(firstVisiblePosition)?.bottom ?: 0
                        if (bottom <= viewBinding.topDateContainer.root.height) {
                            lp.topMargin = bottom - viewBinding.topDateContainer.root.height
                        } else {
                            lp.topMargin = 0
                        }
                    } else {
                        lp.topMargin = 0
                    }
                    viewBinding.topDateContainer.root.layoutParams = lp
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {}
        })
    }

    companion object {

        /**
         * 将时间戳转换成开服表时间
         * 开服表时间显示规则:
         *  明天：目标日期=当天的下一天日期
         *  今天：目标日期=当天日期
         *  月日：目标日期在当前自然年以内
         *  年月日：目标日期在当前自然年以外
         */
        fun formatTime(context: Context, time: Long): String {
            val serverCalendar = Calendar.getInstance().apply {
                timeInMillis = time
            }
            val todayCalendar = Calendar.getInstance()
            val tomorrowCalendar = Calendar.getInstance().apply {
                add(Calendar.DATE, 1)
            }

            return if (todayCalendar.get(Calendar.YEAR) == serverCalendar.get(Calendar.YEAR)
                && todayCalendar.get(Calendar.MONTH) == serverCalendar.get(Calendar.MONTH)
                && todayCalendar.get(Calendar.DATE) == serverCalendar.get(Calendar.DATE)
            ) {
                context.getString(R.string.servers_calendar_list_date_today)
            } else if (tomorrowCalendar.get(Calendar.YEAR) == serverCalendar.get(Calendar.YEAR)
                && tomorrowCalendar.get(Calendar.MONTH) == serverCalendar.get(Calendar.MONTH)
                && tomorrowCalendar.get(Calendar.DATE) == serverCalendar.get(Calendar.DATE)
            ) {
                context.getString(R.string.servers_calendar_list_date_tomorrow)
            } else if (todayCalendar.get(Calendar.YEAR) == serverCalendar.get(Calendar.YEAR)) {
                SimpleDateFormat("MM月dd日", Locale.getDefault()).format(time)
            } else {
                SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()).format(time)
            }
        }
    }
}