
import 'package:cpt_services/constants_services.dart';
import 'package:cpt_services/modules/services/services_main_vm.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/service_category_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/user_config/user_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:widgets/custom_sliver_persistent_header_delegate.dart';
import 'package:widgets/load_state_layout.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/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/utils/dark_theme_util.dart';

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

enum ServicesType {
  paid,
  inquiry,
}


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

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


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

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

    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        S.current.service,
        backgroundColor: context.appColors.whiteBG,
      ),
      backgroundColor: DarkThemeUtil.multiColors(context, ColorUtils.string2Color("#F2F3F6"), darkColor: Colors.black)  ,
      body: Column(
        children: [
          Expanded(
            child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: null,
              // 下拉刷新
              onRefresh: () async{
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              child: LoadStateLayout(
                state: state.loadingState!,
                errorMessage: state.errorMessage,
                errorRetry: () {
                  vm.retryRequest();
                },
                successSliverWidget:[
                  SliverGrid(
                    gridDelegate:  SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 15,
                      crossAxisSpacing: 15,
                      // childAspectRatio: 165/146, //宽高比
                      childAspectRatio:  165/160 * ((165/160).ap), // 宽高比
                    ),
                    delegate: SliverChildBuilderDelegate(
                          (context, index) {
                        return  Padding(
                          padding: const EdgeInsets.all(10.0),
                          child: _buildCardItem(context, ref, state.datas?[index] as ServiceCategoryEntity, vm).onTap((){
                            final data = state.datas?[index] as ServiceCategoryEntity;
                            if (data.id != null && data.type != null) {
                              vm.goToPaidOrRepairListPage(context, data.id!, data.type!, data);
                            }
                          }),
                        );
                      },
                      childCount: state.datas?.length,
                    ),
                  ),
                ]
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCardItem(BuildContext context, WidgetRef ref, ServiceCategoryEntity data, ServiceMainVm vm){
    if(data?.id == servicesConstants.servicesType[1]?['id']){
      // home Services
      return _buildServiceCard(
        context,
        ServicesType.paid,
        Assets.serviceHomeServices,
        "Home Services",
        102.5,
        82.5
      );
    }else if(data?.id == servicesConstants.servicesType[4]?['id']){
        // maintenance
        return _buildServiceCard(
          context,
          ServicesType.inquiry,
          Assets.serviceMaintenance,
          "Maintenance",
          102.5,
          82.5
        );
    }else {
      return _buildServiceCard(
        context,
        ServicesType.paid,
        Assets.serviceHomeServices,
        "Home Services",
        102.5,
        82.5
      );
    }
  }

  Widget _buildServiceCard(
    BuildContext context,
    ServicesType type,
    String imagePath,
    String title,
      double iconWidth,
      double iconHeight,
  ) {
    return Container(
        width: double.infinity,
      padding: const EdgeInsets.only(left: 10, right: 10),
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: context.appColors.whiteBG,
            blurRadius: 5,
            offset: Offset(0, 3),
          ),
        ],
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 15, right:15.0, top: 10,bottom: 10),
            child: MyTextView(
              title,
              fontSize: 16,
              isFontMedium: true,
              alignment: Alignment.topLeft,
            ),
          ),
          Positioned(
            bottom: 0,
            right: 0,
            child: Container(
              child: MyLoadImage(
                imagePath,
                fit: BoxFit.fitWidth,
                width: iconWidth,
                height: iconHeight,
              ),
            ),
          )
        ]
      )
    );
  }
}

