package com.narutohuo.xindazhou.vehicle.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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 androidx.fragment.app.Fragment
import com.narutohuo.xindazhou.R
import com.narutohuo.xindazhou.ble.api.BLEService
import com.narutohuo.xindazhou.ble.callback.DataCallback
import com.narutohuo.xindazhou.ble.config.BLEConstants
import com.narutohuo.xindazhou.ble.factory.BLEServiceFactory
import com.narutohuo.xindazhou.ble.model.AppControlInstruction
import com.narutohuo.xindazhou.ble.model.BLECommand
import com.narutohuo.xindazhou.ble.model.BLEDevice
import com.narutohuo.xindazhou.ble.model.BLEResponse
import com.narutohuo.xindazhou.ble.model.SystemControlInstruction
import com.narutohuo.xindazhou.common.log.LogHelper
import com.narutohuo.xindazhou.core.log.ILog
import org.json.JSONObject
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * 车辆Fragment
 * 
 * 主要功能：
 * 1. 蓝牙连接管理
 * 2. 实时状态显示
 * 3. 快捷控制（设撤防、上下电、寻车、锁控制）
 * 4. 系统控制（各种开关、时间设置、氛围灯等）
 * 5. 系统设置（钥匙学码、灵敏度、报警设置等）
 * 
 * 蓝牙协议说明：
 * - 服务UUID: 0000adb0-0000-1000-8000-00805f9b34fb
 * - Notify特征值: 0000adb1-0000-1000-8000-00805f9b34fb
 * - Write特征值: 0000adb2-0000-1000-8000-00805f9b34fb
 * 
 * 功能码：
 * - 0x01: 握手
 * - 0x02: 应用控制
 * - 0x03: 系统控制
 * - 0x04: 系统查询
 * - 0x05: 系统设置
 * - 0x06: MTU设置值查询
 */
class VehicleFragment : Fragment() {

    // 蓝牙服务
    private lateinit var bleService: BLEService
    
