package com.miya.fastcashier.ui.dialog

import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.*
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.miya.fastcashier.databinding.DialogAuthorizePasswordInputBinding
import com.miya.fastcashier.ui.BaseActivity
import com.miya.fastcashier.ui.RefundActivity
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.dp2px
import com.miya.fastcashier.utils.manage.AccountPasswordManageKit

class AuthorizePasswordInputDialog : DialogFragment(), View.OnClickListener {

    private lateinit var viewBinding: DialogAuthorizePasswordInputBinding
    private var callback: OnAuthorizedFinishListener? = null

    companion object {

        fun newInstance(): AuthorizePasswordInputDialog {
            return AuthorizePasswordInputDialog()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewBinding = DialogAuthorizePasswordInputBinding.inflate(inflater)
        viewBinding.ivClose.setOnClickListener(this)
        viewBinding.tvConfirm.setOnClickListener(this)
        viewBinding.etPassword.apply {
            afterTextChanged {
                viewBinding.tvError.visibility = View.GONE
            }
        }
        viewBinding.tvConfirm.alpha = 0.5f
        viewBinding.tvConfirm.isEnabled = false
        return viewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val window = dialog!!.window!!
        window.setDimAmount(0.0f)

        super.onViewCreated(view, savedInstanceState)
        window.setBackgroundDrawable(ColorDrawable(0x191919))
        window.setGravity(Gravity.BOTTOM)
        window.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            context?.let { dp2px(it, 637f) }!!
        )
        showView()
    }

    fun showView() {
        dialog!!.window!!.setDimAmount(0.7f)
        viewBinding.container.visibility = View.VISIBLE
    }

    override fun onClick(view: View?) {
        when (view) {
            viewBinding.ivClose -> dismissAllowingStateLoss()
            viewBinding.tvConfirm -> checkAuthorizePassword()
        }
    }

    private fun checkAuthorizePassword() {
        val inputPassword = viewBinding.etPassword.text.toString()

        if (TextUtils.isEmpty(inputPassword)) {
            context?.let { CenterToasty.error(it, "请输入授权密码").show() }
            return
        }

        val accountPassword = AccountPasswordManageKit.get().accountPassword
        if (TextUtils.isEmpty(accountPassword)) {
            AccountPasswordManageKit.get().loadAccountPassword(context as AppCompatActivity,
                object : AccountPasswordManageKit.AccountPasswordManageCallback {
                    override fun onPasswordGet(password: String?) {
                        password?.let { checkPasswordAndDoNext(it, inputPassword) }
                    }
                })
        } else {
            checkPasswordAndDoNext(accountPassword, inputPassword)
        }
    }

    private fun checkPasswordAndDoNext(accountPassword: String, password: String) {
        if (!accountPassword.equals(password)) {
            viewBinding.tvError.visibility = View.VISIBLE
        } else {
            if (null != callback){
                callback!!.onAuthorizedFinished(true)
                dismissAllowingStateLoss()
                return
            }
            RefundActivity.start(context as BaseActivity)
            dismissAllowingStateLoss()
        }
    }

    private fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
        this.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable?) {
                afterTextChanged.invoke(editable.toString())

                val password = viewBinding.etPassword.text.toString()
                if (TextUtils.isEmpty(password)) {
                    viewBinding.tvConfirm.alpha = 0.5f
                    viewBinding.tvConfirm.isEnabled = false
                } else {
                    viewBinding.tvConfirm.alpha = 1.0f
                    viewBinding.tvConfirm.isEnabled = true
                }
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        })
    }

    fun show(manager: FragmentManager, tag: String?, callback: OnAuthorizedFinishListener) {
        this.callback = callback
        super.show(manager, tag)
    }

    interface OnAuthorizedFinishListener {
        fun onAuthorizedFinished(isSucceed: Boolean)
    }
}