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

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.gamecenter.common.entity.SimpleGameEntity
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.ActivityServersCalendarBinding
import com.gh.gamecenter.databinding.DialogServersCalendearDetailItemBinding
import com.gh.gamecenter.entity.*
import com.gh.gamecenter.feature.entity.GameDetailServer
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.MeEntity
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.help.HelpAndFeedbackBridge
import com.gh.gamecenter.servers.add.AddKaiFuActivity
import com.halo.assistant.HaloApp
import com.lightgame.adapter.BaseRecyclerAdapter
import java.text.SimpleDateFormat
import java.util.*

class ServersCalendarActivity : ToolBarActivity() {
    private lateinit var mBinding: ActivityServersCalendarBinding
    private lateinit var mViewModel: ServersCalendarViewModel

    private val mDelayLogRunnable = Runnable {
        NewLogUtils.logGameDetailOpenCalendarView(mViewModel.game.name ?: "", mViewModel.game.id)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val serverCalendars = mViewModel.serverCalendarLiveData.value ?: return
        if (requestCode == GAME_DETAIL_ADD_KAIFU_REQUEST && resultCode == Activity.RESULT_OK) { // 新增开服
            val dataList = data!!.getParcelableArrayListExtra<ServerCalendarEntity>(GAME_DETAIL_ADD_KAIFU_KEY)
            if (dataList != null) {
                serverCalendars.addAll(dataList)
                mViewModel.serverCalendarLiveData.postValue(serverCalendars)
            }
        } else if (requestCode == GAME_DETAIL_PATCH_KAIFU_REQUEST && resultCode == Activity.RESULT_OK) { // 修改开服
            val dataEntity = data!!.getParcelableExtra<ServerCalendarEntity>(GAME_DETAIL_PATCH_KAIFU_KEY)
            if (dataEntity != null) {
                if (TextUtils.isEmpty(dataEntity.getNote())) { // 删除
                    for (entity in serverCalendars) {
                        if (dataEntity.id == entity.id) {
                            serverCalendars.remove(entity)
                            mViewModel.serverCalendarLiveData.postValue(serverCalendars)
                            break
                        }
                    }
                } else { // 更改
                    for (entity in serverCalendars) {
                        if (dataEntity.id == entity.id) {
                            entity.setNote(dataEntity.getNote())
                            entity.remark = dataEntity.remark
                            mViewModel.serverCalendarLiveData.postValue(serverCalendars)
                            break
                        }
                    }
                }
            }
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        setNavigationTitle("开服日历表")
        setToolbarMenu(R.menu.menu_post)
        val postMenu = getMenuItem(R.id.menu_post)
        val container = postMenu.actionView?.findViewById<View>(R.id.menu_post)
        val postButton = container?.findViewById<TextView>(R.id.menu_post_text)
        postButton?.text = "反馈"

        mBinding = ActivityServersCalendarBinding.bind(mContentView)
        mBinding.includeNoConnection.root.setOnClickListener {
            mBinding.includeLoading.root.visibility = View.VISIBLE
            mBinding.includeNoConnection.root.visibility = View.GONE
            mViewModel.loadServerData()
        }

        val game = intent?.getParcelableExtra<GameEntity>(GameEntity::class.java.simpleName)
        val serverList = intent?.getParcelableExtra<GameDetailServer>(GameDetailServer::class.java.simpleName)
        val meEntity = intent?.getParcelableExtra<MeEntity>(MeEntity::class.java.simpleName)
        if (game == null || serverList == null) {
            throwExceptionInDebug()
            return
        }

        val factory = ServersCalendarViewModel.Factory(HaloApp.getInstance().application, game, serverList, meEntity)
        mViewModel = ViewModelProviders.of(this, factory).get(ServersCalendarViewModel::class.java)
        mViewModel.calendarLiveData.observeNonNull(this, callback = {
            val adapter = ServersCalendarAdapter(this, mViewModel, it)
            mBinding.recyclerView.isNestedScrollingEnabled = false
            mBinding.recyclerView.layoutManager = GridLayoutManager(this, 7)
            mBinding.recyclerView.adapter = adapter
        })
        mViewModel.serversDetailLiveData.observeNonNull(this, callback = {
            showServersDetailDialog(it)
            NewLogUtils.logGameDetailOpenCalendarClick(mViewModel.game.name ?: "", mViewModel.game.id)
        })
        mViewModel.serverCalendarLiveData.observe(this) {
            if (it != null) {
                mViewModel.initDate()
                initView()
            } else {
                mBinding.includeLoading.root.visibility = View.GONE
                mBinding.includeNoConnection.root.visibility = View.VISIBLE
            }
        }
        mBaseHandler.postDelayed(mDelayLogRunnable, 3000)
    }

    override fun onPause() {
        super.onPause()
        mBaseHandler.removeCallbacks(mDelayLogRunnable)
    }

    override fun onMenuItemClick(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_post) {
            MtaHelper.onEvent("开服日历表", "反馈", mViewModel.game.name)
            HelpAndFeedbackBridge.startSuggestionActivity(
                this,
                SuggestType.normal,
                "service",
                StringUtils.buildString(mViewModel.game.name, "，", "开服信息问题反馈："),
                SimpleGameEntity(id = mViewModel.game.id, name = mViewModel.game.name ?: "")
            )
        }
        return super.onMenuItemClick(item)
    }

