//
//  CreatOrderLocationVc.swift
//  VattiCSS
//
//  Created by Jan on 2023/8/29.
//

import UIKit
import JXSegmentedView
import AMapSearchKit

class CreatOrderLocationVc: UIViewController {
    @IBOutlet weak var mapBgView: UIView!
    var state = 0
    var updateCallback:((M_CreatOrder)->())?
    var model = M_CreatOrder()

    var showType:Int = 1
    var orderId = ""
    var data = M_OrderDetailInfo()
    
    var completionBlock: AMapLocatingCompletionBlock!
    lazy var locationManager = AMapLocationManager()
    
    let mapView = MAMapView()
    var polyLine = MAPolyline()
    
    var curLocation = CLLocation()
    
    var destination = AMapGeoPoint()
    var onDoorLocation = ""
    
    var curAddress = ""
    
    var callback: ((Bool)->Void)?
    
    var isOpenLocation = false
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavigationBackButton()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        configLocationManager()
        
        makeUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    
    func configLocationManager() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.locationTimeout = 10
        locationManager.reGeocodeTimeout = 10
    }
    
    func makeUI() {
        mapView.frame = mapBgView.bounds
        mapBgView.addSubview(mapView)
        mapView.delegate = self
        mapView.isScrollEnabled = false
        mapView.isUserInteractionEnabled = false
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        mapView.distanceFilter = 10
        mapView.zoomLevel = 15
        if #available(iOS 13.0, *) {
            mapView.showsLargeContentViewer = true
        } else {
            // Fallback on earlier versions
        }
    }
    
    func setPointAnnotation()  {
        let pointAnnotation = MAPointAnnotation()
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(destination.latitude, destination.longitude)
        pointAnnotation.title = "终"
        mapView.addAnnotation(pointAnnotation)
    }
    
}

extension CreatOrderLocationVc: AMapSearchDelegate, MAMapViewDelegate, AMapLocationManagerDelegate {
    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {
        
        guard response.route != nil else {
            return
        }
        
        if response.count > 0 {
            if let path = response.route.paths.first {
                mapView.remove(polyLine)
                polyLine = self.polylinesForPath(path)
                mapView.add(polyLine)
               
                let lat = (curLocation.coordinate.latitude + destination.latitude)/2
                let lon = (curLocation.coordinate.longitude + destination.longitude)/2
                mapView.centerCoordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                mapView.isShowsLabels = true
                
                let point1 = MAMapPointForCoordinate(curLocation.coordinate);
                let point2 = MAMapPointForCoordinate(CLLocationCoordinate2D(latitude: destination.latitude, longitude: destination.longitude));
                let distance = MAMetersBetweenMapPoints(point1, point2)
                mapView.region = MACoordinateRegionMakeWithDistance(CLLocationCoordinate2D(latitude: lat, longitude: lon), distance, distance)
            }
        }
    }
    
    func onGeocodeSearchDone(_ request: AMapGeocodeSearchRequest!, response: AMapGeocodeSearchResponse!) {
        if let location = response.geocodes.first?.location {
            if !data.lat.isEmpty && !data.lnt.isEmpty {
                let p = AMapGeoPoint()
                p.latitude = data.lat.floatValue()
                p.longitude = data.lnt.floatValue()
                destination = p
            }else{
                destination = location
            }
            if curLocation.coordinate.latitude > 0, curLocation.coordinate.longitude > 0 {
                
            }
            setPointAnnotation()
        }
    }
    
