package com.example.defenseapplication.liveVideo

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.defenseapplication.bean.DeviceBean
import com.example.defenseapplication.databinding.VoiceSettingsActivityBinding
import com.example.defenseapplication.utils.ApiService
import com.example.defenseapplication.utils.DeviceIdEvent
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 VoiceSettingsActivity : AppCompatActivity() {

    private lateinit var binding: VoiceSettingsActivityBinding
    private lateinit var apiService: ApiService
    private var deviceId: String? = null
    private var originalAlertAudio: String? = null
    private var originalAudioContent: String? = null

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

        apiService = RetrofitNetwork.getNetworkService()

        // ImmersionBar核心调用,沉浸式
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()

        // 获取设备ID
        deviceId = DeviceIdEvent.getDeviceId()

        // 从 Intent 获取设备数据
        originalAlertAudio = intent.getStringExtra("alertAudio") ?: "1"
        originalAudioContent = intent.getStringExtra("audioContent") ?: ""
        
        // 设置Switch状态：0->false，1->true
        binding.swWarningVoice.isChecked = originalAlertAudio == "1"

        binding.swWarningVoice.setOnCheckedChangeListener { _, isChecked ->
            // 开关状态变化时不立即请求，仅记录状态
        }

        binding.rlWarningContent.setOnClickListener {
            val intent = Intent(this, WarningVoiceContentActivity::class.java)
            // 传递设备数据给警告语音内容页面
            intent.putExtra("deviceId", deviceId)
            intent.putExtra("audioContent", originalAudioContent)
            startActivityForResult(intent, 1001)
        }

        binding.ivBack.setOnClickListener {
            // 点击返回时触发修改设备请求
            updateDeviceAlertAudio()
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            // 获取从警告语音内容页面返回的音频内容
            val newAudioContent = data?.getStringExtra("result")
            originalAudioContent = newAudioContent
            Log.d("WarningVoiceContentActivity", "newAudioContent: $newAudioContent")
            if (newAudioContent != null) {}
        }
    }

    private fun updateDeviceAlertAudio() {
        deviceId?.let { id ->
            val newAlertAudio = if (binding.swWarningVoice.isChecked) "1" else "0"
            // 只有状态发生变化时才请求
            if (newAlertAudio != originalAlertAudio) {
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val deviceBean = DeviceBean(id = id, alertAudio = newAlertAudio)
                        val response = apiService.updateDeviceInfo(deviceBean)
                        withContext(Dispatchers.Main) {
                            if (response.code == 200 && response.data != null) {
                                Toast.makeText(this@VoiceSettingsActivity, "修改成功", Toast.LENGTH_SHORT).show()
                            } else {
                                Toast.makeText(this@VoiceSettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                            }
                            finish()
                        }
                    } catch (e: Exception) {
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@VoiceSettingsActivity, "修改失败", Toast.LENGTH_SHORT).show()
                            finish()
                        }
                    }
                }
            } else {
                finish()
            }
        }
    }
}