package com.narutohuo.xindazhou.vehicle.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.narutohuo.xindazhou.R
import com.narutohuo.xindazhou.ble.api.IBLE
import com.narutohuo.xindazhou.ble.config.BLEConstants
import com.narutohuo.xindazhou.ble.BLEKit
import com.narutohuo.xindazhou.ble.model.BLECommand
import com.narutohuo.xindazhou.ble.model.SystemControlInstruction
import com.narutohuo.xindazhou.ble.util.toHexString
import com.narutohuo.xindazhou.common.ui.BaseActivity
import com.narutohuo.xindazhou.core.log.ILog
import com.narutohuo.xindazhou.databinding.ActivityVehicleBinding
import com.narutohuo.xindazhou.community.ui.CommunityActivity
import com.narutohuo.xindazhou.service.ui.ServiceActivity
import com.narutohuo.xindazhou.shop.ui.ShopActivity
import com.narutohuo.xindazhou.user.ui.UserActivity
import kotlin.OptIn
import kotlin.ExperimentalStdlibApi
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * 车辆控制 Activity
 * 
 * 架构A：每个页面一个Activity
 * 
 * 主要功能：
 * 1. 蓝牙连接管理
 * 2. 实时状态显示
 * 3. 快捷控制（设撤防、上下电、寻车、锁控制）
 * 4. 系统控制（各种开关、时间设置、氛围灯等）
 * 5. 系统设置（钥匙学码、灵敏度、报警设置等）
 */
class VehicleActivity : BaseActivity<ActivityVehicleBinding>() {
    
    // 蓝牙服务
    private lateinit var bleService: IBLE
    
    // 当前设防状态（用于切换）
    private var isDefenseOn = false
    // 当前上电状态（用于切换）
    private var isPowerOn = false

    // 蓝牙连接状态
    private lateinit var tvBluetoothStatus: TextView
    private lateinit var btnConnectBluetooth: Button

    // 实时状态
    private lateinit var tvDefenseStatus: TextView
    private lateinit var tvPowerStatus: TextView
    private lateinit var tvDoorLockStatus: TextView
    private lateinit var tvBatteryLevel: TextView
    private lateinit var btnQueryVehicleInfo: Button

    // 快捷控制
    private lateinit var btnDefense: Button
    private lateinit var btnPower: Button
    private lateinit var btnFindCar: Button
    private lateinit var btnSeatLock: Button
    private lateinit var btnHandlebarLock: Button
    private lateinit var btnTrunkLock: Button

    // 系统控制 - 开关
    private lateinit var switchInductionUnlock: Switch
    private lateinit var switchTheftLock: Switch
    private lateinit var switchSeatSensor: Switch
    private lateinit var switchVehicleSound: Switch
    private lateinit var switchAutoHeadlight: Switch
    private lateinit var switchAtmosphereLight: Switch
    private lateinit var switchVoiceBroadcast: Switch
    private lateinit var switchFollowMeHome: Switch
    private lateinit var switchABS: Switch
    private lateinit var switchTCS: Switch

    // 系统控制 - 时间设置
    private lateinit var etAutoPowerOffTime: EditText
    private lateinit var btnSetAutoPowerOffTime: Button
    private lateinit var etAutoDefenseTime: EditText
    private lateinit var btnSetAutoDefenseTime: Button
    private lateinit var etEnterPTime: EditText
    private lateinit var btnSetEnterPTime: Button

    // 系统控制 - 其他设置
    private lateinit var etBluetoothSpeakerVolume: EditText
    private lateinit var btnSetBluetoothSpeakerVolume: Button
    private lateinit var etLowBatteryThreshold: EditText
    private lateinit var btnSetLowBatteryThreshold: Button
    private lateinit var etAtmosphereLightR: EditText
    private lateinit var etAtmosphereLightG: EditText
    private lateinit var etAtmosphereLightB: EditText
    private lateinit var btnSetAtmosphereLightColor: Button
    private lateinit var btnCollectRSSI: Button
    private lateinit var btnResetTripMileage: Button

    // 系统设置
    private lateinit var btnKeyLearning: Button
    private lateinit var btnSetVibrationSensitivity: Button
    private lateinit var switchAlarmReport: Switch
    private lateinit var btnSetTiltAlarmThreshold: Button

