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

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.GameDetailCalenderViewHolder
import com.gh.gamecenter.entity.CalendarEntity
import com.gh.gamecenter.entity.ServerCalendarEntity
import com.gh.gamecenter.servers.add.AddKaiFuActivity.Companion.getIntent
import com.lightgame.adapter.BaseRecyclerAdapter
import java.util.*

class ServersCalendarAdapter(
    context: Context,
    val viewModel: ServersCalendarViewModel,
    val calendarList: List<CalendarEntity>
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {
    private val mGameEntity = viewModel.game

    private val mWeekData = context.resources.getStringArray(R.array.weekdays)


    override fun getItemViewType(position: Int): Int {
        return if (position < 7) {
            ITEM_WEEK
        } else {
            ITEM_DAY
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ITEM_WEEK) {
            val textView = TextView(mContext)
            textView.setPadding(0, 16F.dip2px(), 0, 21F.dip2px())
            textView.gravity = Gravity.CENTER
            textView.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
            textView.textSize = 12F
            WeekViewHolder(textView)
        } else {
            GameDetailCalenderViewHolder(parent.toBinding())
        }
    }

    override fun getItemCount(): Int {
        return calendarList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is WeekViewHolder) {
            holder.week.text = mWeekData[position]
        } else if (holder is GameDetailCalenderViewHolder) {
            val entity: CalendarEntity = calendarList[position - 6]
            if (entity.day != -1) {
                val day = entity.day
                if (day == viewModel.curDay && viewModel.selectedMonth == MonthType.CUR_MONTH) {
                    holder.binding.calendarDay.text = "今天"
                    holder.binding.calendarDay.setTextColor(R.color.theme_font.toColor(mContext))
                    holder.binding.calendarKaifu.setBackgroundResource(R.drawable.textview_blue_style)
                } else {
                    holder.binding.calendarDay.text = day.toString()
                    if (day < viewModel.curDay && viewModel.selectedMonth == MonthType.CUR_MONTH || viewModel.selectedMonth == MonthType.PREVIOUS_MONTH) {
                        holder.binding.calendarDay.setTextColor(
                            ContextCompat.getColor(
                                mContext,
                                R.color.text_subtitleDesc
                            )
                        )
                    } else {
                        holder.binding.calendarDay.setTextColor(ContextCompat.getColor(mContext, R.color.text_title))
                    }
                }
                val calendarServer: List<ServerCalendarEntity> = entity.server
                if (calendarServer.isNotEmpty()) {
                    holder.binding.calendarKaifu.visibility = View.VISIBLE
                    var remark: String? = null
                    for (calendarEntity in calendarServer) {
                        if (!TextUtils.isEmpty(calendarEntity.remark)) {
                            remark = calendarEntity.remark
                            break
                        }
                    }
                    holder.binding.calendarKaifu.text =
                        if (TextUtils.isEmpty(remark)) if (calendarServer.size > 1) "新服×" + calendarServer.size else "新服" else remark
                    if (day < viewModel.curDay && viewModel.selectedMonth == MonthType.CUR_MONTH || viewModel.selectedMonth == MonthType.PREVIOUS_MONTH) {
                        holder.binding.calendarKaifu.background = DrawableView.getOvalDrawable(R.color.text_body, 6F)
                    } else {
                        holder.binding.calendarKaifu.background = DrawableView.getOvalDrawable(
                            if (TextUtils.isEmpty(remark)) R.color.tag_yellow else R.color.tag_orange,
                            6F
                        )
                    }
                } else {
                    holder.binding.calendarKaifu.visibility = View.INVISIBLE
                }
                holder.itemView.isEnabled = true
                holder.itemView.setOnClickListener { v: View? ->
                    if (entity.server.size == 0) {
                        val meEntity = viewModel.meEntity
                        if (meEntity?.isPartTime == true) {
                            (mContext as Activity).startActivityForResult(
                                getIntent(
                                    mContext,
                                    if (viewModel.serverCalendarLiveData.value.isNullOrEmpty()) ServerCalendarEntity() else viewModel.serverCalendarLiveData.value!!.last(),
                                    viewModel.serverCalendarLiveData.value as ArrayList<ServerCalendarEntity>,
                                    mGameEntity.id,
                                    viewModel.getSelectTime(entity.day, entity.month, entity.year)
                                ),
                                ServersCalendarActivity.GAME_DETAIL_ADD_KAIFU_REQUEST
                            )
                        }
                    } else {
                        MtaHelper.onEvent("开服日历表", "详情", "${viewModel.game.name}+${holder.binding.calendarKaifu.text}")
                        viewModel.serversDetailLiveData.postValue(entity)
                    }
                }
            } else {
                holder.itemView.isEnabled = false
                holder.binding.calendarDay.text = ""
                holder.binding.calendarKaifu.visibility = View.INVISIBLE
            }
        }
    }

//    // 获取当前位置(时间)最近的开服信息
//    private fun getRecentServerByPosition(day: Int): ServerCalendarEntity {
//        tryCatchInRelease {
//            val formatDay = SimpleDateFormat("dd", Locale.CHINA)
//            val offsetAndServerMap = HashMap<Int, ServerCalendarEntity>()
//
//            for (calendarEntity in calendarList) {
//                val servers = calendarEntity.server
//                if (servers.isNotEmpty()) {
//                    val server = servers.last()
//                    offsetAndServerMap[abs(formatDay.format(server.getTime() * 1000).toInt() - day)] = server
//                }
//            }
//
//            val toList = offsetAndServerMap.keys.toMutableList()
//            toList.sortWith(Comparator { o1, o2 -> o1 - o2 })
//            return offsetAndServerMap[toList.first()]!!
//        }
//        return viewModel.serverCalendarLiveData.value!!.last()
//    }

    private class WeekViewHolder(val week: TextView) : RecyclerView.ViewHolder(week)

    companion object {
        private const val ITEM_WEEK = 1
        private const val ITEM_DAY = 2
    }
}