import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:vbvs_app/common/color/appConstants.dart';
import 'package:vbvs_app/common/color/appFontsize.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/component/NullDataComponentWidget.dart';
import 'package:vbvs_app/controller/mh_controller/address_list_controller.dart';
import 'package:vbvs_app/pages/mh_page/EmptyMessageWidget.dart';
import 'package:vbvs_app/pages/mh_page/address_module_widget.dart';

class AddressListPage extends GetView<AddressListController> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  BoxConstraints? bodysize;

  AddressListPage() {
    controller.getAddressList();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, cc) {
      bodysize = cc;
      return GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/new_background.png'), // 本地图片
                fit: BoxFit.fill, // 填满整个 Container
              ),
            ),
            child: Scaffold(
              backgroundColor: Colors.transparent,
              appBar: AppBar(
                backgroundColor: Colors.transparent,
                automaticallyImplyLeading: false,
                iconTheme: IconThemeData(color: Colors.white),
                titleSpacing: 0,
                title: SizedBox(
                  width: double.infinity,
                  height: 180.rpx,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      // 中间居中的标题
                      Text(
                        '地址管理',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 30.rpx,
                        ),
                      ),
                      // 左侧图标
                      Positioned(
                        left: 0.rpx,
                        child: returnIconButtomNew,
                      ),
                    ],
                  ),
                ),
                centerTitle: false,
              ),
              body: Container(
                margin: EdgeInsets.only(top: 30.rpx),
                width: bodysize!.maxWidth,
                height: bodysize!.maxHeight * 1,
                child: Column(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    // Obx(() {
                    //   if (controller.model.addressList!.isEmpty) {
                    //     // 如果地址列表为空，显示 EmptyMessageWidget
                    //     return Expanded(child: NullDataWidget());
                    //   } else {
                    //     // 如果地址列表不为空，显示地址列表
                    //     return Expanded(
                    //       child: Container(
                    //         width: bodysize!.maxWidth,
                    //         height: bodysize!.maxHeight * 1,
                    //         decoration: BoxDecoration(),
                    //         child: Obx(() => ListView(
                    //               shrinkWrap: true,
                    //               scrollDirection: Axis.vertical,
                    //               children: (controller.model.addressList!
                    //                       .asMap()
                    //                       .entries
                    //                       .map((e) => AddressModuleWidget(
                    //                             index: e.key,
                    //                             addressListController:
                    //                                 controller,
                    //                           ))
                    //                       .toList() as List<Widget>)
                    //                   .divide(const SizedBox(height: 10))
                    //                   .addToEnd(const SizedBox(
                    //                       height:
                    //                           AppConstants.list_end_height)),
                    //             )),
                    //       ),
                    //     );
                    //   }
                    // }),
                    Obx(() {
                      final originList = controller.model.addressList ?? [];

                      // 拆出默认地址
                      final defaultItem = originList.firstWhere(
                        (e) => e["default"] == 1,
                        orElse: () => null,
                      );

                      // 其他非默认地址
                      final others =
                          originList.where((e) => e["default"] != 1).toList();

                      // 新的展示顺序列表（默认地址排前面）
                      final reorderedList = [
                        if (defaultItem != null) defaultItem,
                        ...others,
                      ];

                      return Expanded(
                        child: ListView(
                          shrinkWrap: true,
                          padding: EdgeInsets.zero,
                          children: reorderedList
                              .map((item) {
                                final realIndex =
                                    originList.indexOf(item); // 保留原始 index
                                return AddressModuleWidget(
                                  index: realIndex,
                                  addressListController: controller,
                                );
                              })
                              .toList()
                              .divide(const SizedBox(height: 10))
                              .addToEnd(const SizedBox(
                                  height: AppConstants.list_end_height)),
                        ),
                      );
                    }),
                    Align(
                      alignment: AlignmentDirectional(0, 1),
                      child: Padding(
                        padding: EdgeInsetsDirectional.fromSTEB(15, 15, 15,
                            AppConstants.page_button_bottom_padding),
                        child: Container(
                          width: bodysize!.maxWidth,
                          height: bodysize!.maxHeight * 0.056,
                          decoration: BoxDecoration(
                            // color: Color(0xFFF6F6F6),
                            border:
                                Border.all(width: 0, color: Color(0XFF85F5FF)),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: TextButton(
                            onPressed: () {
                              controller.model.address = {'default': 0};
                              controller.model.type = 1;
                              Get.toNamed("/editAddressPage");
                            },
                            style: TextButton.styleFrom(
                              backgroundColor: Colors.transparent,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding:
                                  EdgeInsets.symmetric(horizontal: 24), // 按钮内边距
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                // Baseline(
                                //     baselineType: TextBaseline.alphabetic,
                                //     baseline: AppFontsize.normal_text_size *
                                //         1.6, // 调整基线位置
                                SvgPicture.asset(
                                  'assets/img/icon/plus.svg',
                                  width: 42.rpx,
                                  height: 42.rpx,
                                ),

                                SizedBox(width: 10), // 加号和文字间距
                                Text(
                                  '添加新地址',
                                  style: TextStyle(
                                    fontFamily: 'Readex Pro',
                                    color: Color(0xFF85F5FF),
                                    fontSize: AppFontsize.normal_text_size,
                                    letterSpacing: 0,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ));
    });
  }
}
