import 'package:cpt_form/modules/detail/detail_processing_fragment.dart';
import 'package:cpt_form/modules/form/form_types.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.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:router/ext/auto_router_extensions.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';

import '../../router/page/form_page_router.dart';
import 'detail_approved_fragment.dart';
import 'detail_not_approved_fragment.dart';
import 'form_detail_view_model.dart';

@RoutePage()
class FormDetailPage extends HookConsumerWidget {
  final String estateFormId;
  final String taskId;
  final String type;

  const FormDetailPage({
    Key? key,
    @PathParam() required this.estateFormId,
    @PathParam() required this.taskId,
    @PathParam() required this.type,
  }) : super(key: key);

  //启动当前页面
  static void startInstance({
    BuildContext? context,
    required String estateFormId,
    required String taskId,
    required String type,
  }) {
    if (context != null) {
      context.router.push(FormDetailPageRoute(estateFormId: estateFormId, taskId: taskId, type: type));
    } else {
      appRouter.push(FormDetailPageRoute(estateFormId: estateFormId, taskId: taskId, type: type));
    }
  }

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

    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask((){
        viewModel.setType(type);
        viewModel.fetchFormDetail(estateFormId, taskId);
      });
      return () {
        // 组件卸载时执行
      };
    }, []);

    return Scaffold(
      appBar: MyAppBar.appBar(context, FormTypes.iconMap[type]?['name'] ?? "", backgroundColor: context.appColors.backgroundWhite),
      backgroundColor: context.appColors.backgroundDark,
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: LoadStateLayout(
            state: state.loadingState,
            errorMessage: state.errorMessage,
            errorRetry: () {
              viewModel.retryRequest(estateFormId, taskId);
            },
            successWidget: state.status == 0
                ? DetailProcessingFragment()
                : state.status == 1
                    ? DetailApprovedFragment()
                    : DetailNotApprovedFragment()),
      ),
    );
  }
}
