package com.gh.gamecenter.servers.add

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.contrarywind.view.WheelView
import com.gh.gamecenter.common.base.activity.ToolBarActivity
import com.gh.common.databind.AddKaiFuBindingAdapter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.common.util.HaloWheelViewAdapter
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.updateStatusBarColor
import com.gh.gamecenter.databinding.ActivityKaifuAddBinding
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.gamedetail.fuli.kaifu.ServersCalendarActivity
import java.util.*
import kotlin.collections.HashMap
import kotlin.math.abs


class AddKaiFuActivity : ToolBarActivity() {
    private val TWO_MONTH_TIME = 5184000000

    private val mPickerMinutes = intArrayOf(0, 5, 10, 20, 30, 40, 50)

    private var mBinding: ActivityKaifuAddBinding? = null

    private var mViewModel: AddKaiFuViewModel? = null

    private var mSelectTime: Long? = null

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        setNavigationTitle("新增开服")
        mSelectTime = intent.getLongExtra(EntranceConsts.KEY_KAIFU_SELECT_TIME, 0)

        // initViewModel
        mViewModel = ViewModelProviders.of(this).get(AddKaiFuViewModel::class.java)
        mViewModel?.initData(
            intent.getParcelableExtra(ServerCalendarEntity.TAG) ?: ServerCalendarEntity(),
            intent.getParcelableArrayListExtra(EntranceConsts.KEY_KAIFU_LIST) ?: arrayListOf(),
            intent.getStringExtra(EntranceConsts.KEY_GAMEID) ?: ""
        )
        mViewModel?.postResult?.observe(this, androidx.lifecycle.Observer { it ->
            if (it == null) {
                toast(R.string.post_failure_hint)
            } else {
                val intent = Intent()
                intent.putParcelableArrayListExtra(ServersCalendarActivity.GAME_DETAIL_ADD_KAIFU_KEY, it)
                setResult(Activity.RESULT_OK, intent)
                toast("提交成功")
                finish()
            }
        })

        // initView
        mBinding = ActivityKaifuAddBinding.bind(mContentView)
        mBinding?.kaifuAddContainer?.let {
            AddKaiFuBindingAdapter.addKaiFuView(
                it, mViewModel?.calendarList
            ) { view: View, position: Any ->
                if (position is Int) {
                    if (position == 0) {
                        when (view.id) {
                            R.id.kaifu_add_first_name -> { // 自动填充->名字
                                mViewModel?.copyLastFirstNameToNext()
                            }
                            R.id.kaifu_add_server_name -> {
                                mViewModel?.copyLastFirstAndServerNameToNext()
                            }
                            R.id.kaifu_add_time -> { // 自动填充->时间
                                mViewModel?.copyTimeToNext()
                            }
                        }
                    } else if (view.id == R.id.kaifu_add_time) {
                        showDataPicker { data: Date?, _ ->
                            run {
                                if (data == null) {
                                    mViewModel?.calendarList!![position].setTime(0)
                                } else {
                                    val cal = Calendar.getInstance().apply { time = data }
                                    cal.set(Calendar.MINUTE, mPickerMinutes[cal.get(Calendar.MINUTE)])
                                    mViewModel?.calendarList!![position].setTime(cal.time.time / 1000)
                                }
                            }
                        }
                    }
                }
            }
        }
        mBinding?.addPost?.setOnClickListener {
            mViewModel?.post(this)
        }
    }

    private fun getMinuteIndex(curMinute: Int): Int {
        val offsetMap = HashMap<Int, Int>()
        for (i in mPickerMinutes.indices) {
            offsetMap[abs(mPickerMinutes[i] - curMinute)] = i
        }
        return offsetMap[Collections.min(offsetMap.keys)] ?: 0
    }

    // 时间选择器:项目地址 ->https://github.com/Bigkoo/Android-PickerView/
    private fun showDataPicker(timeSelectListener: OnTimeSelectListener) {
        val selectedDate = Calendar.getInstance()
        if (mSelectTime == null || mSelectTime == 0L) {
            selectedDate.time = Date(System.currentTimeMillis())
        } else {
            val curCalendar = Calendar.getInstance()
            curCalendar.time = Date(System.currentTimeMillis())

            val calendar = Calendar.getInstance()
            calendar.time = Date(mSelectTime ?: 0L)
            calendar[Calendar.HOUR] = curCalendar[Calendar.HOUR]
            calendar[Calendar.MINUTE] = curCalendar[Calendar.MINUTE]
            selectedDate.time = Date(calendar.time.time)
        }

        val minuteIndex = getMinuteIndex(selectedDate.get(Calendar.MINUTE))
        selectedDate.set(Calendar.MINUTE, minuteIndex)

        val startDate = Calendar.getInstance()
        val endDate = Calendar.getInstance()
        startDate.time = Date(System.currentTimeMillis() - TWO_MONTH_TIME)
        endDate.time = Date(System.currentTimeMillis() + TWO_MONTH_TIME)
        val pvTime = TimePickerBuilder(this, timeSelectListener)
            .setType(booleanArrayOf(true, true, true, true, true, false))
            .setCancelText("取消")
            .setSubmitText("确定")
            .setTitleSize(15)
            .setOutSideCancelable(false)
            .isCyclic(false)
            .setSubmitColor(com.gh.gamecenter.common.R.color.text_theme.toColor(this))
            .setCancelColor(com.gh.gamecenter.common.R.color.hint.toColor(this))
            .setTitleBgColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(this))
            .setBgColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(this))
            .setDate(selectedDate)
            .setRangDate(startDate, endDate)
            .setLabel("年", "月", "日", "时", "分", "")
            .isCenterLabel(false)
            .isDialog(true)
            .setContentTextSize(15)
            .build()

        val dialog = pvTime.dialog

