import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/network/api_client.dart';
import '../../core/navigation/host_app_channel.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../app.dart';
import 'expense_apply_model.dart';
import 'expense_apply_api.dart';
import 'expense_apply_list_controller.dart';

final expenseApplyApprovalApiProvider = Provider<ExpenseApplyApprovalApi>(
  (ref) => ExpenseApplyApprovalApi(ref.read(apiClientProvider)),
);

class ApprovalListItem {
  final String bilId;
  final String bilNo;
  final String bilDate;
  final String applicant;
  final String dept;
  final double amount;
  final String remark;
  final String status;

  const ApprovalListItem({
    required this.bilId,
    required this.bilNo,
    required this.bilDate,
    required this.applicant,
    required this.dept,
    required this.amount,
    required this.remark,
    required this.status,
  });

  factory ApprovalListItem.fromJson(Map<String, dynamic> json) =>
      ApprovalListItem(
        bilId: json['bilId'] as String? ?? '',
        bilNo: json['bilNo'] as String? ?? '',
        bilDate: json['bilDate'] as String? ?? '',
        applicant: json['applicant'] as String? ?? '',
        dept: json['dept'] as String? ?? '',
        amount: (json['amount'] as num?)?.toDouble() ?? 0,
        remark: json['remark'] as String? ?? '',
        status: json['status'] as String? ?? 'pending',
      );

  ExpenseApplyModel toExpenseApplyModel() => ExpenseApplyModel(
        id: bilNo,
        expenseApplyNo: bilNo,
        expenseApplyDate:
            bilDate.isNotEmpty ? DateTime.tryParse(bilDate) : null,
        applicantId: applicant,
        applicantName: applicant,
        deptId: dept,
        deptName: dept,
        estimatedAmount: amount,
        purpose: remark,
        remark: '',
        status: status == 'approved' ? 'approved' : 'pending',
        createTime: DateTime.now(),
        updateTime: DateTime.now(),
      );
}

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

  Future<Map<String, dynamic>> fetchApprovalList({
    required String bilId,
    required String status,
    String erpCategory = 'MasterService',
    String keyword = '',
    String startDate = '',
    String endDate = '',
    int page = 1,
    int size = 20,
  }) async {
    final response = await _client.get<Map<String, dynamic>>(
      '/OA/GetApprovalList',
      queryParameters: {
        'bilId': bilId,
        'status': status,
        'erpCategory': erpCategory,
        'keyword': keyword,
        'startDate': startDate,
        'endDate': endDate,
        'page': page,
        'size': size,
      },
    );
    return response.data!;
  }
}

final expenseApplyApprovalListProvider =
    FutureProvider.autoDispose.family<List<ExpenseApplyModel>, String>(
  (ref, status) async {
    ref.watch(expenseApplyRefreshProvider);
    ref.watch(expenseApplyDateStartProvider);
    ref.watch(expenseApplyDateEndProvider);
    ref.watch(expenseApplyKeywordProvider);

    final api = ref.read(expenseApplyApprovalApiProvider);
    final dateStart = ref.read(expenseApplyDateStartProvider);
    final dateEnd = ref.read(expenseApplyDateEndProvider);
    final keyword = ref.read(expenseApplyKeywordProvider);

    final response = await api.fetchApprovalList(
      bilId: 'AE',
      keyword: keyword,
      status: status.isEmpty ? '' : status,
      startDate: dateStart != null ? du.DateUtils.formatDate(dateStart) : '',
      endDate: dateEnd != null ? du.DateUtils.formatDate(dateEnd) : '',
    );

    final list = (response['list'] as List<dynamic>?) ?? [];
    return list
        .map((e) =>
            ApprovalListItem.fromJson(e as Map<String, dynamic>)
                .toExpenseApplyModel())
        .toList();
  },
);

/// "我的申请单" 列表（制单人=当前用户，非审批流）
final expenseApplyMyListProvider =
    FutureProvider.autoDispose.family<List<ExpenseApplyModel>, String>(
  (ref, status) async {
    ref.watch(expenseApplyRefreshProvider);
    ref.watch(expenseApplyDateStartProvider);
    ref.watch(expenseApplyDateEndProvider);
    ref.watch(expenseApplyKeywordProvider);

    final api = ref.read(expenseApplyApiProvider);
    final dateStart = ref.read(expenseApplyDateStartProvider);
    final dateEnd = ref.read(expenseApplyDateEndProvider);
    final keyword = ref.read(expenseApplyKeywordProvider);

    final result = await api.fetchList(
      keyword: keyword,
      startDate: dateStart != null ? du.DateUtils.formatDate(dateStart) : '',
      endDate: dateEnd != null ? du.DateUtils.formatDate(dateEnd) : '',
      usr: HostAppChannel.usr,
      sortDir: ref.watch(expenseApplySortDirProvider),
    );
    return result.list;
  },
);
