package com.example.defenseapplication.personal

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.PasswordManagementActivityBinding
import com.example.defenseapplication.view.PasswordInputDialog
import com.blankj.utilcode.util.SPUtils
import com.gyf.immersionbar.ImmersionBar
//密码管理
class PasswordManagementActivity : AppCompatActivity() {

    private lateinit var binding: PasswordManagementActivityBinding
    private lateinit var passwordDialog: PasswordInputDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PasswordManagementActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.loginPassword.setOnClickListener {
            startActivity(Intent(this, LoginPasswordActivity::class.java))
        }

        binding.retrievePassword.setOnClickListener {
            startActivity(Intent(this, RetrievePasswordActivity::class.java))
        }

        binding.operationPassword.setOnClickListener {
            showPasswordDialog()
        }
    }

    private fun showPasswordDialog() {
        passwordDialog = PasswordInputDialog(this).apply {
            setOnConfirmListener { inputPassword ->
                val savedPassword = SPUtils.getInstance().getString("operation_password", "111111")
                if (savedPassword.isEmpty()) {
                    Toast.makeText(this@PasswordManagementActivity, getString(R.string.operation_password_not_set), Toast.LENGTH_SHORT).show()
                    dismiss()
                    return@setOnConfirmListener
                }
                if (inputPassword == savedPassword) {
                    startActivity(Intent(this@PasswordManagementActivity, OperationPasswordActivity::class.java))
                    dismiss()
                } else {
                    showError(getString(R.string.password_error))
                    clearPassword()
                }
            }
            setOnDismissListener {
                // Dialog dismissed
            }
        }
        passwordDialog.show()
    }

    override fun onDestroy() {
        if (::passwordDialog.isInitialized) {
            passwordDialog.dismiss()
        }
        super.onDestroy()
    }
}