package com.example.defenseapplication.personal

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.SPUtils
import com.example.defenseapplication.R
import com.example.defenseapplication.bean.UpdateUserInfo
import com.example.defenseapplication.databinding.OperationPasswordActivityBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//操作密码
class OperationPasswordActivity : AppCompatActivity() {

    private lateinit var binding: OperationPasswordActivityBinding

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

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

        initListener()
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.swOperationPassword.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    binding.etPassword.isEnabled = true
                    binding.etConfirmPassword.isEnabled = true
                    Toast.makeText(this, getString(R.string.operation_password_enabled), Toast.LENGTH_SHORT).show()
                }
                false -> {
                    CoroutineScope(Dispatchers.IO).launch {
                        try {
                            val response = RetrofitNetwork.getNetworkService().updateUserInfo(UpdateUserInfo(optionPassword = ""))
                            withContext(Dispatchers.Main) {
                                if (response.code == 200) {
                                    binding.etPassword.isEnabled = false
                                    binding.etConfirmPassword.isEnabled = false
                                    SPUtils.getInstance().remove("operation_password")
                                    Toast.makeText(this@OperationPasswordActivity, getString(R.string.operation_password_disabled), Toast.LENGTH_SHORT).show()
                                    finish()
                                } else {
                                    binding.swOperationPassword.isChecked = true
                                    Toast.makeText(this@OperationPasswordActivity, response.msg ?: "操作失败", Toast.LENGTH_SHORT).show()
                                }
                            }
                        } catch (e: Exception) {
                            withContext(Dispatchers.Main) {
                                binding.swOperationPassword.isChecked = true
                                Toast.makeText(this@OperationPasswordActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
            }
        }

        binding.etPassword.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) {}

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.etConfirmPassword.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) {}

            override fun afterTextChanged(s: Editable?) {
            }
        })

        binding.btnConfirmReset.setOnClickListener {
            val password = binding.etPassword.text.toString()
            val confirmPassword = binding.etConfirmPassword.text.toString()

            if (password.isEmpty()) {
                Toast.makeText(this, getString(R.string.password_cannot_empty), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (password.length != 6) {
                Toast.makeText(this, getString(R.string.password_must_be_6_digits), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (confirmPassword.isEmpty()) {
                Toast.makeText(this, getString(R.string.please_confirm_password), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (password != confirmPassword) {
                Toast.makeText(this, getString(R.string.password_mismatch), Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            binding.btnConfirmReset.isEnabled = false

            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val response = RetrofitNetwork.getNetworkService().updateUserInfo(UpdateUserInfo(optionPassword = password))
                    withContext(Dispatchers.Main) {
                        binding.btnConfirmReset.isEnabled = true
                        if (response.code == 200) {
                            SPUtils.getInstance().put("operation_password", password)
                            Toast.makeText(this@OperationPasswordActivity, getString(R.string.operation_success), Toast.LENGTH_SHORT).show()
                            finish()
                        } else {
                            Toast.makeText(this@OperationPasswordActivity, response.msg ?: "操作失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        binding.btnConfirmReset.isEnabled = true
                        Toast.makeText(this@OperationPasswordActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
}