import 'package:autosos_flutter/api/_api_client.dart';
import 'package:autosos_flutter/model/base_response.dart';
import 'package:autosos_flutter/model/misc.dart';
import 'package:autosos_flutter/model/order.dart';
import 'package:autosos_flutter/model/payment.dart';

/// 订单 API（对应 Android AppApiService 中 order/* 相关）
class OrderApi {
  static final OrderApi instance = OrderApi._();
  OrderApi._();

  final _http = ApiClient.instance.http;

  // ===== 核单 =====

  /// 核单列表
  Future<BaseResponse<List<CheckItem>>> checkList({int page = 1, int size = 20}) async {
    final r = await _http.get(
      '/v2/order/check-list',
      {'page': page, 'size': size},
    );
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => (d as List).map((e) => CheckItem.fromJson(e as Map<String, dynamic>)).toList());
  }

  /// 提交核单
  Future<BaseResponse<bool>> submitCheck({
    required int orderId,
    required String remark,
  }) async {
    final r = await _http.post('/v2/order/check', {
      'order_id': orderId,
      'remark': remark,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as bool);
  }

  // ===== 等待接单 =====

  /// 当前可接订单列表
  Future<BaseResponse<List<WaitingOrder>>> waitingList() async {
    final r = await _http.get('/v2/order/waiting-list');
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => (d as List).map((e) => WaitingOrder.fromJson(e as Map<String, dynamic>)).toList());
  }

  /// 抢单
  Future<BaseResponse<Order>> grabOrder(int orderId) async {
    final r = await _http.post('/v2/order/grab', {'order_id': orderId});
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => Order.fromJson(d as Map<String, dynamic>));
  }

  // ===== 救援中 =====

  /// 到达现场
  Future<BaseResponse<bool>> arriveScene(int orderId, {double? lat, double? lng}) async {
    final r = await _http.post('/v2/order/arrive', {
      'order_id': orderId,
      'lat': lat,
      'lng': lng,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as bool);
  }

  /// 开始轨迹录制
  Future<BaseResponse<String>> startTrack(int orderId) async {
    final r = await _http.post('/v2/order/track/start', {'order_id': orderId});
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as String);
  }

  /// 上传轨迹点
  Future<BaseResponse<bool>> uploadTrackPoints(int orderId, List<Map<String, dynamic>> points) async {
    final r = await _http.post('/v2/order/track/points', {
      'order_id': orderId,
      'points': points,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as bool);
  }

  /// 结束轨迹
  Future<BaseResponse<bool>> endTrack(int orderId) async {
    final r = await _http.post('/v2/order/track/end', {'order_id': orderId});
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as bool);
  }

  // ===== 拍照取证 =====

  /// 上传照片（实际通过 QiniuUploadService 走七牛，本接口只是返回 token）
  Future<BaseResponse<List<String>>> uploadPhotos(int orderId, List<String> localPaths) async {
    final r = await _http.post('/v2/order/photos', {
      'order_id': orderId,
      'paths': localPaths,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => (d as List).cast<String>());
  }

  // ===== 客户签字 =====

  /// 上传签名图片
  Future<BaseResponse<String>> uploadSignature(int orderId, String localPath) async {
    final r = await _http.post('/v2/order/signature', {
      'order_id': orderId,
      'path': localPath,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as String);
  }

  // ===== 收款 =====

  /// 生成支付订单（微信支付）
  Future<BaseResponse<WxPay>> createWxPay(int orderId, double amount) async {
    final r = await _http.post('/v2/pay/wx', {
      'order_id': orderId,
      'amount': amount,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => WxPay.fromJson(d as Map<String, dynamic>));
  }

  /// 生成收款二维码（技师二维码让客户扫码）
  Future<BaseResponse<String>> createPayQrCode(int orderId, double amount) async {
    final r = await _http.post('/v2/pay/qrcode', {
      'order_id': orderId,
      'amount': amount,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as String);
  }

  /// 现金收款确认
  Future<BaseResponse<bool>> confirmCashPay(int orderId, double amount) async {
    final r = await _http.post('/v2/pay/cash', {
      'order_id': orderId,
      'amount': amount,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => d as bool);
  }

  // ===== 完成 =====

  /// 提交完成（带金额明细）
  Future<BaseResponse<CompleteOrderInfo>> completeOrder({
    required int orderId,
    required List<AmountItem> amountItems,
    String? remark,
  }) async {
    final r = await _http.post('/v2/order/complete', {
      'order_id': orderId,
      'amount_items': amountItems.map((e) => e.toJson()).toList(),
      'remark': remark,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => CompleteOrderInfo.fromJson(d as Map<String, dynamic>));
  }

  // ===== 订单记录 =====

  /// 历史订单（已完成 / 已取消）
  Future<BaseResponse<PageResult<Order>>> historyOrders({
    int page = 1,
    int size = 20,
    String? status,
  }) async {
    final r = await _http.get('/v2/order/history', {
      'page': page,
      'size': size,
      if (status != null) 'status': status,
    });
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => PageResult.fromJson(d as Map<String, dynamic>, (e) => Order.fromJson(e as Map<String, dynamic>)));
  }

  /// 订单详情
  Future<BaseResponse<Order>> orderDetail(int orderId) async {
    final r = await _http.get('/v2/order/detail/$orderId');
    return BaseResponse.fromJson(r as Map<String, dynamic>,
        (d) => Order.fromJson(d as Map<String, dynamic>));
  }
}
