import 'package:domain/entity/payment_page_entity.dart';
import 'package:domain/repository/payment_repository.dart';
import 'package:plugin_basic/constants/app_constant.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:shared/utils/event_bus.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../../payment_confirm/payment_confirm_page.dart';
import 'payment_list_state.dart';

part 'payment_list_view_model.g.dart';

@riverpod
class PaymentListViewModel extends _$PaymentListViewModel with DioCancelableMixin {
  late final PaymentRepository _paymentRepository;
  var _curPage = 1; //请求参数当前的页面
  var _needShowPlaceholder = true; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: true, //允许加载
  );

  @override
  PaymentListState build() {
    _paymentRepository = ref.read(paymentRepositoryProvider);
    final state = PaymentListState(datas: []);

    registerEventBus();
    registerCancellation(callback: () {
      unregisterEventBus();
    });

    return state;
  }

  //刷新页面状态
  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(loadingState: loadState, errorMessage: errorMsg);
  }

  // Refresh 刷新事件
  Future onRefresh() async {
    _curPage = 1;
    fetchList();
  }

  // Refresh 加载事件
  Future loadMore() async {
    _curPage++;
    fetchList();
  }

  // 重试请求
  Future retryRequest() async {
    _curPage = 1;
    _needShowPlaceholder = true;
    fetchList();
  }

  /// 获取服务器数据
  Future fetchList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // 获取列表
    var listResult = await _paymentRepository.fetchPaymentList(
      type: 'pending',
      curPage: _curPage,
      cancelToken: cancelToken,
    );

    // 处理数据
    if (listResult.isSuccess) {
      handleList(listResult.data?.list);
    } else {
      changeLoadingState(LoadState.State_Error, listResult.errorMsg);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<PaymentPageList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_curPage == 1) {
        //刷新的方式
        state = state.copyWith(datas: list);
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        state.datas.addAll(List<PaymentPageList>.from(state.datas)..addAll(list));
        refreshController.finishLoad();
      }
    } else {
      if (_curPage == 1) {
        //展示无数据的布局
        state = state.copyWith(datas: []);
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }

  /// 根据类型跳转到不同的支付页面去支付
  void gotoPaymentPage(PaymentPageList data) {
    switch (data.type) {
      case 'facility_booking':
        //设施预定订单
        ComponentServiceManager().facilityService.startFacilityDetailPage(id: data.orderable?.id ?? "");
        break;
      case 'online_form_apply':
        //在线表单订单
        ComponentServiceManager().formService.startFormDetailPage(
              data.orderable?.estateOnlineFormId ?? "",
              data.orderable?.id ?? "",
              data.orderable?.onlineFormTypeId ?? "",
            );
        break;
      case 'paid_service_order':
        //服务订单
        ComponentServiceManager().servicesService.startServiceOrderDetailPage(data.orderable?.id ?? "");
        break;
      default:
        //默认周期订单的支付 (通用支付页面)
        PaymentConfirmPage.startInstance(
          title: data.title,
          orderId: data.id,
          amount: data.orderAmount,
          deposit: data.depositAmount,
        );
        break;
    }
  }

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventStripePaymentSuccess, (arg) {
      //用户支付成功的通知
      refreshController.callRefresh();
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventStripePaymentSuccess, subscribe);
  }
}
