import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/garage_sale_rent_entity.dart';
import 'package:domain/entity/repair_service_entity.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:plugin_basic/provider/app_config/app_config_service.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/screen_util.dart';
import 'package:shared/utils/size_config.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_button.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/my_appbar.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:widgets/widget_export.dart';

import '../../../router/page/services_page_router.dart';
import 'home_service_vm.dart';
import 'service_card_item.dart';

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

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


  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(repairHomeServiceVmProvider.notifier);
    final state = ref.watch(repairHomeServiceVmProvider);
    // final appConfigState = ref.watch(appConfigServiceProvider)


    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
        Log.d("garage_RepairHomeService_page 组件卸载时执行");
      };
    }, []);

    return Scaffold(
      // appBar: MyAppBar.appBar(
      //   context,
      //   "RepairHomeService",
      //   backgroundColor: context.appColors.whiteBG,
      // ),
      backgroundColor: ColorUtils.string2Color("#F2F3F6"),
      body: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Column(
            children: [
              // sort and filter
              _buildSortAndFilter(context, ref, vm, state),
              Expanded(
                child: EasyRefresh(
                  key: ValueKey('RepairHomeService'),
                  controller: vm.refreshController,
                  // 上拉加载
                  onLoad: () async{
                    Log.d("----onLoad");
                    vm.loadMore();
                  },
                  // 下拉刷新
                  onRefresh: () async{
                    Log.d("----onRefresh");
                    vm.onRefresh();
                  },
                  child: LoadStateLayout(
                    state: state.loadingState,
                    errorMessage: state.errorMessage,
                    errorRetry: () {
                      vm.retryRequest();
                    },
                    successSliverWidget:[
                      SliverGrid(
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2, // 每行显示两个项目
                          mainAxisSpacing: 15,
                          crossAxisSpacing: 15,
                          // childAspectRatio: 172.5/170, // 宽高比
                          childAspectRatio: 180/200, // 宽高比
                          // childAspectRatio:  172.5/170 * ScreenUtil.getAdapterSizeCtx(context, 172.5/170), // 宽高比
                          // childAspectRatio:  172.5/170 * ((172.5/170).ap), // 宽高比
                        ),
                        delegate: SliverChildBuilderDelegate(
                              (context, index) {
                            return  _buildRepairHomeServiceItem(context, ref, state.list[index] as RepairServiceList, vm).onTap((){
                              // 去详情页面
                              RepairServiceList repairServiceEntity = state.list[index] as RepairServiceList;
                              RepairServiceListCategory repairServiceCategory = repairServiceEntity.category!;
                              vm.handlerGotoDetail(context: context, id: repairServiceEntity.id!, repairServiceListCategory: repairServiceCategory!);

                            });
                          },
                          childCount: state.list.length,
                        ),
                      ),
                    ],
                  ),
                ).marginOnly(left: 15,right: 15,top: 15,bottom: 15),
              ),
            ],
          )
      ),
    );
  }

  Widget _buildRepairHomeServiceItem(BuildContext context, WidgetRef ref, RepairServiceList item, vm){
    return SizedBox(
      width: double.infinity,
      // height: 170,
      child: Container(
        decoration: BoxDecoration(
          color: context.appColors.whiteBG,
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: ColorUtils.string2Color('#E5E5E5'),
              offset: const Offset(0, 2),
              blurRadius: 8,
            ),
          ],
        ),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
              // 卡片头部(头像 标题 时间)
              Expanded(
                child: RepairHomeServiceCard(
                    key: UniqueKey(),
                    itemEntity: item,
                    cleanServiceType: item.category!.type,
                    onClickColleciotn: (dynamic collectionValue) async {
                      Log.d("点击了喜欢按钮  --id:${item.id}- $collectionValue");
                      int id = item.id!;
                      return await vm.handlerClickCollection(id, collectionValue);
                    }
                ),
              ),
            ]
        ),
      ),
    );
  }

  Widget _buildSortAndFilter(BuildContext context, WidgetRef ref, vm, state) {
    final sortTitle = ref.watch(repairHomeServiceVmProvider.select((state) => state.sortBySelectedOption));

    final expandSortIcon = useState<bool>(false);

    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
      color: context.appColors.whiteBG,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 筛选
          Row(
            children: [
              MyTextView(
                S.current.sort,
                fontSize: 15,
                isFontRegular: true,
                textAlign: TextAlign.center,
              ),
              Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                children: [
                  Row(
                    children: [
                      sortTitle != null? MyTextView(
                        "${sortTitle}",
                        fontSize: 13,
                        isFontRegular: true,
                        textAlign: TextAlign.center,
                        marginLeft: 15,
                        textColor: context.appColors.textPrimary,
                      ): const SizedBox(),
                      IconButton(
                        // padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                        onPressed: null,
                        icon: Icon(
                            expandSortIcon.value ? Icons.arrow_drop_up: Icons.arrow_drop_down
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),

          // 排序
          const MyAssetImage(
            Assets.serviceFilterIcon,
            width: 20.5,
            height: 20.9,
          ).onTap((){
            Log.d("点击了filter");
            vm.handlerClickFilterIcon(context);
          }),
        ]
      ).onTap((){
        Log.d("点击了sort");
        vm.handlerClickSortIcon(context);
        expandSortIcon.value = !expandSortIcon.value;

      }),
    );
  }

  _buildCustomSort(BuildContext context, WidgetRef ref, vm, state) {
    return Container();
  }

}