package com.example.defenseapplication.liveVideo

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.example.defenseapplication.R
import com.example.defenseapplication.base.BaseActivity
import com.example.defenseapplication.bean.DeviceUserBean
import com.example.defenseapplication.databinding.SettingsActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.LanguageUtil
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.example.defenseapplication.view.RecognitionModeDialog
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
//设置页面
class SettingsActivity : BaseActivity() {

    private lateinit var binding: SettingsActivityBinding
    private var alertAudio: String? = null
    private var audioContent: String? = null

    override fun onResume() {
        super.onResume()
        fetchDeviceInfo()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = SettingsActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // ImmersionBar核心调用,沉浸式
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()
        binding.itemVoiceSetting.setOnClickListener {
            val intent = Intent(this, VoiceSettingsActivity::class.java)
            intent.putExtra("alertAudio", alertAudio ?: "1")
            intent.putExtra("audioContent", audioContent ?: "")
            startActivity(intent)
        }
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.itemRecognitionMode.setOnClickListener {
            val dialog = RecognitionModeDialog(this)
            dialog.setOnConfirmListener { mode ->
                updateRecognitionMode(mode)
            }
            dialog.show()
        }

        binding.itemDeviceName.setOnClickListener {
            val dialog = CustomDialogFragmentText()
                .setTitle(getString(R.string.device_name))
                .setInputText(binding.tvDeviceName.text.toString())
            dialog.setOnConfirmListener { name ->
                updateDeviceName(name)
            }
            dialog.show(supportFragmentManager, "CustomDialogFragment")
        }

        binding.itemUnbindDevice.setOnClickListener {
            val dialog = CustomDialogFragmentText()
                .setTitle(getString(R.string.tip))
                .setMessage(getString(R.string.logout_confirm))
                .setNegativeText(getString(R.string.cancel))
                .setPositiveText(getString(R.string.confirm))
                .setShowInput(false)
            dialog.setOnConfirmListener {
                unbindDevice()
            }
            dialog.show(supportFragmentManager, "CustomDialogFragment")
        }
        binding.itemWaterGunSetting.setOnClickListener {
            val intent = Intent(this, WaterGunSettingsActivity::class.java)
            // 传递水枪设置参数
            val deviceId = DeviceIdEvent.getDeviceId()
            if (!deviceId.isNullOrEmpty()) {
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val response = RetrofitNetwork.getNetworkService().getDeviceInfo(deviceId)
                        withContext(Dispatchers.Main) {
                            if (response.code == 200 && response.data != null) {
                                val device = response.data
                                intent.putExtra("strikeRange", device.strikeRange ?: "7")
                                intent.putExtra("strikeInterval", device.strikeInterval ?: "3")
                                intent.putExtra("container", device.container ?: "容器4")
                                startActivity(intent)
                            } else {
                                // 如果获取失败，使用默认值
                                intent.putExtra("strikeRange", "7")
                                intent.putExtra("strikeInterval", "3")
                                intent.putExtra("container", "容器4")
                                startActivity(intent)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        withContext(Dispatchers.Main) {
                            intent.putExtra("strikeRange", "7")
                            intent.putExtra("strikeInterval", "3")
                            intent.putExtra("container", "容器4")
                            startActivity(intent)
                        }
                    }
                }
            } else {
                intent.putExtra("strikeRange", "7")
                intent.putExtra("strikeInterval", "3")
                intent.putExtra("container", "容器4")
                startActivity(intent)
            }
        }
        binding.itemAutoMode.setOnClickListener {
            val intent = Intent(this, AutoModeActivity::class.java)
            startActivity(intent)
        }
        binding.itemDeviceInfo.setOnClickListener {
            val intent = Intent(this, DeviceInfoActivity::class.java)
            startActivity(intent)
        }
        // 关联用户
        binding.itemRelatedUsers.setOnClickListener {
            val intent = Intent(this, LinkedUserActivity::class.java)
            intent.putExtra(LinkedUserActivity.EXTRA_MODE, LinkedUserActivity.MODE_SETTINGS)
            startActivity( intent)
        }
        binding.itemWifiManage.setOnClickListener {
            val intent = Intent(this, WiFiManagementActivity::class.java)
            intent.putExtra("wifi_name", binding.tvWifiName.text.toString())
            startActivity(intent)
        }
    }

