import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// 门店和员工管理服务
class IssuerStoreService {
  final ApiClient _apiClient;

  IssuerStoreService({ApiClient? apiClient})
      : _apiClient = apiClient ?? ApiClient.instance;

  // ==================== 门店 ====================

  /// 获取门店列表
  Future<List<StoreModel>> listStores({
    String? level,
    String? parentId,
    String? status,
  }) async {
    try {
      final params = <String, dynamic>{};
      if (level != null) params['level'] = level;
      if (parentId != null) params['parentId'] = parentId;
      if (status != null) params['status'] = status;

      final response = await _apiClient.get(
        '/api/v1/issuers/me/stores',
        queryParameters: params,
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      final list = inner is List ? inner : (inner['items'] ?? []);
      return (list as List)
          .map((e) => StoreModel.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (e) {
      debugPrint('[IssuerStoreService] listStores 失败: $e');
      rethrow;
    }
  }

  /// 创建门店
  Future<StoreModel> createStore(Map<String, dynamic> body) async {
    try {
      final response = await _apiClient.post('/api/v1/issuers/me/stores', data: body);
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return StoreModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerStoreService] createStore 失败: $e');
      rethrow;
    }
  }

  /// 更新门店
  Future<void> updateStore(String id, Map<String, dynamic> body) async {
    try {
      await _apiClient.put('/api/v1/issuers/me/stores/$id', data: body);
    } catch (e) {
      debugPrint('[IssuerStoreService] updateStore 失败: $e');
      rethrow;
    }
  }

  /// 删除门店
  Future<void> deleteStore(String id) async {
    try {
      await _apiClient.delete('/api/v1/issuers/me/stores/$id');
    } catch (e) {
      debugPrint('[IssuerStoreService] deleteStore 失败: $e');
      rethrow;
    }
  }

  // ==================== 员工 ====================

  /// 获取员工列表
  Future<List<EmployeeModel>> listEmployees({
    String? storeId,
    String? role,
  }) async {
    try {
      final params = <String, dynamic>{};
      if (storeId != null) params['storeId'] = storeId;
      if (role != null) params['role'] = role;

      final response = await _apiClient.get(
        '/api/v1/issuers/me/employees',
        queryParameters: params,
      );
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      final list = inner is List ? inner : (inner['items'] ?? []);
      return (list as List)
          .map((e) => EmployeeModel.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (e) {
      debugPrint('[IssuerStoreService] listEmployees 失败: $e');
      rethrow;
    }
  }

  /// 创建员工
  Future<EmployeeModel> createEmployee(Map<String, dynamic> body) async {
    try {
      final response = await _apiClient.post('/api/v1/issuers/me/employees', data: body);
      final data = response.data is Map<String, dynamic> ? response.data : {};
      final inner = data['data'] ?? data;
      return EmployeeModel.fromJson(inner as Map<String, dynamic>);
    } catch (e) {
      debugPrint('[IssuerStoreService] createEmployee 失败: $e');
      rethrow;
    }
  }

  /// 更新员工
  Future<void> updateEmployee(String id, Map<String, dynamic> body) async {
    try {
      await _apiClient.put('/api/v1/issuers/me/employees/$id', data: body);
    } catch (e) {
      debugPrint('[IssuerStoreService] updateEmployee 失败: $e');
      rethrow;
    }
  }

  /// 删除员工
  Future<void> deleteEmployee(String id) async {
    try {
      await _apiClient.delete('/api/v1/issuers/me/employees/$id');
    } catch (e) {
      debugPrint('[IssuerStoreService] deleteEmployee 失败: $e');
      rethrow;
    }
  }
}

class StoreModel {
  final String id;
  final String name;
  final String? address;
  final String? phone;
  final String level;
  final String? parentId;
  final String status;
  final DateTime createdAt;

  const StoreModel({
    required this.id,
    required this.name,
    this.address,
    this.phone,
    required this.level,
    this.parentId,
    required this.status,
    required this.createdAt,
  });

  factory StoreModel.fromJson(Map<String, dynamic> json) {
    return StoreModel(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      address: json['address'],
      phone: json['phone'],
      level: json['level'] ?? 'store',
      parentId: json['parentId'],
      status: json['status'] ?? 'active',
      createdAt: DateTime.tryParse(json['createdAt']?.toString() ?? '') ?? DateTime.now(),
    );
  }
}

class EmployeeModel {
  final String id;
  final String name;
  final String? phone;
  final String role;
  final String? storeId;
  final String status;
  final DateTime createdAt;

  const EmployeeModel({
    required this.id,
    required this.name,
    this.phone,
    required this.role,
    this.storeId,
    required this.status,
    required this.createdAt,
  });

  factory EmployeeModel.fromJson(Map<String, dynamic> json) {
    return EmployeeModel(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      phone: json['phone'],
      role: json['role'] ?? 'staff',
      storeId: json['storeId'],
      status: json['status'] ?? 'active',
      createdAt: DateTime.tryParse(json['createdAt']?.toString() ?? '') ?? DateTime.now(),
    );
  }
}
