package com.ypsx.common.app.ext

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.SingleChoiceListener
import com.afollestad.materialdialogs.list.listItemsSingleChoice


private var exitTime: Long = 0
private var clickNum = 1
private val hostMap = mapOf(
    "sit开发环境Host" to "https://sit-cpos.ypshengxian.com/",
    "预发Host" to "https://pre-cpos.ypshengxian.com/",
    "线上正式Host" to "https://cpos.ypshengxian.com/",
)
private val hosts = hostMap.values.toTypedArray()
private val names = hostMap.keys.toList()

@SuppressLint("StaticFieldLeak")
private var materialDialog: MaterialDialog? = null

fun AppCompatActivity.showServerHostExt(host:String,success: (String) -> Unit) {
    if (!this.isFinishing) {
        if (System.currentTimeMillis() - exitTime > 2000) {
            clickNum = 1
            exitTime = System.currentTimeMillis()
        } else {
            exitTime = System.currentTimeMillis()
            clickNum += 1
        }
        if (clickNum >= 5) {
            //选中的host
            val checkHost = host
            var checkedIndex = hosts.indexOf(checkHost)
            if (checkedIndex < 0) checkedIndex = names.size - 1//也就是研发Native那个

            //启用输入的host
            if (materialDialog != null) {
                if (materialDialog!!.isShowing) {
                    materialDialog!!.dismiss()
                    materialDialog = null
                }
            }
            materialDialog = MaterialDialog(this).title(text = "切换Server接口")
                .cancelable(false)
                .cancelOnTouchOutside(false)
                .listItemsSingleChoice(
                    items = names,
                    initialSelection = checkedIndex,
                    selection = object : SingleChoiceListener {
                        override fun invoke(
                            dialog: MaterialDialog,
                            index: Int,
                            text: CharSequence
                        ) {
                            //如果选择了研发native，index就会超过host的index
                            if (index < hosts.size) {
                                success(hosts[index])
                            }
                        }
                    })
                .positiveButton(text = "确定")
                .negativeButton(text = "取消")
            materialDialog!!.show()
        }
    }

}

fun showServerHostPopWindow() {

}
