import 'package:rasadyar_chicken/data/models/response/poultry_order/poultry_order.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/killing_registration/logic.dart';
import 'package:rasadyar_chicken/presentation/pages/poultry_science/root/logic.dart';
import 'package:rasadyar_core/core.dart';

class GenocideLogic extends GetxController {
  List<String> routesName = ['اقدام', 'درخواست کشتارها'];
  var tokenService = Get.find<TokenStorageService>();
  BaseLogic baseLogic = Get.find<BaseLogic>();
  var gService = Get.find<GService>();
  var rootLogic = Get.find<PoultryScienceRootLogic>();
  var killRegistration = Get.find<KillingRegistrationLogic>();

  Rx<Resource<PaginationModel<PoultryOrder>>> poultryOrderList =
      Resource<PaginationModel<PoultryOrder>>.loading().obs;

  RxInt expandedIndex = RxInt(-1);
  final RxInt currentPage = 1.obs;

  final RxBool isLoadingMore = false.obs;

  final RxBool isLoadingDelete = false.obs;

  Rx<Jalali> fromDateFilter = Jalali.now().obs;
  Rx<Jalali> toDateFilter = Jalali.now().obs;
  RxnString searchedValue = RxnString();

  /*  final RxBool isLoadingMoreAllocationsMade = false.obs;
  final RxBool isOnLoadingSubmitOrEdit = false.obs;*/

  @override
  void onReady() {
    super.onReady();
    getPoultryOrderList();
  }

  @override
  void onClose() {
    super.onClose();
    baseLogic.clearSearch();
  }

  Future<void> getPoultryOrderList([bool loadingMore = false]) async {
    if (loadingMore) {
      isLoadingMore.value = true;
    } else {
      poultryOrderList.value = Resource<PaginationModel<PoultryOrder>>.loading();
    }

    if (searchedValue.value != null &&
        searchedValue.value!.trim().isNotEmpty &&
        currentPage.value > 1) {
      currentPage.value = 1;
    }
    await safeCall(
      call: () async => await rootLogic.poultryRepository.getPoultryOderList(
        token: rootLogic.tokenService.accessToken.value!,
        queryParameters: buildQueryParams(
          pageSize: 20,
          page: currentPage.value,
          search: 'filter',
          role: gService.getRole(Module.chicken),
          value: searchedValue.value,
          fromDate: fromDateFilter.value.toDateTime(),
          toDate: toDateFilter.value.toDateTime(),
          queryParams: {'today': null},
        ),
      ),
      onSuccess: (res) async {
        await Future.delayed(Duration(milliseconds: 500));
        if ((res?.count ?? 0) == 0) {
          poultryOrderList.value = Resource<PaginationModel<PoultryOrder>>.empty();
        } else {
          if (loadingMore) {
            poultryOrderList.value = Resource<PaginationModel<PoultryOrder>>.success(
              PaginationModel<PoultryOrder>(
                count: res?.count ?? 0,
                next: res?.next,
                previous: res?.previous,
                results: [...(poultryOrderList.value.data?.results ?? []), ...(res?.results ?? [])],
              ),
            );
          } else {

            poultryOrderList.value = Resource<PaginationModel<PoultryOrder>>.success(res!);
          }
        }
      },
    );
  }

  Future<void> deletePoultryOrder(int id) async {
    toggleExpanded(-1);
    await safeCall(
      call: () async => await rootLogic.poultryRepository.deletePoultryOder(
        token: rootLogic.tokenService.accessToken.value!,
        orderId: id.toString(),
      ),
      onSuccess: (_) {
        defaultShowSuccessMessage('درخواست با موفقیت حذف شد');
      },
    );
  }

  void toggleExpanded(int index) {
    expandedIndex.value = expandedIndex.value == index ? -1 : index;
  }

  String getRequestType(PoultryOrder item) {
    if (item.market ?? false) {
      return 'پنل معاملات';
    } else if (item.union ?? false) {
      return 'اتحادیه';
    } else {
      return 'خرید مستقیم';
    }
  }

  String getKillType(PoultryOrder item) {
    if (item.export ?? false) {
      return 'صادرات';
    } else if (item.freezing ?? false) {
      return 'انجماد';
    } else {
      return 'عادی';
    }
  }

  String getState(PoultryOrder item) {
    if (item.stateProcess == 'pending') {
      return 'در انتظار تایید';
    } else {
      return 'تایید شده';
    }
  }


  Future<void> onRefresh() async {
    currentPage.value = 1;
    await getPoultryOrderList();

  }
}
