import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/network/api_client.dart';
import '../../core/network/api_response.dart';
import '../../app.dart';
import '../../shared/models/pagination_model.dart';
import 'expense_model.dart';

final expenseApiProvider = Provider<ExpenseApi>(
  (ref) => ExpenseApi(ref.read(apiClientProvider)),
);

class ExpenseApi {
  final ApiClient _client;
  ExpenseApi(this._client);

  /// 费用报销列表（分页）
  Future<PaginatedData<ExpenseModel>> fetchList({
    String status = '',
    String keyword = '',
    String startDate = '',
    String endDate = '',
    String usr = '',
    int page = 1,
    int size = 20,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetExpenseReports',
      queryParameters: {
        'status': status,
        'keyword': keyword,
        'startDate': startDate,
        'endDate': endDate,
        'usr': usr,
        'page': page,
        'size': size,
      },
    );
    return PaginatedData.fromJson(response.data!, ExpenseModel.fromJson);
  }

  /// 费用报销详情（主表+明细）
  Future<ExpenseModel> fetchDetail(String billNo) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetExpenseReportDetail',
      queryParameters: {'billNo': billNo},
    );
    return ExpenseModel.fromJson(response.data!);
  }

  /// 提交审批
  Future<void> submit(Map<String, dynamic> data) async {
    await _client.post('/OA/BillSave', data: {
      'erpCategory': 'MasterService',
      'billId': 'BX',
      'procId': '',
      'data': data,
    });
  }

  /// 财务核销
  Future<void> verify(Map<String, dynamic> data) async {
    await _client.post('/OA/ExpenseVerify', data: data);
  }

  /// 币别查询
  Future<ApiResponse<Map<String, dynamic>>> fetchCurrencies({
    String keyword = '',
    int page = 1,
    int size = 50,
  }) async {
    return await _client.get('/OA/GetCurrencies',
        queryParameters: {'keyword': keyword, 'page': page, 'size': size});
  }
}
