package com.example.defenseapplication.liveVideo

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import com.example.defenseapplication.bean.DeviceBean
import com.example.defenseapplication.databinding.WarningVoiceContentActivityBinding
import com.example.defenseapplication.utils.ApiService
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 WarningVoiceContentActivity : AppCompatActivity() {

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

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

        apiService = RetrofitNetwork.getNetworkService()

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

        // 从 Intent 获取设备数据（不再发送网络请求）
        deviceId = intent.getStringExtra("deviceId")
        originalAudioContent = intent.getStringExtra("audioContent") ?: ""
        
        // 设置告警内容
        binding.etWarningContent.setText(originalAudioContent)
        // 更新字数统计
        updateWordCount(originalAudioContent?.length ?: 0)

        // 添加文本变化监听
        binding.etWarningContent.doAfterTextChanged { text ->
            val length = text?.length ?: 0
            updateWordCount(length)
        }

        binding.btnBack.setOnClickListener {
            finish()
        }

        binding.btnSave.setOnClickListener {
            // 点击保存时触发修改设备请求
            updateDeviceAudioContent()
        }
    }

    private fun updateDeviceAudioContent() {
        deviceId?.let { id ->
            val newAudioContent = binding.etWarningContent.text.toString().trim()
            // 只有内容发生变化时才请求
            if (newAudioContent != originalAudioContent) {
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val deviceBean = DeviceBean(id = id, audioContet = newAudioContent)
                        val response = apiService.updateDeviceInfo(deviceBean)
                        withContext(Dispatchers.Main) {
                            if (response.code == 200 && response.data != null) {
                                Toast.makeText(this@WarningVoiceContentActivity, "保存成功", Toast.LENGTH_SHORT).show()
                            } else {
                                Toast.makeText(this@WarningVoiceContentActivity, response.msg, Toast.LENGTH_SHORT).show()
                            }
                            val intent = Intent()
                            intent.putExtra("result",newAudioContent)
                            setResult(RESULT_OK, intent)
                            finish()
                        }
                    } catch (e: Exception) {
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@WarningVoiceContentActivity, "保存失败", Toast.LENGTH_SHORT).show()
                            finish()
                        }
                    }
                }
            } else {
                finish()
            }
        }
    }

    private fun updateWordCount(current: Int) {
        binding.tvWordCount.text = "$current/100"
        //字数达到上限时改变颜色
        val color = if (current >= 100) Color.RED else Color.GRAY
        binding.tvWordCount.setTextColor(color)
    }
}
