package com.example.defenseapplication.liveVideo

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import com.example.defenseapplication.R
import com.example.defenseapplication.base.BaseActivity
import com.example.defenseapplication.bean.DeviceBean
import com.example.defenseapplication.databinding.WaterGunSettingsActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.ContainerSelectDialog
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//水枪设置
class WaterGunSettingsActivity : BaseActivity() {

    private lateinit var binding: WaterGunSettingsActivityBinding
    private var deviceId: String? = null
    private var currentStrikeRange: String = "7"
    private var currentStrikeInterval: String = "3"
    private var currentContainer: String = "容器4"

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

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

        deviceId = DeviceIdEvent.getDeviceId()

        // 接收传递过来的参数
        currentStrikeRange = intent.getStringExtra("strikeRange") ?: "7"
        currentStrikeInterval = intent.getStringExtra("strikeInterval") ?: "3"
        currentContainer = intent.getStringExtra("container") ?: "容器4"

        // 显示初始值
        binding.tvDistance.text = "${currentStrikeRange}m"
        binding.tvInterval.text = "${currentStrikeInterval}s"
        binding.tvContainer.text = currentContainer

        initListeners()
    }

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

        binding.itemDistance.setOnClickListener {
            val dialog = CustomDialogFragmentText()
                .setTitle(getString(R.string.strike_distance))
                .setInputText(currentStrikeRange)
            dialog.setOnConfirmListener { distance ->
                updateStrikeRange(distance)
            }
            dialog.show(supportFragmentManager, "DistanceDialog")
        }

        binding.itemInterval.setOnClickListener {
            val dialog = CustomDialogFragmentText()
                .setTitle(getString(R.string.strike_interval))
                .setInputText(currentStrikeInterval)
            dialog.setOnConfirmListener { interval ->
                updateStrikeInterval(interval)
            }
            dialog.show(supportFragmentManager, "IntervalDialog")
        }

        binding.itemContainer.setOnClickListener {
            val dialog = ContainerSelectDialog(this)
            dialog.setSelectedContainer(currentContainer)
            dialog.setOnConfirmListener { container ->
                updateContainer(container)
            }
            dialog.show()
        }

        binding.itemPosition.setOnClickListener {
            // 跳转到打击位置设置页面
            startActivity(android.content.Intent(this, StrikePositionActivity::class.java))
        }
    }

    private fun updateStrikeRange(distance: String) {
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = DeviceBean(
                    id = deviceId,
                    strikeRange = distance
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        currentStrikeRange = distance
                        binding.tvDistance.text = "${distance}m"
                        Toast.makeText(this@WaterGunSettingsActivity, "修改成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@WaterGunSettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WaterGunSettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateStrikeInterval(interval: String) {
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = DeviceBean(
                    id = deviceId,
                    strikeInterval = interval
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        currentStrikeInterval = interval
                        binding.tvInterval.text = "${interval}s"
                        Toast.makeText(this@WaterGunSettingsActivity, "修改成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@WaterGunSettingsActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WaterGunSettingsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateContainer(container: String) {
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            return
        }

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