    // 当前设防状态（用于切换）
    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

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_vehicle, container, false)
    }

    private var rootView: View? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        rootView = view

        // 初始化蓝牙服务
        bleService = BLEServiceFactory.create(requireContext())
        
        initViews(view)
        setupClickListeners()
        updateConnectionStatus()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        rootView = null
        // 断开连接
        if (bleService.isConnected()) {
            bleService.disconnect()
        }
    }

    private fun initViews(view: View) {
        // 蓝牙连接状态
        tvBluetoothStatus = view.findViewById(R.id.tvBluetoothStatus)
        btnConnectBluetooth = view.findViewById(R.id.btnConnectBluetooth)

        // 实时状态
        tvDefenseStatus = view.findViewById(R.id.tvDefenseStatus)
        tvPowerStatus = view.findViewById(R.id.tvPowerStatus)
        tvDoorLockStatus = view.findViewById(R.id.tvDoorLockStatus)
        tvBatteryLevel = view.findViewById(R.id.tvBatteryLevel)
        btnQueryVehicleInfo = view.findViewById(R.id.btnQueryVehicleInfo)

        // 快捷控制
        btnDefense = view.findViewById(R.id.btnDefense)
        btnPower = view.findViewById(R.id.btnPower)
        btnFindCar = view.findViewById(R.id.btnFindCar)
        btnSeatLock = view.findViewById(R.id.btnSeatLock)
        btnHandlebarLock = view.findViewById(R.id.btnHandlebarLock)
        btnTrunkLock = view.findViewById(R.id.btnTrunkLock)

        // 系统控制 - 开关
        switchInductionUnlock = view.findViewById(R.id.switchInductionUnlock)
        switchTheftLock = view.findViewById(R.id.switchTheftLock)
        switchSeatSensor = view.findViewById(R.id.switchSeatSensor)
        switchVehicleSound = view.findViewById(R.id.switchVehicleSound)
        switchAutoHeadlight = view.findViewById(R.id.switchAutoHeadlight)
        switchAtmosphereLight = view.findViewById(R.id.switchAtmosphereLight)
        switchVoiceBroadcast = view.findViewById(R.id.switchVoiceBroadcast)
        switchFollowMeHome = view.findViewById(R.id.switchFollowMeHome)
        switchABS = view.findViewById(R.id.switchABS)
        switchTCS = view.findViewById(R.id.switchTCS)

        // 系统控制 - 时间设置
        etAutoPowerOffTime = view.findViewById(R.id.etAutoPowerOffTime)
        btnSetAutoPowerOffTime = view.findViewById(R.id.btnSetAutoPowerOffTime)
        etAutoDefenseTime = view.findViewById(R.id.etAutoDefenseTime)
        btnSetAutoDefenseTime = view.findViewById(R.id.btnSetAutoDefenseTime)
        etEnterPTime = view.findViewById(R.id.etEnterPTime)
        btnSetEnterPTime = view.findViewById(R.id.btnSetEnterPTime)

        // 系统控制 - 其他设置
        etBluetoothSpeakerVolume = view.findViewById(R.id.etBluetoothSpeakerVolume)
        btnSetBluetoothSpeakerVolume = view.findViewById(R.id.btnSetBluetoothSpeakerVolume)
        etLowBatteryThreshold = view.findViewById(R.id.etLowBatteryThreshold)
        btnSetLowBatteryThreshold = view.findViewById(R.id.btnSetLowBatteryThreshold)
        etAtmosphereLightR = view.findViewById(R.id.etAtmosphereLightR)
        etAtmosphereLightG = view.findViewById(R.id.etAtmosphereLightG)
        etAtmosphereLightB = view.findViewById(R.id.etAtmosphereLightB)
        btnSetAtmosphereLightColor = view.findViewById(R.id.btnSetAtmosphereLightColor)
        btnCollectRSSI = view.findViewById(R.id.btnCollectRSSI)
        btnResetTripMileage = view.findViewById(R.id.btnResetTripMileage)

        // 系统设置
        btnKeyLearning = view.findViewById(R.id.btnKeyLearning)
        btnSetVibrationSensitivity = view.findViewById(R.id.btnSetVibrationSensitivity)
        switchAlarmReport = view.findViewById(R.id.switchAlarmReport)
        btnSetTiltAlarmThreshold = view.findViewById(R.id.btnSetTiltAlarmThreshold)
    }


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

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

        // 查询车辆信息
        btnQueryVehicleInfo.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            bleService.queryVehicleInfo { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        val data = response.data
                        if (data != null) {
                            parseVehicleInfo(data)
                            Toast.makeText(context, "查询成功", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(context, "查询失败: 数据为空", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        Toast.makeText(context, "查询失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 快捷控制 ==========
        // 设撤防
        btnDefense.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val enabled = !isDefenseOn
            isDefenseOn = enabled
            
            bleService.setDefense(enabled = enabled) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, if (enabled) "设防成功" else "撤防成功", Toast.LENGTH_SHORT).show()
                    } else {
                        isDefenseOn = !enabled // 恢复状态
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 上下电
        btnPower.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            if (isPowerOn) {
                // 下电
                isPowerOn = false
                bleService.powerOff { response ->
                    activity?.runOnUiThread {
                        if (response.success) {
                            Toast.makeText(context, "下电成功", Toast.LENGTH_SHORT).show()
                        } else {
                            isPowerOn = true // 恢复状态
                            Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            } else {
                // 上电
                isPowerOn = true
                bleService.powerOn { response ->
                    activity?.runOnUiThread {
                        if (response.success) {
                            Toast.makeText(context, "上电成功", Toast.LENGTH_SHORT).show()
                        } else {
                            isPowerOn = false // 恢复状态
                            Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        }

        // 寻车
        btnFindCar.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            bleService.findCar { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "寻车成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "寻车失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 座桶锁
        btnSeatLock.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            bleService.unlockSeat { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "座桶锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 龙头锁
        btnHandlebarLock.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            // 假设当前是关闭，点击后打开
            bleService.unlockHandlebar { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "龙头锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 尾箱锁
        btnTrunkLock.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            // 假设当前是关闭，点击后打开
            bleService.unlockTrunk { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "尾箱锁已打开", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // ========== 系统控制 - 开关 ==========
        // 感应解锁开关
        switchInductionUnlock.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchInductionUnlock.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            bleService.setSensorUnlock(enabled = isChecked) { response ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchInductionUnlock.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchTheftLock.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchSeatSensor.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchVehicleSound.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchAutoHeadlight.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 氛围灯开关
        switchAtmosphereLight.setOnCheckedChangeListener { _, isChecked ->
            if (!checkConnection()) {
                switchAtmosphereLight.isChecked = !isChecked
                return@setOnCheckedChangeListener
            }
            
            bleService.setAmbientLight(enabled = isChecked) { response ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchAtmosphereLight.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchVoiceBroadcast.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchFollowMeHome.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchABS.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchTCS.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${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(context, "时间范围：0-60000秒", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.setAutoPowerOffTime(timeSeconds = time) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${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(context, "时间范围：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 ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${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(context, "时间范围：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 ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${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(context, "音量范围：0-100%", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.setSpeakerVolume(volume = volume) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${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(context, "阈值范围：0-100%", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            bleService.sendSystemControlCommand(SystemControlInstruction.LOW_BATTERY_ALARM, byteArrayOf(threshold.toByte())) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${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 ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 感应解锁RSSI信号强度采集
        btnCollectRSSI.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            // 这里需要选择采集位置（左前方、右前方、左后方、右后方）
            // 简化实现：采集左前方
            bleService.sendSystemControlCommand(SystemControlInstruction.RSSI_COLLECTION, byteArrayOf(0x01)) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "RSSI采集成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "采集失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

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

        // ========== 系统设置 ==========
        // 钥匙学码（功能码 0x05, 指令类型 0x01）
        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 ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "钥匙学码成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 震动灵敏度（功能码 0x05, 指令类型 0x02）
        btnSetVibrationSensitivity.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val sensitivity = when {
                rootView?.findViewById<RadioButton>(R.id.rbSensitivity1)?.isChecked == true -> 1
                rootView?.findViewById<RadioButton>(R.id.rbSensitivity2)?.isChecked == true -> 2
                rootView?.findViewById<RadioButton>(R.id.rbSensitivity3)?.isChecked == true -> 3
                rootView?.findViewById<RadioButton>(R.id.rbSensitivity4)?.isChecked == true -> 4
                rootView?.findViewById<RadioButton>(R.id.rbSensitivity5)?.isChecked == true -> 5
                else -> 3
            }
            
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x02.toByte(),
                applicationData = byteArrayOf(sensitivity.toByte())
            )
            
            bleService.sendCommand(command) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 报警是否上报（功能码 0x05, 指令类型 0x03）
        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 ->
                activity?.runOnUiThread {
                    if (!response.success) {
                        switchAlarmReport.isChecked = !isChecked
                        Toast.makeText(context, "操作失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        // 倾倒报警阈值（功能码 0x05, 指令类型 0x04）
        btnSetTiltAlarmThreshold.setOnClickListener {
            if (!checkConnection()) return@setOnClickListener
            
            val threshold = when {
                rootView?.findViewById<RadioButton>(R.id.rbTilt50)?.isChecked == true -> 0x32.toByte()
                rootView?.findViewById<RadioButton>(R.id.rbTilt60)?.isChecked == true -> 0x3c.toByte()
                rootView?.findViewById<RadioButton>(R.id.rbTilt70)?.isChecked == true -> 0x46.toByte()
                else -> 0x3c.toByte()
            }
            
            val command = BLECommand(
                functionCode = BLEConstants.FUNCTION_CODE_SYSTEM_SETTING,
                instructionType = 0x04.toByte(),
                applicationData = byteArrayOf(threshold)
            )
            
            bleService.sendCommand(command) { response ->
                activity?.runOnUiThread {
                    if (response.success) {
                        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "设置失败: ${response.errorMessage}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

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

    /**
     * 连接到设备（一键完成扫描+连接+握手）
     */
    private fun connectToDevice() {
        ILog.d("VehicleFragment", "========== 开始连接设备 ==========")
        
        // 检查并请求权限
        val requiredPermissions = mutableListOf<String>()
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+ 需要新权限
            requiredPermissions.add(Manifest.permission.BLUETOOTH_SCAN)
            requiredPermissions.add(Manifest.permission.BLUETOOTH_CONNECT)
        } else {
            // Android 11 及以下需要旧权限
            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(requireContext(), permission) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            ILog.w("VehicleFragment", "缺少权限: ${missingPermissions.joinToString(", ")}")
            ILog.d("VehicleFragment", "请求权限...")
            btnConnectBluetooth.isEnabled = false
            tvBluetoothStatus.text = "请求权限..."
            permissionLauncher.launch(missingPermissions.toTypedArray())
            return
        }
        
        ILog.d("VehicleFragment", "✅ 所有权限已授予")
        performConnectToDevice()
    }
    
    /**
     * 执行连接设备（权限已授予后调用）
     */
    private fun performConnectToDevice() {
        btnConnectBluetooth.isEnabled = false
        tvBluetoothStatus.text = "正在扫描设备..."
        
        // TODO: 从用户信息获取userId和userType（这里使用示例数据）
        val userId = ByteArray(16) { it.toByte() } // 示例：实际应该从用户信息获取
        val userType = BLEConstants.USER_TYPE_OWNER
        
        ILog.d("VehicleFragment", "开始扫描并连接设备...")
        
        // 一键完成：初始化监听 + 扫描 + 连接 + 握手
        bleService.initializeAndConnect(
            userId = userId,
            userType = userType,
            onConnected = {
                activity?.runOnUiThread {
                    btnConnectBluetooth.isEnabled = true
                    updateConnectionStatus()
                    Toast.makeText(context, "连接成功", Toast.LENGTH_SHORT).show()
                    // 连接成功后可以查询车辆信息
                    btnQueryVehicleInfo.performClick()
                }
            },
            onDisconnected = {
                activity?.runOnUiThread {
                    updateConnectionStatus()
                    Toast.makeText(context, "连接已断开", Toast.LENGTH_SHORT).show()
                }
            },
            onDataReceived = { data ->
                // 处理接收到的数据
                handleReceivedData(data)
            },
            onError = { error ->
                activity?.runOnUiThread {
                    btnConnectBluetooth.isEnabled = true
                    updateConnectionStatus()
                    Toast.makeText(context, "连接失败: $error", Toast.LENGTH_SHORT).show()
                }
            }
        )
    }
    
    /**
     * 处理接收到的数据
     */
    private fun handleReceivedData(data: ByteArray) {
        try {
            val jsonString = String(data, Charsets.UTF_8)
            val jsonObject = org.json.JSONObject(jsonString)
            
            activity?.runOnUiThread {
                // 根据消息类型更新UI
                val ty = jsonObject.optInt("TY", 0)
                val `in` = jsonObject.optInt("IN", 0)
                
                // 处理不同类型的消息
                when {
                    ty == 3 && `in` == 3 -> {
                        // 握手请求
                        LogHelper.d("VehicleFragment", "收到握手请求")
                    }
                    ty == 3 && `in` == 4 -> {
                        // 配对请求
                        val pairing = jsonObject.optJSONObject("C")?.optJSONObject("D")?.optInt("Pairing", 0) ?: 0
                        LogHelper.d("VehicleFragment", "收到配对请求，状态: $pairing")
                    }
                    else -> {
                        // 其他业务消息
                        LogHelper.d("VehicleFragment", "收到业务消息: $jsonString")
                    }
                }
            }
        } catch (e: Exception) {
            LogHelper.e("VehicleFragment", "解析接收数据失败", 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 "打开"
        
        // 电池信息（byte40开始是电池1，byte48开始是电池2）
        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 // 平均电量
        
        // 更新UI
        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()
    }
}
