import 'package:dio/dio.dart';
import 'mock_data.dart';

class MockInterceptor extends Interceptor {
  final bool enabled;

  MockInterceptor({this.enabled = false});

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (!enabled) {
      handler.next(options);
      return;
    }

    final path = options.path;
    final params = options.queryParameters;
    final mockData = _matchMock(path, params);

    if (mockData != null) {
      Future.delayed(const Duration(milliseconds: 300), () {
        handler.resolve(
          Response(requestOptions: options, statusCode: 200, data: mockData),
        );
      });
    } else {
      handler.resolve(
        Response(
          requestOptions: options,
          statusCode: 200,
          data: {'code': 0, 'message': 'ok', 'data': null},
        ),
      );
    }
  }

  Map<String, dynamic>? _matchMock(String path, Map<String, dynamic> params) {
    final status = params['status'] as String? ?? '';
    final page = params['page'] as String? ?? '1';

    if (path == '/home/summary') return MockData.homeSummary;

    // ==================== 费用报销 ====================
    if (path == '/OA/GetExpenseList') {
      var list = MockData.expenseList;
      if (status.isNotEmpty) {
        list = list.where((e) => e['status'] == status).toList();
      }
      return _paginate(list, page);
    }
    if (path == '/OA/GetExpenseDetail') {
      final billNo = params['billNo'] ?? '';
      return MockData.expenseDetail(billNo);
    }
    if (path == '/OA/BillSave' || path == '/OA/ExpenseVerify') {
      return MockData.success;
    }

    // ==================== 事前申请 ====================
    if (path == '/OA/GetExpenseApplyList') {
      var list = MockData.expenseApplicationList;
      if (status.isNotEmpty) {
        list = list.where((e) => e['status'] == status).toList();
      }
      return _paginate(list, page);
    }
    if (path == '/OA/GetExpenseApplyDetail') {
      final billNo = params['billNo'] ?? '';
      return MockData.expenseApplicationDetail(billNo);
    }
    if (path == '/OA/GetCurrencies') {
      return {
        'code': 0,
        'message': 'success',
        'data': _paginate(MockData.currencies, page),
      };
    }
    if (path == '/OA/GetCostTypes') {
      return {
        'code': 0,
        'message': 'success',
        'data': _paginate(MockData.costTypes, page),
      };
    }
    if (path == '/OA/GetProjectCodes') {
      return {
        'code': 0,
        'message': 'success',
        'data': _paginate(MockData.projectCodes, page),
      };
    }
    if (path == '/OA/GetDepartments') {
      return {
        'code': 0,
        'message': 'success',
        'data': _paginate(MockData.departments, page),
      };
    }
    if (path == '/OA/GetCustomers') {
      return {
        'code': 0,
        'message': 'success',
        'data': _paginate(MockData.customers, page),
      };
    }
    if (path == '/OA/GetApprovalTimeline') {
      return {
        'code': 0,
        'message': 'success',
        'data': MockData.approvalTimeline,
      };
    }
    if (path == '/OA/GetApprovalList') {
      var list = MockData.approvalList;
      if (status.isNotEmpty) {
        list = list.where((e) => e['status'] == status).toList();
      }
      return _paginate(list, page);
    }

    // ==================== 加班 ====================
    if (path == '/overtime/list') {
      var list = MockData.overtimeList;
      if (status.isNotEmpty) {
        list = list.where((e) => e['status'] == status).toList();
      }
      return _paginate(list, page);
    }
    if (path.startsWith('/overtime/detail/')) {
      return MockData.overtimeDetail(path.split('/').last);
    }
    if (path == '/overtime/apply' || path == '/overtime/draft') {
      return MockData.success;
    }

    // ==================== 用车 ====================
    if (path == '/vehicle/list') {
      var list = MockData.vehicleList;
      if (status.isNotEmpty) {
        list = list.where((e) => e['status'] == status).toList();
      }
      return _paginate(list, page);
    }
    if (path.startsWith('/vehicle/detail/')) {
      return MockData.vehicleDetail(path.split('/').last);
    }
    if (path == '/vehicle/apply' || path == '/vehicle/draft') {
      return MockData.success;
    }
    if (path == '/vehicle/return') {
      return MockData.success;
    }
    if (path == '/vehicle/check-collision') {
      return {
        'code': 0,
        'message': 'ok',
        'data': {'collision': false},
      };
    }

    // ==================== 外出日志 ====================
    if (path == '/outing-log/list') {
      return _paginate(MockData.outingLogList, page);
    }
    if (path.startsWith('/outing-log/detail/')) {
      return MockData.outingLogDetail(path.split('/').last);
    }
    if (path == '/outing-log/create') return MockData.success;
    if (path == '/outing-log/view') return MockData.success;
    if (path == '/outing-log/comment') {
      return {
        'code': 0,
        'message': 'ok',
        'data': {
          'id': 'comment-001',
          'logId': path.split('/').last,
          'commenterId': 'U100',
          'commenterName': '李经理',
          'ratingStars': 5,
          'commentText': '工作认真，继续保持。',
          'createTime': DateTime.now().toIso8601String(),
        },
      };
    }

    // ==================== 公告 ====================
    if (path == '/announcement/list') {
      return _paginate(MockData.announcementList, page);
    }
    if (path.startsWith('/announcement/detail/')) {
      return MockData.announcementDetail(path.split('/').last);
    }

    // ==================== 报表 ====================
    if (path.startsWith('/report/expense-detail/')) {
      return MockData.expenseReportDetail(path.split('/').last);
    }
    if (path.startsWith('/report/expense-apply-detail/')) {
      return MockData.expenseApplyReportDetail(path.split('/').last);
    }
    if (path.startsWith('/report/overtime-detail/')) {
      return MockData.overtimeReportDetail(path.split('/').last);
    }
    if (path.startsWith('/report/vehicle-detail/')) {
      return MockData.vehicleReportDetail(path.split('/').last);
    }

    return null;
  }

  Map<String, dynamic> _paginate(
    List<Map<String, dynamic>> list,
    String pageStr,
  ) {
    final page = int.tryParse(pageStr) ?? 1;
    const size = 20;
    return {
      'code': 0,
      'message': 'ok',
      'data': {'list': list, 'page': page, 'size': size, 'total': list.length},
    };
  }
}
