import 'package:domain/entity/facility_book_entity.dart';
import 'package:domain/repository/facility_repository.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import '../../router/page/facility_page_router.dart';
import '../book_confirm/book_confirm_page.dart';
import '../detail/facility_detail_page.dart';
import 'facility_booking_state.dart';

part 'facility_booking_view_model.g.dart';

@riverpod
class FacilityBookingViewModel extends _$FacilityBookingViewModel with DioCancelableMixin {
  late final FacilityRepository _facilityRepository;

  @override
  FacilityBookingState build() {
    _facilityRepository = ref.read(facilityRepositoryProvider);

    final state = FacilityBookingState(
      selectedDate: DateTime.now(),
    );
    initListener(state);
    registerCancellation(callback: () {
      onDispose(state);
    });

    return state;
  }

  //设置设施的ID
  void setFacilityId(String? facilityId, String? facilityName) {
    state = state.copyWith(facilityId: facilityId, facilityName: facilityName);
  }

  //修改选中的时间
  void changeSelectedDate(DateTime dateTime) {
    state = state.copyWith(selectedDate: dateTime);
    Log.d("当前选中的日期：$dateTime");
    fetchListByDate();
  }

  //失败的重试
  void retryRequest() {
    fetchListByDate();
  }

  /// 获取服务器数据
  Future fetchListByDate() async {
    state = state.copyWith(loadingState: LoadState.State_Loading);

    // 获取列表
    var result = await _facilityRepository.fetchFacilityDateDetail(
      id: state.facilityId,
      date: state.selectedDate,
      cancelToken: cancelToken,
    );

    // 处理数据
    if (result.isSuccess) {
      if (result.data != null) {
        //有数据
        state = state.copyWith(data: result.data, bookAdvanceDays: result.data?.facilityType?.bookAdvanceDays ?? 0, loadingState: LoadState.State_Success);
      } else {
        //展示无数据的布局
        state = state.copyWith(data: null, loadingState: LoadState.State_Empty, errorMessage: null);
      }
    } else {
      state = state.copyWith(data: null, loadingState: LoadState.State_Error, errorMessage: result.errorMsg);
    }
  }

  void initListener(FacilityBookingState state) {
    Log.d("FacilityBookingViewModel - initListener");
  }

  void onDispose(FacilityBookingState state) {
    Log.d("FacilityBookingViewModel - onDispose");
  }

  //去付款确认页面
  void gotoConfirmPage() {
    if (state.data == null) return;

    //找到数据中的已选中数据
    final selectedPeriods = <FacilityBookFacilitiesPeriods>[];
    for (var facility in state.data!.facilities!) {
      final periods = facility.periods ?? [];

      // 筛选出已选中的 periods，并添加到结果列表
      selectedPeriods.addAll(
        periods.where((period) => period.selected).toList(),
      );
    }

    if (selectedPeriods.isEmpty) {
      ToastEngine.show("Select Facility And Date");
    } else {
      BookConfirmPage.startInstance();
    }
  }

  //选中指定的Task
  void selectPeriods(int index, int innerIndex) {
    // 创建新的 periods 列表来更新状态
    final updatedFacilities = state.data!.facilities!.map((facility) {
      // 创建新的 periods 列表
      final updatedPeriods = facility.periods!.map((period) {
        return FacilityBookFacilitiesPeriods()
          ..id = period.id
          ..start = period.start
          ..end = period.end
          ..price = period.price
          ..deposit = period.deposit
          ..enable = period.enable
          ..selected = false; // 设置默认未选中
      }).toList();

      return FacilityBookFacilities()
        ..id = facility.id
        ..name = facility.name
        ..periods = updatedPeriods;
    }).toList();

    // 设置指定索引的 selected 为 true
    updatedFacilities[index].periods?[innerIndex].selected = true;

    // 更新 FacilityBookEntity 的状态
    state = state.copyWith(
      data: FacilityBookEntity()
        ..remainQuota = state.data!.remainQuota
        ..quotaResetOn = state.data!.quotaResetOn
        ..facilityType = state.data!.facilityType
        ..facilities = updatedFacilities, //只更新了facilities对象
      index: index,
      innerIndex: innerIndex,
    );
  }

  //确认页面执行支付
  void doPayment() async {
    //支付流程 Loading 开始
    LoadingEngine.show();

    final result = await _facilityRepository.submitBooking(
      periodId: state.data?.facilities?[state.index].periods?[state.innerIndex].id,
      date: state.selectedDate,
      cancelToken: cancelToken,
    );

    LoadingEngine.dismiss();

    if (result.isSuccess) {
      final bookingId = result.data?.booking?.id;
      String orderId = result.data?.order?.id ?? "";

      Log.d("当前 Facility 生成的订单ID:$orderId");
      // 暂时直接进入线下支付页面
      ComponentServiceManager().paymentService.startWithPopOfflinePaymentPage('FacilityPageRoute');


      // //调用支付服务
      // bool success = await ComponentServiceManager().paymentService.executePayment(orderId: orderId);
      //
      // //支付流程 Loading 结束
      // LoadingEngine.dismiss();
      //
      // //如果成功，走下一步流程
      // if (success) {
      //   FacilityDetailPage.startWithPop2Main(bookingId: bookingId);
      // }else{
      //   //如果失败需要关闭到跟页面，并且跳转到详情的支付页面
      //   appRouter.pushAndPopUntil(
      //     FacilityDetailPageRoute(bookingId: bookingId),
      //     predicate: (route) {
      //       return route.settings.name == 'FacilityPageRoute';
      //     },
      //   );
      // }
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //确认页面选择银行卡页面
  void gotoChooseCardPage() {
    ComponentServiceManager().paymentService.startChooseCardPage();
  }
}
