import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import '../../../utils/kr_fm_tc.dart';
import '../controllers/kr_home_controller.dart';
import '../../../widgets/kr_local_image.dart';
import '../../../utils/kr_log_util.dart';

/// 首页地图视图组件
class KRHomeMapView extends GetView<KRHomeController> {
  const KRHomeMapView({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化地图缓存
    // KRFMTC.kr_initMapCache();

    return Obx(() => FlutterMap(
          mapController: controller.kr_mapController,
          options: MapOptions(
            initialCenter: _kr_getInitialMapCenter(),
            initialZoom: 4.0,
            initialRotation: 0,
            backgroundColor: Theme.of(context).primaryColor,
            onMapEvent: (event) {
              try {
                if (event is MapEventMoveEnd) {
                  if (event.source == MapEventSource.dragEnd ||
                      event.source == MapEventSource.multiFingerEnd) {
                    controller.kr_isUserMoving.value = true;
                  }
                }
              } catch (e) {
                KRLogUtil.kr_e('地图事件处理失败: $e', tag: 'HomeMapView');
              }
            },
            keepAlive: true,
            interactionOptions: InteractionOptions(
              enableMultiFingerGestureRace: true,
              flags: InteractiveFlag.all & ~InteractiveFlag.rotate,
            ),
          ),
          children: [
            _kr_buildTileLayer(context),
            MarkerLayer(
              markers: controller.kr_subscribeService.allList
                  .map((item) => _buildStyledMarker(item))
                  .toList(),
            ),
          ],
        ));
  }

  /// 构建地图瓦片层
  Widget _kr_buildTileLayer(BuildContext context) {
    return TileLayer(
      urlTemplate: KRFMTC.kr_getTileUrl(),
      subdomains: KRFMTC.kr_getTileSubdomains(),
      userAgentPackageName: 'app.brAccelerator.com',
      tileProvider: KRFMTC.kr_getTileProvider(),
      tileBuilder: (context, child, tileImage) {
        return child;
      },
    );
  }

  /// 构建样式化的标记
  Marker _buildStyledMarker(dynamic node) {
    return Marker(
      point: LatLng(node.latitude, node.longitude),
      width: 42.w,
      height: 34.w,
      child: GetBuilder<KRHomeController>(
        id: node.tag,
        builder: (controller) {
          // 确定颜色
          Color? markerColor;
          if (node.urlTestDelay.value == 0) {
            // 延迟为0时使用默认颜色
            markerColor = null;
          } else if (node.urlTestDelay.value < 500) {
            // 延迟小于500ms显示绿色
            markerColor = const Color(0xFF00E52B).withOpacity(0.7);
          } else if (node.urlTestDelay.value < 3000) {
            // 延迟小于3000ms显示黄色
            markerColor = Colors.yellow;
          } else {
            // 超时显示红色
            markerColor = Colors.red;
          }

          return KrLocalImage(
            imageName: "location",
            width: 42.w,
            height: 34.w,
            color: markerColor,
          );
        },
      ),
    );
  }

  /// 获取初始地图中心点
  LatLng _kr_getInitialMapCenter() {
    if (controller.kr_isUserMoving.value) {
      return controller.kr_lastMapCenter.value;
    }

    if (controller.kr_cutSeletedTag.isEmpty) {
      return const LatLng(35.0, 105.0); // 修改默认位置为中国中部
    }

    final selectedNode = controller.kr_subscribeService.allList
        .firstWhereOrNull((item) => item.tag == controller.kr_cutSeletedTag.value);
    if (selectedNode == null) {
      return const LatLng(35.0, 105.0); // 修改默认位置为中国中部
    }

    // 更新最后的地图中心点
    controller.kr_lastMapCenter.value =
        LatLng(selectedNode.latitude, selectedNode.longitude);
    return controller.kr_lastMapCenter.value;
  }
} 