package com.cheng.blzb.ui.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.DialogFragment
import com.example.base.common.RxCountDown
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.utils.RegexUtils
import com.example.base.utils.ScreenUtils
import com.cheng.blzb.R
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.DialogBindPhoneBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.utils.KeyboardUtils
import io.reactivex.rxjava3.disposables.Disposable

class BindPhoneDialog : DialogFragment(), KeyboardUtils.OnSoftInputChangedListener {
    private var mOnBackListener: ((String, String, String) -> Unit)? = null     //回调事件
    private var mOnSendCodeClickListener:((String) -> Unit)? = null

    private var disposable: Disposable? = null
    private var timestamp = ""

    lateinit var binding: DialogBindPhoneBinding

    override fun onStart() {
        super.onStart()
        val window = dialog?.window
        val windowParams = window?.attributes
        windowParams?.dimAmount = 0.7f
        windowParams?.width = ScreenUtils.getWindowSize().x
        windowParams?.gravity = Gravity.BOTTOM
        windowParams?.windowAnimations = R.style.dialog_bottom
        dialog?.window?.attributes = windowParams
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        setCancelable(false)
        KeyboardUtils.registerSoftInputChangedListener(requireActivity(), this)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private val textWatcher = object : TextWatcherImpl() {
        @SuppressLint("SetTextI18n")
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            binding.ivClearText.visibility = if (TextUtils.isEmpty(s)) View.GONE else View.VISIBLE
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = layoutInflater.inflate(R.layout.dialog_bind_phone, null)

        binding = DialogBindPhoneBinding.bind(view)

        binding.tvTitle.typeface = Constants.douyinsansB

        binding.etPhone.addTextChangedListener(textWatcher)

        binding.ivClose.onClick {
            dismiss()
        }
        binding.ivClearText.onClick {
            binding.etPhone.setText("")
        }
        binding.tvSendCode.onClick {
            val phone = binding.etPhone.text?.trim().toString()
            if (TextUtils.isEmpty(phone)) {
                toast("请输入手机号")
                return@onClick
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                toast("请输入正确的手机号")
                return@onClick
            }
            mOnSendCodeClickListener?.invoke(phone)
        }
        binding.btnNext.onClick {
            val phone = binding.etPhone.text?.trim().toString()
            val code = binding.etCode.text?.trim().toString()
            if (TextUtils.isEmpty(phone)) {
                toast("请输入手机号")
                return@onClick
            }
            if (!RegexUtils.isMobileSimple(phone)) {
                toast("请输入正确的手机号")
                return@onClick
            }
            if (TextUtils.isEmpty(code)) {
                toast("请输入验证码")
                return@onClick
            }
            mOnBackListener?.invoke(phone, code, timestamp)
            dismiss()
        }

        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        return dialog
    }

    @SuppressLint("SetTextI18n")
    private fun startTimer() {
        disposable?.dispose()
        disposable = RxCountDown.countdown(60).subscribe {
            if (it > 0) {
                binding.tvSendCode.text = "${it}s"
                binding.tvSendCode.isEnabled = false
                binding.tvSendCode.alpha = 0.5f
            } else {
                binding.tvSendCode.text = "重新发送"
                binding.tvSendCode.isEnabled = true
                binding.tvSendCode.alpha = 1f
            }
        }
    }

    fun setOnSendCodeClickListener(listener: (String) -> Unit) {
        mOnSendCodeClickListener = listener
    }

    fun setOnBackListener(listener: (String, String, String) -> Unit) {
        mOnBackListener = listener
    }

    fun setTimestamp(timestamp:String) {
        this.timestamp = timestamp
        startTimer()
    }

    override fun onSoftInputChanged(height: Int) {
        val lp = binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams
        lp.bottomMargin = height
        binding.layoutContent.layoutParams = lp
    }

    override fun onDestroyView() {
        KeyboardUtils.unregisterSoftInputChangedListener(requireActivity().window)
        binding.etPhone.removeTextChangedListener(textWatcher)
        super.onDestroyView()
    }

    companion object {
        fun newInstance(): BindPhoneDialog {
            val arg = Bundle()
            val fragment = BindPhoneDialog()
            fragment.arguments = arg
            return fragment
        }
    }
}