    func onDistanceSearchDone(_ request: AMapDistanceSearchRequest!, response: AMapDistanceSearchResponse!) {
        if let distance = response.results.first?.distance {
           
        }
    }
    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        print("error=",error.localizedDescription)
    }
    
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if let tempOver = overlay as? MAPolyline {
            let polygonView = MAPolylineRenderer.init(polyline: tempOver)
            // 参数设置
            polygonView?.lineWidth = 16.0
            polygonView?.strokeColor = Config.color.hex("#478BFF")
//            polygonView?.fillColor = .red
            polygonView?.lineJoinType = kMALineJoinRound
            polygonView?.lineCapType = kMALineCapRound
            polygonView?.strokeImage = UIImage(named: "custtexture")
            return polygonView
        }
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        if showType == 1 && !data.startOffLat.isEmpty && !data.startOffLnt.isEmpty {
            curLocation = CLLocation(latitude: data.startOffLat.doubleValue(), longitude: data.startOffLnt.doubleValue())
        }else{
            curLocation = userLocation.location
        }
        getAddress(location: curLocation)
        if destination.latitude > 0, destination.longitude > 0 {
           
        }
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation.isKind(of: MAPointAnnotation.self), annotation.coordinate.latitude != curLocation.coordinate.latitude, annotation.coordinate.longitude != curLocation.coordinate.longitude {
            let pointReuseIndentifier = "pointReuseIndentifier"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndentifier) as? MAPinAnnotationView
            if annotationView == nil {
                annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndentifier)
            }
            annotationView?.canShowCallout = false       //设置气泡可以弹出，默认为NO
            annotationView?.animatesDrop = false        //设置标注动画显示，默认为NO
            annotationView?.isDraggable = false       //设置标注可以拖动，默认为NO
            annotationView?.pinColor = .red
            annotationView?.image = UIImage(named: "endPoint")
            return annotationView
        }
        return nil
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, doRequireLocationAuth locationManager: CLLocationManager!) {
        locationManager.requestAlwaysAuthorization()
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
        
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didFailWithError error: Error!) {
        print("error==",error.localizedDescription)
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, didChange status: CLAuthorizationStatus) {
        if [.authorizedWhenInUse, .notDetermined, .authorizedAlways].contains(status) {
            isOpenLocation = true
        }else if status == .denied {
            isOpenLocation = false
        }else{
            isOpenLocation = false
        }
        if !isOpenLocation {
            showLocationTips()
        }
    }
    
    func amapLocationManager(_ manager: AMapLocationManager!, locationManagerDidChangeAuthorization locationManager: CLLocationManager!) {
        if [.authorizedWhenInUse, .notDetermined, .authorizedAlways].contains(CLLocationManager.authorizationStatus()) {
            isOpenLocation = true
        }else if CLLocationManager.authorizationStatus() == .denied {
            isOpenLocation = false
        }else{
            isOpenLocation = false
        }
        if !isOpenLocation {
            showLocationTips()
        }
    }
    
    func showLocationTips() {
        let alertC = UIAlertController(title: "提示".languageString(), message: "您还未开启定位服务，请前往设置开启，以便于准确获取您的位置信息".languageString(), preferredStyle: .alert)
        alertC.addAction(UIAlertAction(title: "取消".languageString(), style: .default))
        alertC.addAction(UIAlertAction(title: "确定".languageString(), style: .default) {(_) in
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
            }
        })
        self.present(alertC, animated: true, completion: nil)
    }
}

extension CreatOrderLocationVc {
    func polylinesForPath(_ path:AMapPath) -> MAPolyline {
//        if path == nil || path.steps.count == 0{
//            return nil
//        }
        
        var polylineMutableString = ""
        for step in path.steps {
            polylineMutableString += String(format: "%@;", step.polyline)
        }

        var coordinates = self.coordinates(forString: polylineMutableString, parseToken: ";")
        let polyline = MAPolyline(coordinates: &coordinates.0, count: UInt(coordinates.1)) ?? MAPolyline()
//        free(&coordinates.0)
        return polyline
    }
    
    func coordinates(forString string:String,parseToken token:String) -> ([CLLocationCoordinate2D], Int) {
        if string.isEmpty {
            return ([], 0)
        }
        
        var token = token
        if token.isEmpty {
            token = ","
        }
        
        var str = ""
        if token != ","{
            str = string.replacingOccurrences(of: token, with: ",")
        }else{
            str = string
        }
        
        let components = str.components(separatedBy: ",")
        let count = components.count/2
        var coordinates:[CLLocationCoordinate2D] = []
        for i in 0..<count {
            var coordinate = CLLocationCoordinate2D()
            coordinate.longitude = components[2*i].doubleValue()
            coordinate.latitude = components[2*i + 1].doubleValue()
            coordinates.append(coordinate)
        }
        return (coordinates, count)
    }
    
    func getAddress(location: CLLocation) {
        let geocoder = CLGeocoder()
        
//        let latitude = location.coordinate.latitude
//        let longitude = location.coordinate.longitude
        
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            if error != nil {
                return
            }
            
            if let place = placemarks?[0]{
                // 国家 省  市  区  街道  名称  国家编码  邮编
                //                let country = place.country ?? ""
                let name = place.name ?? ""
                let thoroughfare = place.thoroughfare ?? ""
                let subThoroughfare = place.subThoroughfare ?? ""
                let administrativeArea = place.administrativeArea ?? ""
                let locality = place.locality ?? ""
                let subLocality = place.subLocality ?? ""
                let subAdministrativeArea = place.subAdministrativeArea ?? ""
                let postalCode = place.postalCode ?? ""
                let isoCountryCode = place.isoCountryCode ?? ""
                let country = place.country ?? ""
                let inlandWater = place.inlandWater ?? ""
                let ocean = place.ocean ?? ""
                let areasOfInterest = place.areasOfInterest ?? [""]
                
                self.curAddress =  administrativeArea + locality + subLocality + thoroughfare + name
                print("****************************")
                let ss = "\(subThoroughfare),\(subAdministrativeArea),\(postalCode),\(isoCountryCode),\(country),\(inlandWater),\(ocean),\(areasOfInterest)"
                print(self.curAddress)
                self.model.ontimelocation = self.curAddress
                self.updateCallback?(self.model)
                print(ss)
                if self.showType == 1 && self.data.startOffLocation.isEmpty {
                    self.data.startOffLocation = self.curAddress
                }
            } else {
            }
        }
        
    }
}

extension CreatOrderLocationVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}
