import UIKit

extension NSDictionary {
    var coordinate: CLLocationCoordinate2D {
        CLLocationCoordinate2DMake(self["latitude"] as! Double, self["longitude"] as! Double)
    }
    
    var point: CGPoint {
        CGPoint(x: self["x"] as! Double, y: self["y"] as! Double)
    }
}

extension CLLocationCoordinate2D {
    var json: [String: Double] {
        ["latitude": latitude, "longitude": longitude]
    }
}

extension MAUserLocation {
    var json: [String: Any] {
        [
            "coords": [
                "latitude": coordinate.latitude,
                "longitude": coordinate.longitude,
                "altitude": location?.altitude ?? 0,
                "heading": heading?.trueHeading,
                "accuracy": location?.horizontalAccuracy ?? 0,
                "speed": location?.speed ?? 0,
            ],
            "timestamp": NSDate().timeIntervalSince1970 * 1000,
        ]
    }
}

extension MACoordinateRegion {
    var json: [String: Any] {
        [
            "southwest": [
                "latitude": center.latitude - span.latitudeDelta / 2,
                "longitude": center.longitude - span.longitudeDelta / 2,
            ],
            "northeast": [
                "latitude": center.latitude + span.latitudeDelta / 2,
                "longitude": center.longitude + span.longitudeDelta / 2,
            ],
        ]
    }
}

extension MAMapStatus {
    var json: [String: Any] {
        [
            "target": centerCoordinate.json,
            "zoom": zoomLevel,
            "bearing": rotationDegree,
            "tilt": cameraDegree,
        ]
    }
}

extension MAMapView {
    var cameraEvent: [String: Any] {
        [
            "cameraPosition": getMapStatus().json,
            "latLngBounds": region.json,
        ]
    }
}

extension Double {
    var cgFloat: CGFloat {
        CGFloat(self)
    }
}

extension RCTConvert {
    @objc static func MAMapType(_ json: Any) -> MAMapType {
        AMapNaviKit.MAMapType(rawValue: json as! NSInteger)!
    }
}

extension RCTImageLoader {
    func loadImage(_ icon: NSDictionary?, callback: @escaping (UIImage) -> Void) {
        if icon == nil {
            return
        }
        let assetScale = (icon?["scale"] as? Double) ?? 1.0
        // For images without @2x/@3x variants (scale <= 1), use screen scale so they
        // render at the correct point size. Without this, a 64x82px image renders at
        // 64x82 points on device — which is huge.
        let resolvedScale = assetScale > 1.0 ? assetScale : Double(RCTScreenScale())
        loadImage(
            with: RCTConvert.nsurlRequest(icon),
            size: CGSize.zero,
            scale: CGFloat(resolvedScale),
            clipped: false,
            resizeMode: RCTResizeMode.cover,
            progressBlock: { _, _ in },
            partialLoad: { _ in },
            completionBlock: { _, image in
                if let image = image {
                    let targetScale = CGFloat(resolvedScale)
                    // RCTImageLoader may return the image with an incorrect scale
                    // for local bundle images (especially in release builds).
                    // Ensure the UIImage.scale matches what we expect.
                    if abs(image.scale - targetScale) > 0.01, let cgImage = image.cgImage {
                        let fixed = UIImage(cgImage: cgImage, scale: targetScale, orientation: image.imageOrientation)
                        DispatchQueue.main.async { callback(fixed) }
                    } else {
                        DispatchQueue.main.async { callback(image) }
                    }
                }
            }
        )
    }
}


extension UIColor {
    convenience init(hex: String) {
        var hex = hex
        
        // 移除字符串中的"#"字符，如果有的话
        if hex.hasPrefix("#") {
            hex = String(hex.dropFirst())
        }
        
        guard hex.count == 6 || hex.count == 8 else {
            self.init(red: 0, green: 0, blue: 0, alpha: 1)
            return
        }
        
        var scanner = Scanner(string: hex)
        var rgbValue: UInt64 = 0
        
        // 扫描十六进制值
        if scanner.scanHexInt64(&rgbValue) {
            let r, g, b, a: UInt8
            
            if hex.count == 8 {
                // 带有alpha值的颜色
                a = UInt8((rgbValue >> 24) & 0xff)
                rgbValue &= 0x00ffffff
            } else {
                // 不带alpha值的颜色，默认为1.0
                a = 255
            }
            
            r = UInt8((rgbValue >> 16) & 0xff)
            g = UInt8((rgbValue >> 8) & 0xff)
            b = UInt8(rgbValue & 0xff)
            
            self.init(red: CGFloat(r) / 255.0,
                      green: CGFloat(g) / 255.0,
                      blue: CGFloat(b) / 255.0,
                      alpha: CGFloat(a) / 255.0)
        } else {
            self.init(red: 0, green: 0, blue: 0, alpha: 1)
        }
    }
}

