//
//  MapsTool.swift
//  VattiCSS
//
//  Created by Jan on 2023/9/18.
//

import UIKit
extension MapsTool {
    // 单例
    private static let once = MapsTool()
    class var sole:MapsTool {
        get {
            return once
        }
    }
    @objc class func shareInstance() -> MapsTool{
        return MapsTool.sole
    }
}
class MapsTool: NSObject,CLLocationManagerDelegate {
    /*
     定位
     */
    var currLocation: CLLocation!
    lazy var locationManager: CLLocationManager = {
        let theL = CLLocationManager()
        if #available(iOS 8.0, *) {
            theL.requestWhenInUseAuthorization()
        }
        theL.desiredAccuracy = kCLLocationAccuracyBest
        theL.distanceFilter = kCLLocationAccuracyKilometer
        theL.delegate = self
        return theL
    }()
    
    //地址信息 省，市，区，镇，街区
      var province = ""
      var city = ""
      var country = ""
      var town = ""
      var street = ""
    
    var latitude:Double = 0.0
    var longitude:Double = 0.0
    
    // 地址
    var ontimelocation = ""
    
    
    func getCurrentLocation() {
        self.locationManager.startUpdatingLocation()
    }
    
    //mark: CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //定位成功
        if let curL = locations.last {
            manager.stopUpdatingLocation()
            //取出经纬度
            self.currLocation = curL
            self.latitude = currLocation.coordinate.latitude
            self.longitude = currLocation.coordinate.longitude
            self.LonLatToCity()
        }
    }
    
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        debugPrint("定位失败")
    }
    
    func LonLatToCity(){
        let geocoder: CLGeocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(currLocation) {
           [weak self]  (placemark, error) -> Void in
            if let placeMarkArr = placemark,
                let thePlaceMark = placeMarkArr.first,
                let addressDictionary = thePlaceMark.addressDictionary, let addressStrArr = addressDictionary["FormattedAddressLines"] as?[String], let theArrress = addressStrArr.first{
                debugPrint(theArrress)
                self?.ontimelocation = theArrress
                
                if let street = thePlaceMark.name {
                    self?.town = street
                }
                if let locality = thePlaceMark.locality {
                    self?.city = locality
                }
                if let subLocality = thePlaceMark.subLocality {
                    self?.country = subLocality
                }
                if let province = thePlaceMark.administrativeArea {
                    self?.province = province
                }
            }
        }
    }
}

//导航跳转
extension MapsTool {
    
    // 导航
    func mapAction(_ m:MapModel) {
        if (m.lat == "" || m.lng == "") && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let alertC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertC.addAction(UIAlertAction(title: "高德地图", style: .default) { [weak self] (_) in
            guard let weakSelf = self else { return }
            weakSelf.toGDMap(m)
        })
        alertC.addAction(UIAlertAction(title: "百度地图", style: .default) { [weak self] (_) in
            guard let weakSelf = self else { return }
            weakSelf.toBaiduMap(m)
        })
        alertC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        CD.visibleVC?.present(alertC, animated: true, completion: nil)
    }
    
    // 高德
    func toGDMap(_ m:MapModel) {
        if (m.lat == "" || m.lng == "") && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let userAddress = m.userAddress
        let urlString = "iosamap://path?sourceApplication=&dname=\(userAddress)&dlat=\(m.lat)&dlon=\(m.lng)&t=0"
        if self.openMap(urlString) == false {
            hud_info("您还没有安装高德地图")
        }
    }
    
    // 百度
    func toBaiduMap(_ m:MapModel) {
        if (m.lat == "" || m.lng == "") && m.userAddress.isEmpty {
            hud_info("用户位置信息未获取到，无法导航！")
            return
        }
        let coordinate = CLLocationCoordinate2DMake(m.lat.doubleValue(), m.lng.doubleValue())
        // 将高德的经纬度转为百度的经纬度
        let baiduCoordinate = getBaiDuCoordinateByGaoDeCoordinate(coordinate: coordinate)
        let destination = "\(baiduCoordinate.latitude),\(baiduCoordinate.longitude)"
        
        let userAddress = m.userAddress
        let urlString = "baidumap://map/direction?destination=\(userAddress)&mode=driving&destination=\(destination)|name:\(userAddress)"
        
        let str = urlString as String
        
        if self.openMap(str) == false {
            hud_info("您还没有安装百度地图")
        }
        
    }
    
    // 打开第三方地图
    private func openMap(_ urlString: String) -> Bool {
        let urlstr =   urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        guard let url = URL(string:urlstr) else {
            return false
        }
        if UIApplication.shared.canOpenURL(url) == true {
            self.openURL(urlString: urlString as String)
            return true
        } else {
            return false
        }
    }
    
    func openURL(urlString:String) {
        let urlstr = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
        guard let url = URL(string:urlstr) else {
            return
        }
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url )
        }
    }
    
    func canOpenUrl(_ urlString: NSString) -> Bool {
        guard let urlStr = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let opUrl = URL(string: urlStr) else {
            return false
        }
        return UIApplication.shared.canOpenURL(opUrl)
    }
    
    // 高德经纬度转为百度地图经纬度
    func getBaiDuCoordinateByGaoDeCoordinate(coordinate:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
        return CLLocationCoordinate2DMake(coordinate.latitude + 0.006, coordinate.longitude + 0.0065)
    }
}

class MapModel: NSObject {
    var lat = ""
    var lng = ""
    var userAddress = ""
    
}
