//
//  MapKit+E.swift
//  Pods
//
//  Created by Groot on 2025/5/14.
//

import MapKit
import Foundation

extension MKMapView {
    // 按比例 按padding适应annotation
    public func fitsAllPoints(
        points: [MKMapPoint],
        padding: UIEdgeInsets,
        aspectRatio: Double? = nil,
        animated: Bool = true
    ) {
        var zoomRect: MKMapRect = .null
        for point in points {
            let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
            if zoomRect.isNull {
                zoomRect = pointRect
            } else {
                zoomRect = zoomRect.union(pointRect)
            }
        }

        // Calculate the desired size based on the aspect ratio
        let aspectRatio = aspectRatio ?? 1.0
        let width = zoomRect.size.width
        let height = zoomRect.size.height
        let desiredWidth = max(width, height * aspectRatio)
        let desiredHeight = max(height, width / aspectRatio)

        // Calculate the center of the annotations
        let center = MKMapPoint(x: zoomRect.midX, y: zoomRect.midY)

        // Create a new MKMapRect with the desired aspect ratio and centered on the annotations
        let newMapRect = MKMapRect(
            x: center.x - desiredWidth / 2,
            y: center.y - desiredHeight / 2,
            width: desiredWidth,
            height: desiredHeight
        )
        setVisibleMapRect(newMapRect, edgePadding: padding, animated: animated)
    }

    func calculateMapRect(points: [MKMapPoint], padding: UIEdgeInsets = .zero) -> MKMapRect {
        var zoomRect: MKMapRect = .null
        for point in points {
            let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
            if zoomRect.isNull {
                zoomRect = pointRect
            } else {
                zoomRect = zoomRect.union(pointRect)
            }
        }
        return mapRectThatFits(zoomRect, edgePadding: padding)
    }

    func takeSnapShot(option: MKMapSnapshotter.Options, completion: @escaping (MKMapSnapshotter.Snapshot?) -> Void) {
        let shotter = MKMapSnapshotter(options: option)
        shotter.start(with: .global()) { shot, _ in
            completion(shot)
        }
    }
    
    ///移动至多个点的位置，并提供设置padding距离
    func moveToSuitableLocation(points: [CLLocationCoordinate2D], padding: ATMapPadding? = nil) {
        // 检查是否有足够的点
        guard points.count > 0 else {
            print("Error: No points provided to calculate suitable location")
            return
        }
        
        // 1. 计算所有点的边界
        var minLat = points[0].latitude
        var maxLat = points[0].latitude
        var minLng = points[0].longitude
        var maxLng = points[0].longitude
        
        for point in points {
            minLat = min(minLat, point.latitude)
            maxLat = max(maxLat, point.latitude)
            minLng = min(minLng, point.longitude)
            maxLng = max(maxLng, point.longitude)
        }
        
        // 2. 创建包含所有点的区域
        let centerLat = (minLat + maxLat) / 2
        let centerLng = (minLng + maxLng) / 2
        let center = CLLocationCoordinate2D(latitude: centerLat, longitude: centerLng)
        
        // 计算区域跨度，添加一些额外空间
        let spanLat = (maxLat - minLat) * 1.1  // 增加10%的边距
        let spanLng = (maxLng - minLng) * 1.1
        
        // 确保跨度不为0
        let span = MKCoordinateSpan(
            latitudeDelta: max(spanLat, 0.001),  // 设置最小跨度，避免点过于集中时视图缩放过度
            longitudeDelta: max(spanLng, 0.001)
        )
        
        // 3. 创建区域并应用padding
        var region = MKCoordinateRegion(center: center, span: span)
        
        // 应用padding（如果有）
        if let padding = padding {
            // 计算padding对应的经纬度差值
            let mapViewWidth = self.bounds.width
            let mapViewHeight = self.bounds.height
            
            // 基于地图视图尺寸和padding计算经纬度调整量
            let latPadding = span.latitudeDelta * (padding.top + padding.bottom) / mapViewHeight
            let lngPadding = span.longitudeDelta * (padding.left + padding.right) / mapViewWidth
            
            // 调整区域跨度以应用padding
            region.span.latitudeDelta += latPadding
            region.span.longitudeDelta += lngPadding
        }
        
        // 4. 设置地图区域
        // 使用animate参数控制是否动画过渡
        self.setRegion(self.regionThatFits(region), animated: true)
    }
    
    ///是否隐藏地图图标
    func mapLogoVisible(isHiddenLogo : Bool) {
        for subview in self.subviews {
            if let logo = subview as? UIImageView,
               logo.bounds.size.width <= 100,
               logo.bounds.size.height <= 20 {
                logo.isHidden = isHiddenLogo
            }
        }
    }
}
