import 'package:cpt_profile/modules/change_mobile/change_mobile_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/user_me_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:router/componentRouter/component_service_manager.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/widget_export.dart';
import '../../router/page/profile_page_router.dart';
import 'item_estate.dart';
import 'item_estate_header.dart';
import 'my_estate_view_model.dart';

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

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

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

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.yy_home_accounts,
        backgroundColor: context.appColors.backgroundWhite,
      ),
      backgroundColor: context.appColors.backgroundDark,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          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 StickyHeader(
                      header: EstateItemHeader(state.datas[index].name),
                      content: Column(
                        children: _buildGroup(state.datas[index].accounts!, index,viewModel),
                      ),
                    );
                  },
                  childCount: state.datas.length,
                ))
              ],
            ),
          ).expanded(),
          MyButton(
            onPressed: () {
              ComponentServiceManager().authService.startSelectEstatePage();
            },
            text: S.current.add,
            textColor: Colors.white,
            backgroundColor: context.appColors.btnBgDefault,
            fontWeight: FontWeight.w500,
            type: ClickType.throttle,
            fontSize: 16,
            minHeight: 50,
            radius: 0,
          )
        ],
      ),
    );
  }

  //当前组内的子数据
  List<Widget> _buildGroup(List<UserMeEstatesAccounts> list, int index, MyEstateViewModel viewModel) {
    return list
        .asMap()
        .map((childIndex, item) {
          return MapEntry(
              childIndex,
              EstateItem(
                item: item,
                childIndex: childIndex,
                itemAction: (){
                  viewModel.setEstateUnitDefault(item);
                },
                deleteAction: () {
                  viewModel.showRemoveEstateDialog(item.unit?.id);
                },
              ));
        })
        .values
        .toList();
  }
}