//         强制更改 MinuteWheelView 的内容
//         注意：选择后的数据minute其实是mPickerMinutes的position，需要在回调时对返回的date数据进行转换
        val minuteWheelView = dialog.findViewById<WheelView>(com.bigkoo.pickerview.R.id.min)
        minuteWheelView.adapter = HaloWheelViewAdapter(mPickerMinutes)

        if (dialog != null) {
            val params = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM
            )
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime.dialogContainerLayout.layoutParams = params
            val dialogWindow = dialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)
                dialogWindow.setGravity(Gravity.BOTTOM)
            }
            val cancelText = dialog.findViewById<TextView>(com.bigkoo.pickerview.R.id.btnCancel)
            val text = "取消     清空"
            val spannableString = SpannableString(text)
            spannableString.setSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    timeSelectListener.onTimeSelect(null, null)
                }
            }, text.length - 2, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

            cancelText.text = spannableString
            cancelText.movementMethod = LinkMovementMethod.getInstance()

            dialog.show()
        }
    }

    override fun isAutoResetViewBackgroundEnabled() = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
        mBinding?.run {
            root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(this@AddKaiFuActivity))
            container.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(this@AddKaiFuActivity))
            kaifuAddContainer.run {
                for (i in 1 until childCount) {
                    (getChildAt(i) as? LinearLayout)?.run {
                        for (j in 0 until childCount) {
                            (getChildAt(j) as? EditText)?.run {
                                AddKaiFuBindingAdapter.kaiFuTextColor(
                                    this,
                                    mViewModel?.calendarList?.safelyGetInRelease(i - 1)?.getDataMark() ?: 0,
                                    i - 1
                                )
                            }
                        }
                    }
                }
            }
        }
    }

    companion object {
        fun getIntent(
            context: Context, entity: ServerCalendarEntity,
            kaifuList: ArrayList<ServerCalendarEntity>,
            gameId: String,
            selectTime: Long
        ): Intent {
            val intent = Intent(context, AddKaiFuActivity::class.java)
            intent.putExtra(ServerCalendarEntity.TAG, entity)
            intent.putExtra(EntranceConsts.KEY_GAMEID, gameId)
            intent.putParcelableArrayListExtra(EntranceConsts.KEY_KAIFU_LIST, kaifuList)
            intent.putExtra(EntranceConsts.KEY_KAIFU_SELECT_TIME, selectTime)
            return intent
        }
    }
}
