package com.gh.common.databind

import android.os.Build
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.gh.gamecenter.R
import com.gh.gamecenter.common.callback.OnViewClickListener
import com.gh.gamecenter.common.databinding.LayoutPopupContainerBinding
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.databinding.KaifuAddItemBinding
import com.gh.gamecenter.databinding.LayoutAddKaifuPopupBinding
import com.gh.gamecenter.feature.entity.ServerCalendarEntity
import com.gh.gamecenter.servers.add.AddKaiFuPopupAdapter
import java.text.SimpleDateFormat
import java.util.*

object AddKaiFuBindingAdapter {
    private var popupWindow: BugFixedPopupWindow? = null

    @JvmStatic
    @BindingAdapter("addKaiFuView", "clickListener")
    fun addKaiFuView(
        view: LinearLayout,
        list: List<ServerCalendarEntity?>?,
        listener: OnViewClickListener<*>?
    ) {
        if (list == null) return
        view.removeAllViews()
        view.addView(LayoutInflater.from(view.context).inflate(R.layout.kaifu_new_add_item_title, null))
        for (i in list.indices) {
            val inflate = LayoutInflater.from(view.context).inflate(R.layout.kaifu_add_item, null)
            val binding = KaifuAddItemBinding.bind(inflate)
            binding.clickListener = listener
            binding.entity = list[i]
            binding.position = i
            binding.isCloseBottom = list.size - 1 == i
            view.addView(inflate)
            binding.kaifuAddFirstName.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) {
                    binding.kaifuAddFirstName.hint = ""
                    if (binding.kaifuAddFirstName.text.isNullOrEmpty()) {
                        showPopupOption(binding.kaifuAddFirstName) {
                            binding.kaifuAddFirstName.setText(it)
                            binding.kaifuAddFirstName.setSelection(it.length)
                        }
                    }
                } else {
                    binding.kaifuAddFirstName.hint = "点击填写"
                }
            }
            binding.kaifuAddServerName.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) {
                    binding.kaifuAddServerName.hint = ""
                } else {
                    binding.kaifuAddServerName.hint = "点击填写"
                }
            }
            binding.kaifuAddFirstName.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    if (!s.isNullOrEmpty()) {
                        popupWindow?.dismiss()
                    }
                }

                override fun afterTextChanged(s: Editable?) {
                }

            })
            if (i == list.size - 1) {
                binding.kaifuAddTime.background = R.drawable.bg_add_kaifu_bottom_left.toDrawable(view.context)
                binding.kaifuAddServerName.background = R.drawable.bg_add_kaifu_bottom_right.toDrawable(view.context)
            }
        }
    }

    @JvmStatic
    @BindingAdapter("addKaiFuTime", "addKaiFuPosition")
    fun addKaiFuTime(view: EditText, time: Long, position: Int) {
        if (time == 0L) {
            view.hint = "点击选择"
            view.setText("")
        } else {
            val pattern = "yyy-MM-dd HH:mm"
            val format = SimpleDateFormat(pattern, Locale.CHINA)
            view.setText(format.format(time * 1000))
            if (position == 0) {
                view.append(
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) Html.fromHtml(
                        String.format(
                            "<font color='#2496FF'>%1\$s</font>",
                            "&nbsp+"
                        ), Html.FROM_HTML_MODE_LEGACY
                    ) else Html.fromHtml(String.format("<font color='#2496FF'>%1\$s</font>", "&nbsp+"))
                )
            }
        }
    }

    @JvmStatic
    @BindingAdapter("kaiFuTextColor", "kaiFuTextPosition")
    fun kaiFuTextColor(view: EditText, dataMark: Int, position: Int) {
        if (dataMark == 1 && view.id == R.id.kaifu_add_time || dataMark == 2 && view.id == R.id.kaifu_add_first_name || dataMark == 3 && view.id == R.id.kaifu_add_server_name || dataMark == 4) {
            view.setTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.secondary_red))
            view.setHintTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.secondary_red))
        } else if (position == 0) {
            view.setTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.hint))
            view.setHintTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.hint))
        } else {
            view.setTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.text_primary))
            view.setHintTextColor(ContextCompat.getColor(view.context, com.gh.gamecenter.common.R.color.hint))
        }
    }

    @JvmStatic
    private fun showPopupOption(view: View, callback: (text: String) -> Unit) {
        val inflater = LayoutInflater.from(view.context)
        val mainBinding = LayoutPopupContainerBinding.inflate(inflater)
        popupWindow = BugFixedPopupWindow(
            mainBinding.root,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val windowPos = IntArray(2)
        val anchorLoc = IntArray(2)
        // 获取锚点View在屏幕上的左上角坐标位置
        view.getLocationOnScreen(anchorLoc)
        val anchorHeight = view.height
        // 获取屏幕的高宽
        val screenHeight = view.context.resources.displayMetrics.heightPixels
        popupWindow?.let { popupWindow ->
            // 测量contentView
            popupWindow.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val windowHeight = popupWindow.contentView.measuredHeight

            // 判断需要向上弹出还是向下弹出显示
            val isNeedShowUp = screenHeight - anchorLoc[1] - anchorHeight < windowHeight
            windowPos[1] = if (isNeedShowUp) {
                anchorLoc[1] - windowHeight
            } else anchorLoc[1] + anchorHeight

            LayoutAddKaifuPopupBinding.inflate(inflater, mainBinding.container, false).apply {
                root.layoutParams = root.layoutParams.apply {
                    width = view.width + 16F.dip2px()
                }
                popupRv.adapter = AddKaiFuPopupAdapter(
                    root.context,
                    arrayListOf("安卓混服", "硬核专服", "官方专服", "官方渠道服", "腾讯QQ服", "腾讯微信服")
                ) {
                    callback.invoke(it)
                    popupWindow.dismiss()
                }
                popupRv.layoutManager = LinearLayoutManager(root.context)
                mainBinding.container.addView(root)
            }

            popupWindow.isTouchable = true
            popupWindow.inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
            popupWindow.isOutsideTouchable = true
            popupWindow.animationStyle = com.gh.gamecenter.common.R.style.popwindow_option_anim_style

            // 设置偏移
            windowPos[1] = windowPos[1] - 12F.dip2px()
            windowPos[0] = anchorLoc[0] - 11F.dip2px()
            popupWindow.showAtLocation(view, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
        }
    }
}