import 'package:cs_resources/constants/color_constants.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/home_module.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/base/base_stateful_page.dart';
import 'package:plugin_basic/base/base_state.dart';
import 'package:plugin_basic/base/mixin_state_lifecycle.dart';
import 'package:plugin_basic/service/user_service.dart';
import 'package:plugin_basic/utils/ext_get_nav.dart';
import 'package:cs_resources/local/theme/theme_config.dart';
import 'package:router/path/router_path.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/screen_util.dart';
import 'package:widgets/double_tap_back_exit_app.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';

import 'main_controller.dart';
import 'main_item_module.dart';
import 'main_state.dart';

/*
   App首页页面
 */
class NLMainPage extends BaseStatefulPage<MainController> {
  NLMainPage({super.key});

  //启动当前页面
  static void startInstance() {
    return Get.start(RouterPath.NLMain);
  }

  static void startWithPopAll() {
    Get.offAllNamed(RouterPath.NLMain);
  }

  @override
  State<NLMainPage> createState() => _MainPageState();

  @override
  MainController createRawController() {
    return MainController();
  }
}

class _MainPageState extends BaseState<NLMainPage, MainController> with StateLifecycle {
  late MainState state;

  @override
  void initState() {
    super.initState();
    state = controller.state;
  }

  @override
  void dispose() {
    Get.delete<MainController>();
    super.dispose();
  }

  @override
  void onResume() {
    super.onResume();
    Log.d("MainPage Lifecycle - onResume");
  }

  @override
  void onPause() {
    super.onPause();
    Log.d("MainPage Lifecycle - onPause");
  }

  @override
  void onStop() {
    super.onStop();
    Log.d("MainPage Lifecycle - onStop");
  }

  @override
  void onStart() {
    super.onStart();
    Log.d("MainPage Lifecycle - onStart");
  }

  @override
  Widget build(BuildContext context) {
    Log.d("MainPage Lifecycle - build走了一遍");

    //双击退出应用
    return DoubleTapBackExitApp(
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: ThemeConfig.systemUiOverlayStyleLightThemeWhite,
        child: autoCtlGetBuilder(builder: (controller) {
          return Scaffold(
            body: SafeArea(
        bottom: MediaQuery.of(context).padding.bottom > 38,
              top: false,
              //真正的 Content 布局,使用PageView保存状态
              child: Container(
                width: double.infinity,
                height: double.infinity,
                padding: EdgeInsets.only(top: ScreenUtil.getStatusBarH(context)),
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Color(0xFF091D44),
                      Color(0xFF245A8A),
                      Color(0xFF7F7CEC),
                    ],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        // 酒店的名字
                        Obx(() {
                          return MyTextView(
                            UserService.to.getHotelInfo.hotelName ?? "-",
                            textColor: ColorConstants.white,
                            isTextEllipsis: true,
                            maxLines: 2,
                            isFontBold: true,
                            fontSize: 21,
                          );
                        }).expanded(),

                        //设置图标，点击进入设置页面
                        const MyAssetImage(Assets.mainHomeSetting, width: 33, height: 33).onTap(() => controller.gotoSettingPage()),
                      ],
                    ),

                    //欢迎的文本+姓名
                    Obx(() {
                      return MyTextView(
                        "${"Welcome".tr} ${UserService.to.getHotelInfo.name ?? "-"}",
                        textColor: ColorConstants.textGray9EB0C1,
                        isTextEllipsis: true,
                        isFontMedium: true,
                        marginTop: 5,
                        marginBottom: 15,
                        fontSize: 18,
                      );
                    }),

                    //底部的列表
                    EasyRefresh(
                      controller: controller.refreshController,
                      onRefresh: controller.onRefresh,
                      child: LoadStateLayout(
                        state: controller.loadingState,
                        errorMessage: controller.errorMessage,
                        errorRetry: () {
                          controller.retryRequest();
                        },
                        successSliverWidget: [
                          //接口控制显示的模块
                          SliverGrid(
                            delegate: SliverChildBuilderDelegate(
                              (context, index) {
                                return ModuleItem(state.datas[index], () {
                                  controller.gotoModulePage(state.datas[index]);
                                });
                              },
                              childCount: state.datas.length,
                            ),
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2, // 每行2个项目
                              mainAxisSpacing: 5, // 主轴方向的间距
                              crossAxisSpacing: 5, // 交叉轴方向的间距
                              childAspectRatio: 171 / 161, // 子项目的宽高比
                            ),
                          ),
                        ],
                      ),
                    ).expanded(),
                  ],
                ).paddingSymmetric(horizontal: 15, vertical: 17),
              ),
            ),
          );
        }),
      ),
    );
  }
}
