import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/vehicle_cmd.dart';
import '../models/vehicle_cmd_response.dart';
import 'vehicle_state_service.dart';

/// 车辆命令服务 - 负责与后端交互以获取和处理车辆控制命令
class VehicleCommandService {
  // final VehicleStateService vehicleStateService = VehicleStateService();

  Future<VehicleCommandResponse?> getCommandFromText(String text) async {
    try {
      final uri = Uri.parse('http://143.64.185.20:18606/control');

      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({'text': text}),
      );

      if (response.statusCode == 200) {
        final decoded = json.decode(response.body);
        final tips = decoded['tips'];
        final commandList = decoded['commands'];
        List<VehicleCommand> vehicleCommandList = (commandList as List)
            .map<VehicleCommand>((item) => VehicleCommand.fromString(
            item['command'] as String,
            item['params'] as Map<String, dynamic>?,
            item['error'] ?? ''))
            .toList();
        return VehicleCommandResponse(tips: tips, commands: vehicleCommandList);
      } else {
        print(
            'Vehicle command query failed: ${response.statusCode}, ${response.body}');
        return null;
      }
    } catch (e) {
      print('Error during vehicle command processing: $e');
      return null;
    }
  }

  Future<String> getControlResponse(List<String> successCommandList) async {
    String reply = "";
    try {
      final uri = Uri.parse('http://143.64.185.20:18606/control_resp');
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode(successCommandList),
      );
      if (response.statusCode == 200) {
        return response.body;
      } else {
        print("请求控制回复失败: ${response.statusCode}");
      }
    } catch (e) {
      print('请求控制回复异常: $e');
    }
    return reply;
  }
}