    private fun fetchDeviceInfo() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            try {
                val deviceResponse = RetrofitNetwork.getNetworkService().getDeviceInfo(deviceId)
                withContext(Dispatchers.Main) {
                    if (deviceResponse.code == 200 && deviceResponse.data != null) {
                        updateDeviceInfo(deviceResponse.data)
                    } else {
                        Toast.makeText(this@SettingsActivity, deviceResponse.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@SettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }

        fetchDeviceUserList()
    }

    private fun fetchDeviceUserList() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            return
        }

        lifecycleScope.launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getDeviceUserList(deviceId)
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        updateRelatedUsersCount(response.data.size)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun updateRelatedUsersCount(count: Int) {
        binding.tvRelatedUsers.text = "$count 人"
    }

    private fun updateDeviceInfo(device: com.example.defenseapplication.bean.DeviceBean) {
        binding.tvDeviceName.text = device.deviceName ?: "未设置"
        binding.tvWifiName.text = device.wifiName ?: "未设置"
        
        // 保存告警音频和内容数据，用于传递给 VoiceSettingsActivity
        alertAudio = device.alertAudio
        audioContent = device.audioContet
        
        val serverMode = device.patternPerception
        val cacheMode = getCachedRecognitionMode()
        
        binding.tvRecognitionMode.text = when {
            !serverMode.isNullOrEmpty() -> {
                val displayMode = when (serverMode) {
                    "0" -> getString(R.string.bluetooth_recognition)
                    "1" -> getString(R.string.bluetooth_face_recognition)
                    else -> serverMode
                }
                saveRecognitionMode(displayMode)
                displayMode
            }
            !cacheMode.isNullOrEmpty() -> cacheMode
            else -> getString(R.string.bluetooth_recognition)
        }
        
        device.workMode?.let { workMode ->
            binding.tvAutoMode.text = when (workMode) {
                "0" -> getString(R.string.full_auto_mode)
                "1" -> getString(R.string.semi_auto_mode)
                else -> getString(R.string.full_auto_mode)
            }
        }
    }

    private fun getCachedRecognitionMode(): String? {
        val sp = getSharedPreferences("DeviceSettings", Context.MODE_PRIVATE)
        return sp.getString("recognition_mode", null)
    }

    private fun saveRecognitionMode(mode: String) {
        val sp = getSharedPreferences("DeviceSettings", Context.MODE_PRIVATE)
        sp.edit().putString("recognition_mode", mode).apply()
    }

    private fun updateDeviceName(name: String) {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = com.example.defenseapplication.bean.DeviceBean(
                    id = deviceId,
                    deviceName = name,
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        binding.tvDeviceName.text = name
                        Toast.makeText(this@SettingsActivity, "修改成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@SettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@SettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateRecognitionMode(mode: String) {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        val patternPerception = when (mode) {
            getString(R.string.bluetooth_recognition) -> "0"
            getString(R.string.bluetooth_face_recognition) -> "1"
            else -> "0"
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = com.example.defenseapplication.bean.DeviceBean(
                    id = deviceId,
                    patternPerception = patternPerception,
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        binding.tvRecognitionMode.text = mode
                        saveRecognitionMode(mode)
                        Toast.makeText(this@SettingsActivity, "修改成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@SettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@SettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun unbindDevice() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deleteBean = com.example.defenseapplication.bean.DeleteBean()
                deleteBean.deviceId = deviceId
                val response = RetrofitNetwork.getNetworkService().deleteDevice(deleteBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        Toast.makeText(this@SettingsActivity, "解绑成功", Toast.LENGTH_SHORT).show()
                        val intent = Intent(this@SettingsActivity, com.example.defenseapplication.home.HomeActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                        startActivity(intent)
                        finish()
                    } else {
                        Toast.makeText(this@SettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@SettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}