    fun initView() {
        mBinding.contentContainer.visibility = View.VISIBLE
        mBinding.includeLoading.root.visibility = View.GONE

        val serversDes = mViewModel.gameServer.des
        if (serversDes.isNotEmpty()) {
            mBinding.des.text = serversDes.fromHtml()
        }

        val curTime = System.currentTimeMillis()

        val formatMonth = SimpleDateFormat("MM", Locale.CHINA)
        val formatMonthText = SimpleDateFormat("M月", Locale.CHINA)
        val formatYearText = SimpleDateFormat("yyyy年", Locale.CHINA)
        val curMonth = formatMonth.format(curTime).toInt()

        var previousTime: Long = -1
        var previousMonth = -1

        var nextTime: Long = -1
        var nextMonth = -1

        for (serverEntity in mViewModel.serverCalendarLiveData.value ?: arrayListOf()) {
            previousTime = serverEntity.getTime() * 1000
            previousMonth = formatMonth.format(previousTime).toInt()
            if (previousMonth != curMonth && previousTime < curTime) break
        }

        for (serverEntity in mViewModel.serverCalendarLiveData.value ?: arrayListOf()) {
            nextTime = serverEntity.getTime() * 1000
            nextMonth = formatMonth.format(nextTime).toInt()
            if (nextMonth != curMonth && nextTime > curTime) break
        }

        // 是否存在下一个月开服表
        if (nextMonth != curMonth && nextTime > curTime) {
            mBinding.nextMonth.text = formatMonthText.format(nextTime)
            mBinding.nextMonth.visibility = View.VISIBLE
        } else {
            mBinding.nextMonth.visibility = View.GONE
        }

        // 是否存在上一个月开服表
        if (previousMonth != curMonth && previousTime < curTime) {
            mBinding.previousMonth.text = formatMonthText.format(previousTime)
            mBinding.previousMonth.visibility = View.VISIBLE
        } else {
            mBinding.previousMonth.visibility = View.GONE
        }


        if (!mViewModel.isExistCurServer) {
            mViewModel.selectedMonth = MonthType.NEXT_MONTH

            mBinding.curMonth.visibility = View.GONE

            mBinding.nextMonth.setBackgroundResource(R.drawable.download_oval_hint_up)
            mBinding.nextMonth.setTextColor(Color.WHITE)
            mBinding.year.text = formatYearText.format(previousTime)
        } else {
            mViewModel.selectedMonth = MonthType.CUR_MONTH

            mBinding.curMonth.visibility = View.VISIBLE

            mBinding.curMonth.setBackgroundResource(R.drawable.download_oval_hint_up)
            mBinding.curMonth.text = formatMonthText.format(curTime)
            mBinding.year.text = formatYearText.format(curTime)
        }

        mBinding.nextMonth.setOnClickListener { v ->
            if (mViewModel.selectedMonth == MonthType.NEXT_MONTH) {
                return@setOnClickListener
            }

            mViewModel.selectedMonth = MonthType.NEXT_MONTH
            mViewModel.initDate()

            mBinding.nextMonth.setBackgroundResource(R.drawable.download_oval_hint_up)
            mBinding.nextMonth.setTextColor(Color.WHITE)

            mBinding.curMonth.setBackgroundColor(0)
            mBinding.curMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.previousMonth.setBackgroundColor(0)
            mBinding.previousMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.year.text = formatYearText.format(previousTime)
        }

        mBinding.curMonth.setOnClickListener { v ->
            if (mViewModel.selectedMonth == MonthType.CUR_MONTH) {
                return@setOnClickListener
            }

            mViewModel.selectedMonth = MonthType.CUR_MONTH
            mViewModel.initDate()

            mBinding.curMonth.setBackgroundResource(R.drawable.download_oval_hint_up)
            mBinding.curMonth.setTextColor(Color.WHITE)

            mBinding.nextMonth.setBackgroundColor(0)
            mBinding.nextMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.previousMonth.setBackgroundColor(0)
            mBinding.previousMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.year.text = formatYearText.format(curTime)
        }

        mBinding.previousMonth.setOnClickListener { v ->
            if (mViewModel.selectedMonth == MonthType.PREVIOUS_MONTH) {
                return@setOnClickListener
            }

            mViewModel.selectedMonth = MonthType.PREVIOUS_MONTH
            mViewModel.initDate()

            mBinding.previousMonth.setBackgroundResource(R.drawable.download_oval_hint_up)
            mBinding.previousMonth.setTextColor(Color.WHITE)

            mBinding.nextMonth.setBackgroundColor(0)
            mBinding.nextMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.curMonth.setBackgroundColor(0)
            mBinding.curMonth.setTextColor(R.color.text_title.toColor(this))
            mBinding.year.text = formatYearText.format(curTime)
        }

        if (SPUtils.getBoolean("showServersDetailHint", true)) {
            showHintDialog()
        }
    }

