import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../transaction/model/payment_method_model.dart';
import 'models/customer_contract_object_model.dart';
import 'models/electric_payment_response_model.dart';

class ElectricPaymentBillViewModel extends RestfulApiViewModel {
  final RxList<PaymentMethodModel> paymentMethods = <PaymentMethodModel>[].obs;
  final RxInt selectedPaymentMethodIndex = 0.obs;
  void Function(ElectricPaymentResponseModel data)? customerEvnPaymentGatewayResponse;
  void Function(String message)? onShowAlertError;

  Future<void> getPaymentMethods() async {
    await callApi<List<PaymentMethodModel>>(
      request: () => client.getPreviewPaymentMethods(),
      onSuccess: (data, _) {
        selectedPaymentMethodIndex.value = 0;
        paymentMethods.assignAll(data);
      },
      onFailure: (_, _, _) async {},
    );
  }

  Future<void> customerEvnPaymentGatewayRequest(CustomerContractModel bill) async {
    final paymentMethod = paymentMethods.safe(selectedPaymentMethodIndex.value) ?? paymentMethods.firstOrNull;
    final paymentMethodType = paymentMethod?.type?.methodBillEVN ?? '';
    if (paymentMethodType.isEmpty) {
      onShowAlertError?.call("Vui lòng chọn phương thức thanh toán.");
      return;
    }
    await callApi<ElectricPaymentResponseModel>(
      request: () => client.customerEvnPaymentGatewayRequest(bill, paymentMethodType),
      onSuccess: (data, _) {
        customerEvnPaymentGatewayResponse?.call(data);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
      defaultError: "Lỗi khi thanh toán, vui lòng thử lại sau.",
    );
  }
}
