import 'dart:convert';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/network/api_client.dart';
import '../../shared/models/pagination_model.dart';
import '../../app.dart';
import 'vehicle_model.dart';

final vehicleApiProvider = Provider<VehicleApi>(
  (ref) => VehicleApi(ref.read(apiClientProvider)),
);

/// 部门项（复用自 expense_apply_api）
class DepartmentItem {
  final String dep;
  final String name;
  const DepartmentItem({required this.dep, required this.name});
  factory DepartmentItem.fromJson(Map<String, dynamic> json) =>
      DepartmentItem(dep: json['dep'] as String? ?? '', name: json['name'] as String? ?? '');
}

/// 员工项
class EmployeeItem {
  final String salNo;
  final String name;
  const EmployeeItem({required this.salNo, required this.name});
  factory EmployeeItem.fromJson(Map<String, dynamic> json) =>
      EmployeeItem(salNo: json['salNo'] as String? ?? '', name: json['name'] as String? ?? '');
}

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

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

  /// 用车申请详情
  Future<VehicleModel> fetchDetail(String billNo) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetVehicleApplyDetail',
      queryParameters: {'billNo': billNo},
    );
    return VehicleModel.fromJson(response.data!);
  }

  /// 提交审批，返回申请单号
  Future<String?> submit(Map<String, dynamic> data) async {
    final response = await _client.post<Map<String, dynamic>>(
      '/OA/BillSave',
      data: {
        'erpCategory': 'MasterService',
        'billId': 'VC',
        'procId': '',
        'data': data,
      },
    );
    final resData = response.data;
    if (resData == null) return null;

    final resultData = resData['resultData'];
    if (resultData is Map<String, dynamic>) {
      final bilNo = resultData['BIL_NO'] as String?;
      if (bilNo != null && bilNo.isNotEmpty) return bilNo;
    }
    if (resultData is String && resultData.isNotEmpty) {
      try {
        final parsed = json.decode(resultData) as Map<String, dynamic>;
        final bilNo = parsed['BIL_NO'] as String?;
        if (bilNo != null && bilNo.isNotEmpty) return bilNo;
      } catch (_) {}
    }
    final rootBilNo = resData['BIL_NO'] as String?;
    if (rootBilNo != null && rootBilNo.isNotEmpty) return rootBilNo;

    return null;
  }

  /// 还车登记
  Future<void> submitReturn(String billNo, Map<String, dynamic> returnData) async {
    await _client.post<Map<String, dynamic>>(
      '/OA/BillSave',
      data: {
        'erpCategory': 'MasterService',
        'billId': 'VC',
        'procId': '',
        'data': {
          'HeadData': {
            'YC_NO': billNo,
            'IS_RETURN': 'T',
            'RETURN_TIME': returnData['returnTime'],
            'ODOMETER': returnData['odometer'],
            'AMTN': returnData['amtn'],
            'REMARK': returnData['remark'],
          },
        },
      },
    );
  }

  /// 获取单据状态
  Future<Map<String, dynamic>> getBillStatus(String billNo) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetBillStatus',
      queryParameters: {'billId': 'VC', 'billNo': billNo},
    );
    return response.data!;
  }

  /// 部门查询
  Future<List<DepartmentItem>> getDepartments({
    String keyword = '',
    bool onlyActive = true,
    int page = 1,
    int size = 100,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetDepartments',
      queryParameters: {
        'keyword': keyword,
        'onlyActive': onlyActive,
        'page': page,
        'size': size,
      },
    );
    final list = (response.data?['list'] as List<dynamic>?) ?? [];
    return list
        .map((e) => DepartmentItem.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  /// 员工查询
  Future<List<EmployeeItem>> getEmployees({
    String keyword = '',
    String salNo = '',
    int page = 1,
    int size = 100,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetEmployees',
      queryParameters: {
        'keyword': keyword,
        'salNo': salNo,
        'page': page,
        'size': size,
      },
    );
    final list = (response.data?['list'] as List<dynamic>?) ?? [];
    return list
        .map((e) => EmployeeItem.fromJson(e as Map<String, dynamic>))
        .toList();
  }
}