    private fun showHintDialog() {
        val contentView = LayoutInflater.from(this).inflate(R.layout.dialog_servers_calendear_detail_hint, null)
        val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, resources.displayMetrics.heightPixels)
        val dialog = Dialog(this, R.style.DialogWindowTransparent)
        dialog.setContentView(contentView, params)
        dialog.setCancelable(false)
        dialog.show()

        contentView.findViewById<View>(R.id.confirm).setOnClickListener {
            dialog.dismiss()
            SPUtils.setBoolean("showServersDetailHint", false)
        }
    }


    private fun showServersDetailDialog(calendarEntity: CalendarEntity) {
        val contentView = LayoutInflater.from(this).inflate(R.layout.dialog_servers_calendear_detail, null)
        val params = ViewGroup.LayoutParams(resources.displayMetrics.widthPixels, ViewGroup.LayoutParams.WRAP_CONTENT)
        val dialog = Dialog(this, R.style.DialogWindowTransparent)
        val window = dialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        dialog.setContentView(contentView, params)
        dialog.show()

        val calendarHint = contentView.findViewById<TextView>(R.id.calendar_hint)
        calendarHint.text = (calendarEntity.server.first().getFormatTime("MM-dd") + "详细开服")

        val addBtn = contentView.findViewById<View>(R.id.add)
        if (mViewModel.meEntity?.isPartTime == true) {
            addBtn.visibility = View.INVISIBLE
        } else {
            addBtn.visibility = View.GONE
        }

        val feedback = contentView.findViewById<TextView>(R.id.feedback)
        feedback.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        feedback.paint.isAntiAlias = true
        if (mViewModel.meEntity?.isPartTime == true) {
            feedback.text = "新增"
        } else {
            feedback.text = "有奖反馈"
        }

        feedback.setOnClickListener {
            if (mViewModel.meEntity?.isPartTime == true) {
                startActivityForResult(
                    AddKaiFuActivity.getIntent(
                        this,
                        mViewModel.serverCalendarLiveData.value!!.last(),
                        mViewModel.serverCalendarLiveData.value as ArrayList<ServerCalendarEntity>,
                        mViewModel.game.id, calendarEntity.server.first().getTime() * 1000
                    ), GAME_DETAIL_ADD_KAIFU_REQUEST
                )
            } else {
                val feedbackTime = if (calendarEntity.server.isNotEmpty()) {
                    calendarEntity.server[0].getFormatTime("yyyy年M月d日")
                } else {
                    throwExceptionInDebug("server data is null")
                    ""
                }
                HelpAndFeedbackBridge.startSuggestionActivity(
                    this,
                    SuggestType.normal,
                    "service",
                    StringUtils.buildString(mViewModel.game.name, "，", feedbackTime, "开服信息有误：")
                )
            }
        }

        contentView.findViewById<View>(R.id.close).setOnClickListener {
            dialog.dismiss()
        }

        val recyclerView = contentView.findViewById<RecyclerView>(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = object : BaseRecyclerAdapter<ServersDetailViewHolder>(this) {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ServersDetailViewHolder {
                val view = mLayoutInflater.inflate(R.layout.dialog_servers_calendear_detail_item, parent, false)
                return ServersDetailViewHolder(DialogServersCalendearDetailItemBinding.bind(view))
            }

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

            override fun onBindViewHolder(holder: ServersDetailViewHolder, position: Int) {
                val data = calendarEntity.server[position]
                holder.bindItem(data, mViewModel.meEntity, mViewModel.game)

                if (mViewModel.meEntity?.isPartTime == true) {
                    holder.binding.add.visibility = View.VISIBLE
                } else {
                    holder.binding.add.visibility = View.GONE
                }
                holder.binding.add.setOnClickListener {
                    startActivityForResult(
                        AddKaiFuActivity.getIntent(
                            this@ServersCalendarActivity,
                            data,
                            mViewModel.serverCalendarLiveData.value as ArrayList<ServerCalendarEntity>,
                            mViewModel.game.id,
                            mViewModel.getSelectTime(calendarEntity.day, calendarEntity.month, calendarEntity.year)
                        ), ServersCalendarActivity.GAME_DETAIL_ADD_KAIFU_REQUEST
                    )
                }
                if (itemCount == position + 1) {
                    holder.itemView.setPadding(0, 5F.dip2px(), 0, 19F.dip2px())
                } else {
                    holder.itemView.setPadding(0, 5F.dip2px(), 0, 5F.dip2px())
                }
            }
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(R.color.background_white, R.color.background_white)
        mBinding.root.setRootBackgroundColor(R.color.background)
        mBinding.hint.setBackgroundColor(R.color.background.toColor(this))
        mBinding.hint.setTextColor(R.color.text_subtitleDesc.toColor(this))
        mBinding.contentContainer.setBackgroundColor(R.color.background_white.toColor(this))
        mBinding.divider.setBackgroundColor(R.color.background.toColor(this))
        mBinding.dividerLine1.setBackgroundColor(R.color.background.toColor(this))
        mBinding.dividerLine2.setBackgroundColor(R.color.background.toColor(this))
        mBinding.year.setTextColor(R.color.text_title.toColor(this))
        mBinding.recyclerView.recycledViewPool.clear()
        mBinding.recyclerView.adapter?.notifyItemRangeChanged(0, mBinding.recyclerView.adapter?.itemCount ?: 0)
    }

    companion object {
        const val GAME_DETAIL_PATCH_KAIFU_REQUEST = 51
        const val GAME_DETAIL_ADD_KAIFU_REQUEST = 50
        const val GAME_DETAIL_ADD_KAIFU_KEY = "GAME_DETAIL_ADD_KAIFU_KEY"
        const val GAME_DETAIL_PATCH_KAIFU_KEY = "GAME_DETAIL_PATCH_KAIFU_KEY"

        fun getIntent(context: Context, game: GameEntity, gameServer: GameDetailServer, me: MeEntity?): Intent {
            val intent = Intent(context, ServersCalendarActivity::class.java)
            intent.putExtra(GameEntity::class.java.simpleName, game)
            intent.putExtra(GameDetailServer::class.java.simpleName, gameServer)
            intent.putExtra(MeEntity::class.java.simpleName, me)
            return intent
        }
    }
}