import 'package:auto_route/auto_route.dart';
import 'package:cpt_form/modules/apply/form_terms_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'form_apply_view_model.dart';
import 'item_form_apply.dart';

@RoutePage()
class FormApplyScreen extends HookConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(formApplyViewModelProvider.notifier);
    final state = ref.watch(formApplyViewModelProvider);

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

    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: EasyRefresh(
        controller: viewModel.refreshController,
        onRefresh: viewModel.onRefresh,
        child: LoadStateLayout(
          state: state.loadingState,
          errorMessage: state.errorMessage,
          errorRetry: () {
            viewModel.retryRequest();
          },
          successSliverWidget: [
            SliverList(
                delegate: SliverChildBuilderDelegate(
              (context, index) {
                return FormApplyItem(index: index, item: state.datas[index]).onTap(() {
                  //进入申请的协议页面
                  FormTermsPage.startInstance(
                    formType: state.datas[index].typeId!,
                    enableEdit: true,
                    estateFormId: state.datas[index].id!,
                    formItem: state.datas[index],
                    description: state.datas[index].description,
                  );
                });
              },
              childCount: state.datas.length,
            ))
          ],
        ),
      ).marginOnly(top: 5, bottom: 5),
    );
  }
}
