import 'package:domain/repository/form_repository.dart';
import 'package:plugin_platform/engine/loading/loading_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:widgets/load_state_layout.dart';

import 'form_detail_state.dart';

part 'form_detail_view_model.g.dart';

@riverpod
class FormDetailViewModel extends _$FormDetailViewModel with DioCancelableMixin {
  late final FormRepository _formRepository;

  @override
  FormDetailState build() {
    _formRepository = ref.read(formRepositoryProvider);
    final state = FormDetailState();
    registerCancellation();
    return state;
  }

  void setType(String type) {
    state = state.copyWith(typeId: type);
  }

  void retryRequest(String? estateFormId, String? taskId) {
    fetchFormDetail(estateFormId, taskId);
  }

  //获取表单的详情数据
  void fetchFormDetail(String? estateFormId, String? taskId) async {
    //显示加载数据
    state = state.copyWith(loadingState: LoadState.State_Loading);

    final result = await _formRepository.fetchFormDetail(estateFormId: estateFormId, taskId: taskId);

    //根据后端返回的数据赋值状态
    if (result.isSuccess) {
      state = state.copyWith(loadingState: LoadState.State_Success, status: result.data?.status, forDetail: result.data, estateFormId: estateFormId);
    } else {
      state = state.copyWith(loadingState: LoadState.State_Error, errorMessage: result.errorMsg);
    }
  }

  //根据OrderId继续支付订单
  // void doPaymentOrder(String orderId) async {
  //   //支付流程 Loading 开始
  //   LoadingEngine.show();
  //
  //   //调用支付服务
  //   bool success = await ComponentServiceManager().paymentService.executePayment(orderId: orderId);
  //
  //   //支付流程 Loading 结束
  //   LoadingEngine.dismiss();
  //
  //   //如果成功，返回页面
  //   if (success) {
  //     appRouter.maybePop();
  //   }
  // }
}
