import 'package:cpt_form/modules/apply/vm/apply_view_model.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/form_content_entity.dart';
import 'package:domain/entity/form_list_entity.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/widget/webview_page.dart';
import 'package:router/ext/auto_router_extensions.dart';
import '../../router/page/form_page_router.dart';

//协议页面，也是详情页面的第一个页面入口，内部可以请求详情数据和选项数据
@RoutePage()
class FormTermsPage extends HookConsumerWidget {
  final String type;
  final String? estateFormId;
  final FormListEntity? formItem;
  final bool enableEdit;
  final FormContentEntity? formContent;

  const FormTermsPage({Key? key, required this.type, this.estateFormId, this.formItem, required this.enableEdit, this.formContent}) : super(key: key);

  //启动当前页面
  static void startInstance({
    BuildContext? context,
    required String formType,
    String? estateFormId,
    FormListEntity? formItem,
    required bool enableEdit,
    FormContentEntity? formContent,
  }) {
    if (context != null) {
      context.router.push(FormTermsPageRoute(
        type: formType,
        formItem: formItem,
        enableEdit: enableEdit,
        formContent: formContent,
        estateFormId: estateFormId,
      ));
    } else {
      appRouter.push(FormTermsPageRoute(
        type: formType,
        formItem: formItem,
        enableEdit: enableEdit,
        formContent: formContent,
        estateFormId: estateFormId,
      ));
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.watch(applyViewModelProvider.notifier);
    final state = ref.watch(applyViewModelProvider);

    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => viewModel.setFormType(type, estateFormId, formItem, enableEdit, formContent));
      return () {
        // 组件卸载时执行
      };
    }, []);

    return state.detailPage != null
        ? WebViewPage(
            showAppbar: true,
            initialUrl: state.detailPage?['term_url'],
            arguments: {'title': state.detailPage?['title']},
            bottomBtnTxt: S.current.next,
            bottomBtnAction: viewModel.gotoNextPage,
          )
        : const SizedBox();
  }
}
