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:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/profile_page_router.dart';
import 'item_household.dart';
import 'my_household_view_model.dart';

@RoutePage()
class MyHouseholdPage extends HookConsumerWidget {
  const MyHouseholdPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const MyHouseholdPageRoute());
    } else {
      appRouter.push(const MyHouseholdPageRoute());
    }
  }

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

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.household_members,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: context.appColors.backgroundDark,
      body: 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: [
              //顶部的房产显示
              _buildEstateWidget(context),

              //房产内成员的列表
              SliverList(
                  delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return HouseholdItem(index: index, item: state.datas[index]);
                },
                childCount: state.datas.length,
              ))
            ],
          ),
        ),
      ),
    );
  }

  //顶部的房产布局
  Widget _buildEstateWidget(BuildContext context) {
    ;
    return SliverToBoxAdapter(
      child: MyTextView(
        UserConfigService.getState().user?.defaultUnit?.address ?? "",
        fontSize: 20,
        paddingLeft: 15,
        paddingRight: 15,
        paddingTop: 19,
        paddingBottom: 19,
        isFontMedium: true,
        textColor: context.appColors.textBlack,
      ),
    );
  }
}