    // 权限请求器
    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.all { it.value }
        if (allGranted) {
            ILog.d("VehicleActivity", "✅ 所有权限已授予，开始连接设备")
            performConnectToDevice()
        } else {
            val deniedPermissions = permissions.filter { !it.value }.keys.joinToString(", ")
            ILog.e("VehicleActivity", "❌ 权限被拒绝: $deniedPermissions")
            Toast.makeText(
                this,
                "需要蓝牙权限才能连接设备，请在设置中授予权限",
                Toast.LENGTH_LONG
            ).show()
            btnConnectBluetooth.isEnabled = true
            tvBluetoothStatus.text = "权限被拒绝"
        }
    }

    override fun getViewBinding(): ActivityVehicleBinding {
        return ActivityVehicleBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化蓝牙服务
        bleService = BLEKit.create(this)
        
        initViews()
        setupClickListeners()
        setupBottomNavigation()
        updateConnectionStatus()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 断开连接
        if (bleService.isConnected()) {
            bleService.disconnect()
        }
    }

    override fun initView() {
        // UI初始化在onCreate中完成
    }

    private fun initViews() {
        // 蓝牙连接状态
        tvBluetoothStatus = binding.tvBluetoothStatus
        btnConnectBluetooth = binding.btnConnectBluetooth

        // 实时状态
        tvDefenseStatus = binding.tvDefenseStatus
        tvPowerStatus = binding.tvPowerStatus
        tvDoorLockStatus = binding.tvDoorLockStatus
        tvBatteryLevel = binding.tvBatteryLevel
        btnQueryVehicleInfo = binding.btnQueryVehicleInfo

        // 快捷控制
        btnDefense = binding.btnDefense
        btnPower = binding.btnPower
        btnFindCar = binding.btnFindCar
        btnSeatLock = binding.btnSeatLock
        btnHandlebarLock = binding.btnHandlebarLock
        btnTrunkLock = binding.btnTrunkLock

        // 系统控制 - 开关
        switchInductionUnlock = binding.switchInductionUnlock
        switchTheftLock = binding.switchTheftLock
        switchSeatSensor = binding.switchSeatSensor
        switchVehicleSound = binding.switchVehicleSound
        switchAutoHeadlight = binding.switchAutoHeadlight
        switchAtmosphereLight = binding.switchAtmosphereLight
        switchVoiceBroadcast = binding.switchVoiceBroadcast
        switchFollowMeHome = binding.switchFollowMeHome
        switchABS = binding.switchABS
        switchTCS = binding.switchTCS

        // 系统控制 - 时间设置
        etAutoPowerOffTime = binding.etAutoPowerOffTime
        btnSetAutoPowerOffTime = binding.btnSetAutoPowerOffTime
        etAutoDefenseTime = binding.etAutoDefenseTime
        btnSetAutoDefenseTime = binding.btnSetAutoDefenseTime
        etEnterPTime = binding.etEnterPTime
        btnSetEnterPTime = binding.btnSetEnterPTime

        // 系统控制 - 其他设置
        etBluetoothSpeakerVolume = binding.etBluetoothSpeakerVolume
        btnSetBluetoothSpeakerVolume = binding.btnSetBluetoothSpeakerVolume
        etLowBatteryThreshold = binding.etLowBatteryThreshold
        btnSetLowBatteryThreshold = binding.btnSetLowBatteryThreshold
        etAtmosphereLightR = binding.etAtmosphereLightR
        etAtmosphereLightG = binding.etAtmosphereLightG
        etAtmosphereLightB = binding.etAtmosphereLightB
        btnSetAtmosphereLightColor = binding.btnSetAtmosphereLightColor
        btnCollectRSSI = binding.btnCollectRSSI
        btnResetTripMileage = binding.btnResetTripMileage

        // 系统设置
        btnKeyLearning = binding.btnKeyLearning
        btnSetVibrationSensitivity = binding.btnSetVibrationSensitivity
        switchAlarmReport = binding.switchAlarmReport
        btnSetTiltAlarmThreshold = binding.btnSetTiltAlarmThreshold
    }

    /**
     * 设置底部导航栏
     */
    private fun setupBottomNavigation() {
        binding.bottomNavView.selectedItemId = R.id.vehicleFragment
        binding.bottomNavView.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.vehicleFragment -> {
                    // 当前已在车辆模块，不需要跳转
                    true
                }
                R.id.communityFragment -> {
                    startActivity(Intent(this, CommunityActivity::class.java))
                    finish()
                    true
                }
                R.id.serviceFragment -> {
                    startActivity(Intent(this, ServiceActivity::class.java))
                    finish()
                    true
                }
                R.id.shopFragment -> {
                    startActivity(Intent(this, ShopActivity::class.java))
                    finish()
                    true
                }
                R.id.userFragment -> {
                    startActivity(Intent(this, UserActivity::class.java))
                    finish()
                    true
                }
                else -> false
            }
        }
    }

    /**
     * 更新连接状态显示
     */
    private fun updateConnectionStatus() {
        if (bleService.isConnected()) {
            tvBluetoothStatus.text = "蓝牙已连接"
            btnConnectBluetooth.text = "断开"
        } else {
            tvBluetoothStatus.text = "蓝牙未连接"
            btnConnectBluetooth.text = "连接"
        }
    }

    private fun setupClickListeners() {
        // 蓝牙连接/断开
        btnConnectBluetooth.setOnClickListener {
            Toast.makeText(this, "按钮被点击了", Toast.LENGTH_SHORT).show()
            ILog.e("VehicleActivity", "🔴🔴🔴 按钮被点击了")
            if (bleService.isConnected()) {
                // 断开连接
                bleService.disconnect()
                updateConnectionStatus()
                Toast.makeText(this, "已断开连接", Toast.LENGTH_SHORT).show()
            } else {
                // 一键扫描并连接
                connectToDevice()
            }
        }

        // 查询车辆信息
        btnQueryVehicleInfo.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击查询车辆信息按钮")
            if (!checkConnection()) return@setOnClickListener
            
            bleService.queryVehicleInfo { response ->
                ILog.d("VehicleActivity", "📥 查询车辆信息响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        val data = response.data
                        if (data != null) {
                            parseVehicleInfo(data)
                            Toast.makeText(this@VehicleActivity, "查询成功", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(this@VehicleActivity, "查询失败: 数据为空", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        Toast.makeText(this@VehicleActivity, "查询失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 快捷控制 ==========
        // 设撤防
        btnDefense.setOnClickListener {
            val enabled = !isDefenseOn
            ILog.d("VehicleActivity", "🟢 点击设撤防按钮: enabled=$enabled")
            if (!checkConnection()) return@setOnClickListener
            
            isDefenseOn = enabled
            
            bleService.setDefense(enabled = enabled) { response ->
                ILog.d("VehicleActivity", "📥 设撤防响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, if (enabled) "设防成功" else "撤防成功", Toast.LENGTH_SHORT).show()
                    } else {
                        isDefenseOn = !enabled // 恢复状态
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 上下电
        btnPower.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击上下电按钮: 当前状态 isPowerOn=$isPowerOn")
            if (!checkConnection()) return@setOnClickListener
            
            if (isPowerOn) {
                // 下电
                isPowerOn = false
                bleService.powerOff { response ->
                    ILog.d("VehicleActivity", "📥 下电响应: success=${response.success}, error=${response.errorMessage}")
                    runOnUiThread {
                        if (response.success) {
                            Toast.makeText(this@VehicleActivity, "下电成功", Toast.LENGTH_SHORT).show()
                        } else {
                            isPowerOn = true // 恢复状态
                            Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            } else {
                // 上电
                isPowerOn = true
                bleService.powerOn { response ->
                    ILog.d("VehicleActivity", "📥 上电响应: success=${response.success}, error=${response.errorMessage}")
                    runOnUiThread {
                        if (response.success) {
                            Toast.makeText(this@VehicleActivity, "上电成功", Toast.LENGTH_SHORT).show()
                        } else {
                            isPowerOn = false // 恢复状态
                            Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }

        // 寻车
        btnFindCar.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击寻车按钮")
            if (!checkConnection()) return@setOnClickListener
            
            bleService.findCar { response ->
                ILog.d("VehicleActivity", "📥 寻车响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "寻车成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "寻车失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 座桶锁
        btnSeatLock.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击座桶锁按钮")
            if (!checkConnection()) return@setOnClickListener
            
            bleService.unlockSeat { response ->
                ILog.d("VehicleActivity", "📥 座桶锁响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "座桶锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 龙头锁
        btnHandlebarLock.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击车把锁按钮")
            if (!checkConnection()) return@setOnClickListener
            
            bleService.unlockHandlebar { response ->
                ILog.d("VehicleActivity", "📥 车把锁响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "龙头锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 尾箱锁
        btnTrunkLock.setOnClickListener {
            ILog.d("VehicleActivity", "🟢 点击尾箱锁按钮")
            if (!checkConnection()) return@setOnClickListener
            
            bleService.unlockTrunk { response ->
                ILog.d("VehicleActivity", "📥 尾箱锁响应: success=${response.success}, error=${response.errorMessage}")
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "尾箱锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 系统控制 - 开关 ==========
        // 感应解锁开关
        switchInductionUnlock.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchInductionUnlock.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            bleService.setSensorUnlock(enabled = isChecked) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchInductionUnlock.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 被盗锁定开关
        switchTheftLock.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchTheftLock.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.STOLEN_LOCK, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchTheftLock.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 座椅感应开关
        switchSeatSensor.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchSeatSensor.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.SEAT_SENSOR, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchSeatSensor.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 车辆音效开关
        switchVehicleSound.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchVehicleSound.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.SOUND_EFFECT, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchVehicleSound.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 自动大灯开关
        switchAutoHeadlight.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchAutoHeadlight.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.AUTO_HEADLIGHT, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchAutoHeadlight.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 氛围灯开关
        switchAtmosphereLight.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchAtmosphereLight.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            bleService.setAmbientLight(enabled = isChecked) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchAtmosphereLight.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 语音播报开关
        switchVoiceBroadcast.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchVoiceBroadcast.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.VOICE_BROADCAST, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchVoiceBroadcast.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 伴我回家
        switchFollowMeHome.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchFollowMeHome.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.WALK_ME_HOME, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchFollowMeHome.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ABS
        switchABS.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchABS.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.ABS, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchABS.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // TCS
        switchTCS.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchTCS.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            bleService.sendSystemControlCommand(SystemControlInstruction.TCS, byteArrayOf(action)) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchTCS.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 系统控制 - 时间设置 ==========
        // 自动下电时间
        btnSetAutoPowerOffTime.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val time = etAutoPowerOffTime.text.toString().toIntOrNull() ?: 300
            if (time < 0 || time > 60000) {
                Toast.makeText(this, "时间范围：0-60000秒", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.setAutoPowerOffTime(timeSeconds = time) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 自动设防时间
        btnSetAutoDefenseTime.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val time = etAutoDefenseTime.text.toString().toIntOrNull() ?: 5
            if (time < 0 || time > 60000) {
                Toast.makeText(this, "时间范围：0-60000秒", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            val data = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(time.toShort()).array()
            bleService.sendSystemControlCommand(SystemControlInstruction.AUTO_DEFENSE_TIME, data) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 进入P档时间
        btnSetEnterPTime.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val time = etEnterPTime.text.toString().toIntOrNull() ?: 300
            if (time < 0 || time > 60000) {
                Toast.makeText(this, "时间范围：0-60000秒", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            val data = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(time.toShort()).array()
            bleService.sendSystemControlCommand(SystemControlInstruction.ENTER_P_TIME, data) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 系统控制 - 其他设置 ==========
        // 蓝牙音箱音量
        btnSetBluetoothSpeakerVolume.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val volume = etBluetoothSpeakerVolume.text.toString().toIntOrNull() ?: 50
            if (volume < 0 || volume > 100) {
                Toast.makeText(this, "音量范围：0-100%", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.setSpeakerVolume(volume = volume) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 低电量报警阈值
        btnSetLowBatteryThreshold.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val threshold = etLowBatteryThreshold.text.toString().toIntOrNull() ?: 20
            if (threshold < 0 || threshold > 100) {
                Toast.makeText(this, "阈值范围：0-100%", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.sendSystemControlCommand(SystemControlInstruction.LOW_BATTERY_ALARM, byteArrayOf(threshold.toByte())) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 氛围灯颜色
        btnSetAtmosphereLightColor.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val r = etAtmosphereLightR.text.toString().toIntOrNull()?.coerceIn(0, 255) ?: 255
            val g = etAtmosphereLightG.text.toString().toIntOrNull()?.coerceIn(0, 255) ?: 255
            val b = etAtmosphereLightB.text.toString().toIntOrNull()?.coerceIn(0, 255) ?: 255
            
            bleService.setAmbientLightColor(r = r, g = g, b = b) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 感应解锁RSSI信号强度采集
        btnCollectRSSI.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            bleService.sendSystemControlCommand(SystemControlInstruction.RSSI_COLLECTION, byteArrayOf(0x01)) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "RSSI采集成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "采集失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 小计里程清零
        btnResetTripMileage.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            bleService.sendSystemControlCommand(SystemControlInstruction.RESET_MILEAGE, byteArrayOf(0x01)) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "里程清零成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 系统设置 ==========
        // 钥匙学码
        btnKeyLearning.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x01.toByte(),
                applicationData = byteArrayOf(0x01)
            )
            
            bleService.sendCommand(command) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "钥匙学码成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 震动灵敏度
        btnSetVibrationSensitivity.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val sensitivity = when {
                binding.rbSensitivity1.isChecked -> 1
                binding.rbSensitivity2.isChecked -> 2
                binding.rbSensitivity3.isChecked -> 3
                binding.rbSensitivity4.isChecked -> 4
                binding.rbSensitivity5.isChecked -> 5
                else -> 3
            }
            
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x02.toByte(),
                applicationData = byteArrayOf(sensitivity.toByte())
            )
            
            bleService.sendCommand(command) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 报警是否上报
        switchAlarmReport.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchAlarmReport.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            val action = if (isChecked) 0x01.toByte() else 0x00.toByte()
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x03.toByte(),
                applicationData = byteArrayOf(action)
            )
            
            bleService.sendCommand(command) { response ->
                runOnUiThread {
                    if (!response.success) {
                        switchAlarmReport.isChecked = !isChecked
                        Toast.makeText(this@VehicleActivity, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 倾倒报警阈值
        btnSetTiltAlarmThreshold.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val threshold = when {
                binding.rbTilt50.isChecked -> 0x32.toByte()
                binding.rbTilt60.isChecked -> 0x3c.toByte()
                binding.rbTilt70.isChecked -> 0x46.toByte()
                else -> 0x3c.toByte()
            }
            
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x04.toByte(),
                applicationData = byteArrayOf(threshold)
            )
            
            bleService.sendCommand(command) { response ->
                runOnUiThread {
                    if (response.success) {
                        Toast.makeText(this@VehicleActivity, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@VehicleActivity, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    /**
     * 检查连接状态
     */
    private fun checkConnection(): Boolean {
        if (!bleService.isConnected()) {
            Toast.makeText(this, "请先连接蓝牙设备", Toast.LENGTH_SHORT).show()
            return false
        }
        return true
    }

    /**
     * 连接到设备（一键完成扫描+连接+握手）
     */
    private fun connectToDevice() {
        ILog.d("VehicleActivity", "========== 开始连接设备 ==========")
        
        // 检查并请求权限
        val requiredPermissions = mutableListOf<String>()
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requiredPermissions.add(Manifest.permission.BLUETOOTH_SCAN)
            requiredPermissions.add(Manifest.permission.BLUETOOTH_CONNECT)
        } else {
            requiredPermissions.add(Manifest.permission.BLUETOOTH)
            requiredPermissions.add(Manifest.permission.BLUETOOTH_ADMIN)
            requiredPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        
        val missingPermissions = requiredPermissions.filter { permission ->
            ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            ILog.w("VehicleActivity", "缺少权限: ${missingPermissions.joinToString(", ")}")
            btnConnectBluetooth.isEnabled = false
            tvBluetoothStatus.text = "请求权限..."
            permissionLauncher.launch(missingPermissions.toTypedArray())
            return
        }
        
        ILog.d("VehicleActivity", "✅ 所有权限已授予")
        performConnectToDevice()
    }
    
    /**
     * 执行连接设备（权限已授予后调用）
     */
    private fun performConnectToDevice() {
        btnConnectBluetooth.isEnabled = false
        tvBluetoothStatus.text = "正在扫描设备..."
        
        val userId = ByteArray(16) { it.toByte() }
        val userType = BLEConstants.USER_TYPE_OWNER
        
        ILog.d("VehicleActivity", "开始扫描并连接设备...")
        
        bleService.initializeAndConnect(
            userId = userId,
            userType = userType,
            onConnected = {
                runOnUiThread {
                    btnConnectBluetooth.isEnabled = true
                    updateConnectionStatus()
                    Toast.makeText(this@VehicleActivity, "连接成功", Toast.LENGTH_SHORT).show()
                    btnQueryVehicleInfo.performClick()
                }
            },
            onDisconnected = {
                runOnUiThread {
                    updateConnectionStatus()
                    Toast.makeText(this@VehicleActivity, "连接已断开", Toast.LENGTH_SHORT).show()
                }
            },
            onDataReceived = { data ->
                handleReceivedData(data)
            },
            onError = { error ->
                runOnUiThread {
                    btnConnectBluetooth.isEnabled = true
                    updateConnectionStatus()
                    Toast.makeText(this@VehicleActivity, "连接失败: $error", Toast.LENGTH_SHORT).show()
                }
            }
        )
    }
    
    /**
     * 处理接收到的数据
     */
    @OptIn(ExperimentalStdlibApi::class)
    private fun handleReceivedData(data: ByteArray) {
        val hexString = data.toHexString()
        ILog.d("VehicleActivity", "🔔🔔🔔 Android收到设备响应 (${data.size} bytes): $hexString")
        
        if (data.size == 1) {
            val byte = data[0]
            ILog.d("VehicleActivity", "⚠️ 收到单字节响应: 0x${String.format("%02x", byte)}")
            
            if (byte == 0x33.toByte()) {
                ILog.e("VehicleActivity", "❌ 设备返回认证失败 (0x33 = '3')")
            }
            return
        }
        
        try {
            val jsonString = String(data, Charsets.UTF_8)
            ILog.d("VehicleActivity", "📥 数据内容(JSON): $jsonString")
            val jsonObject = org.json.JSONObject(jsonString)
            
            runOnUiThread {
                val ty = jsonObject.optInt("TY", 0)
                val `in` = jsonObject.optInt("IN", 0)
                
                when {
                    ty == 3 && `in` == 3 -> {
                        ILog.d("VehicleActivity", "收到握手请求")
                    }
                    ty == 3 && `in` == 4 -> {
                        val pairing = jsonObject.optJSONObject("C")?.optJSONObject("D")?.optInt("Pairing", 0) ?: 0
                        ILog.d("VehicleActivity", "📥 收到配对请求，Pairing=$pairing")
                        when (pairing) {
                            1 -> ILog.d("VehicleActivity", "✅ 设备需要配对 (Pairing=1)")
                            2 -> ILog.d("VehicleActivity", "✅ 设备不需要配对 (Pairing=2)")
                            3 -> ILog.e("VehicleActivity", "❌ 认证失败 (Pairing=3)")
                        }
                    }
                    else -> {
                        ILog.d("VehicleActivity", "收到业务消息: $jsonString")
                    }
                }
            }
        } catch (e: Exception) {
            ILog.e("VehicleActivity", "解析接收数据失败", e)
        }
    }

    /**
     * 解析车辆信息
     */
    private fun parseVehicleInfo(data: ByteArray) {
        if (data.size < 84) {
            return
        }
        
        val defenseStatus = if (data[0] == 0x01.toByte()) "设防" else "撤防"
        val powerStatus = if (data[1] == 0x01.toByte()) "上电" else "下电"
        val doorLockStatus = if (data[2] == 0x01.toByte()) "关闭" else "打开"
        
        val battery1SOC = if (data.size > 42) data[42].toInt() and 0xFF else 0
        val battery2SOC = if (data.size > 50) data[50].toInt() and 0xFF else 0
        val batteryLevel = (battery1SOC + battery2SOC) / 2
        
        tvDefenseStatus.text = defenseStatus
        tvPowerStatus.text = powerStatus
        tvDoorLockStatus.text = doorLockStatus
        tvBatteryLevel.text = "$batteryLevel%"
        
        switchInductionUnlock.isChecked = data.size > 8 && data[8] == 0x01.toByte()
        switchTheftLock.isChecked = data.size > 10 && data[10] == 0x01.toByte()
        switchSeatSensor.isChecked = data.size > 11 && data[11] == 0x01.toByte()
        switchVehicleSound.isChecked = data.size > 12 && data[12] == 0x01.toByte()
        switchAutoHeadlight.isChecked = data.size > 13 && data[13] == 0x01.toByte()
        switchAtmosphereLight.isChecked = data.size > 26 && data[26] == 0x01.toByte()
        switchVoiceBroadcast.isChecked = data.size > 27 && data[27] == 0x01.toByte()
        switchFollowMeHome.isChecked = data.size > 28 && data[28] == 0x01.toByte()
        switchABS.isChecked = data.size > 38 && data[38] == 0x01.toByte()
        switchTCS.isChecked = data.size > 39 && data[39] == 0x01.toByte()
    }
}
