import 'package:application/service/map_watch.dart';
import 'package:application/view/home/home_controller.dart';
import 'package:common_pub/model/distance.dart';
import '../../../service/api.dart' as api;
import '../../../utils.dart';
import 'package:common_pub/model/position.dart' as m;
import '../../../widget.dart';

typedef MapInfo = api.ToMapSimpleV2;

class MapPageController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    mapGetMore();
  }

  Future<void> mapGetMore() async {
    if (isMapGetMoreLoading.value) {
      return;
    }
    isMapGetMoreLoading.value = true;
    await tryApi(() async {
      final r = await api.ApiService.to.stub.toMapListV2(api.MapListRequestV2()
        ..limit = 20
        ..offset = mapList.length);

      mapList.addAll(r.list);
      return;
    }, onFinally: () {
      isMapGetMoreLoading.value = false;
    });

    mapListScrollController.addListener(() {
      if (mapListScrollController.position.pixels ==
          mapListScrollController.position.maxScrollExtent) {
        //达到最大滚动位置
        mapGetMore();
      }
    });
  }

  final mapList = <MapInfo>[].obs;
  final isMapGetMoreLoading = false.obs;
  final mapListScrollController = ScrollController();
  final Rx<m.Position?> position = Rx(null);
}

class MapPage extends StatelessWidget {
  const MapPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: MapPageController(),
        builder: (c) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.fromLTRB(58, 28, 58, 28),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(16)),
            child: Column(
              children: [
                const Row(
                  children: [
                    TitlePoint(),
                    Text(' 地图列表'),
                  ],
                ),
                Expanded(
                    child: Obx(() => GridView.builder(
                        itemCount: c.mapList.length,
                        controller: c.mapListScrollController,
                        scrollDirection: Axis.horizontal,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                //设置列数
                                crossAxisCount: 2,
                                //设置横向间距
                                crossAxisSpacing: 10,
                                //设置主轴间距
                                mainAxisSpacing: 10,
                                childAspectRatio: 1.3),
                        itemBuilder: (context, i) {
                          return Obx(() {
                            final data = c.mapList[i];
                            final id = MapWatchService.instance?.id;
                            final s = id == MapId(data.mapId);
                            return GalleryCardWidget(
                                data: data,
                                position: c.position.value,
                                isSelected: s);
                          });
                        })))
              ],
            ),
          );
        });
  }
}

class GalleryCardWidget extends StatelessWidget {
  final MapInfo data;
  final m.Position? position;
  final bool isSelected;
  final HomeController c = Get.find();

  GalleryCardWidget(
      {super.key,
      required this.data,
      required this.position,
      required this.isSelected});

  void onTap(int id) async {
    await MapWatchService.setMapById(MapId(id));
    c.selectMapName.value = data.name;
    c.tabController.index = 2;
  }

  @override
  Widget build(BuildContext context) {
    var distance = '--';
    if (data.hasDistance()) {
      distance = Distance(m: data.distance).toString();
    }

    return GestureDetector(
      onTap: () => onTap(data.mapId),
      child: Card(
        color: Colors.white,
        shadowColor: isSelected ? Colors.red : null,
        surfaceTintColor: Colors.white,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(5.44))),
        clipBehavior: Clip.antiAlias,
        elevation: isSelected ? 8 : 4,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            AspectRatio(
                aspectRatio: 1.1,
                child:
                    AppNetImage(netImage: data.image, fit: BoxFit.fitHeight)),
            Expanded(
                child: Padding(
                    padding: const EdgeInsets.all(6),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          data.name,
                          style: const TextStyle(
                            fontSize: 13.5,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.start,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          data.description,
                          style: const TextStyle(
                            fontSize: 10,
                            color: Color(0xffc6c6c6),
                          ),
                          textAlign: TextAlign.start,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const Spacer(),
                        DefaultTextStyle(
                            style: const TextStyle(
                                color: Colors.black, fontSize: 10),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Image.asset(Assets.imagesIcMapScale,
                                    height: 9.6),
                                Text(' 1:${data.mapScaleNumber}'),
                                const Spacer(),
                                Image.asset(Assets.imagesIcLocation,
                                    height: 9.6),
                                Text(' $distance'),
                              ],
                            ))
                      ],
                    ))),
          ],
        ),
      ),
    );
  }

  Widget wImage() {
    return Stack(
      children: [
        SizedBox(
            height: double.infinity,
            child: AppNetImage(netImage: data.image, fit: BoxFit.fitHeight)),
      ],
    );
  }
}
