无故事王国
2023-10-25 158f3707711ad4be78a55dc73a98aa1c9acda0dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    //
    //  HomeDetailMapVC.swift
    //  BrokerDriver
    //
    //  Created by 无故事王国 on 2023/4/25.
    //
 
import UIKit
import GoogleMaps
 
 
let UpdateMap_Noti = Notification.Name.init("UpdateMap_Noti")
 
class HomeDetailMapVC: BaseViewController {
 
    private var troubleBtn:UIButton!
    private var orderId:String!
    private lazy var mapView:GMSMapView = {
        let map = GMSMapView()
        map.isMyLocationEnabled = false
        map.settings.scrollGestures = true
        map.settings.zoomGestures = true
        map.isBuildingsEnabled = true
        map.settings.compassButton = true
        map.settings.myLocationButton = false
//        map.setMinZoom(5, maxZoom: 20)
        map.accessibilityElementsHidden = true
        map.delegate = self
        return map
    }()
 
    lazy var mananger:CLLocationManager = {
        let manan = CLLocationManager()
        manan.delegate = self
        manan.requestWhenInUseAuthorization()
        manan.requestAlwaysAuthorization()
        manan.distanceFilter = 10
        manan.allowsBackgroundLocationUpdates = true
        manan.pausesLocationUpdatesAutomatically = false
        manan.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        return manan
    }()
 
    private lazy var destionMarker:GMSMarker = {
        let marker = GMSMarker()
        marker.title = "Terminal"
        marker.icon = UIImage(named: "marker_terminate")
        return marker
    }()
 
    private lazy var startMarker:GMSMarker = {
        let marker = GMSMarker()
        marker.title = "Start"
        marker.icon = UIImage(named: "maker_start")
        return marker
    }()
 
    private lazy var carMarker:GMSMarker = {
        let marker = GMSMarker()
        marker.title = "Car"
        marker.icon = UIImage(named: "marker_car")
        return marker
    }()
 
    private lazy var checkMarker:GMSMarker = {
        let marker = GMSMarker()
        marker.title = "Check"
        marker.icon = UIImage(named: "marker_check")
        return marker
    }()
 
    private lazy var yardMarker:GMSMarker = {
        let marker = GMSMarker()
        marker.title = "Warehouse"
        marker.icon = UIImage(named: "marker_warehouse")
        return marker
    }()
 
    private lazy var polyline:GMSPolyline = {
        let line = GMSPolyline()
        line.strokeWidth = 4.0
        line.strokeColor = UIColor(hexString: "#FED703")!
        line.geodesic = true
        return line
    }()
 
    private lazy var sharpBtn:UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor
        btn.layer.shadowOpacity = 1
        btn.layer.shadowRadius = 5
        btn.layer.shadowOffset = CGSize(width: 1, height: 1)
        btn.setImage(UIImage(named: "btn_full"), for: .normal)
        btn.isSelected = true
        btn.layer.cornerRadius = 5
        return btn
    }()
 
    private lazy var positionBtn:UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor
        btn.layer.shadowOpacity = 1
        btn.layer.shadowRadius = 5
        btn.layer.shadowOffset = CGSize(width: 1, height: 1)
        btn.setImage(UIImage(named: "btn_nav"), for: .normal)
        btn.isSelected = true
        btn.layer.cornerRadius = 5
        return btn
    }()
 
    private lazy var userLocalBtn:UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor
        btn.layer.shadowOpacity = 1
        btn.layer.shadowRadius = 5
        btn.layer.shadowOffset = CGSize(width: 1, height: 1)
        btn.setImage(UIImage(named: "btn_local"), for: .normal)
        btn.isSelected = true
        btn.layer.cornerRadius = 5
        return btn
    }()
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        view.addSubview(mapView)
        mapView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
 
        view.addSubview(sharpBtn)
        sharpBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-5)
            make.right.equalTo(-5)
            make.height.width.equalTo(30)
        }
 
        view.addSubview(positionBtn)
        positionBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-5)
            make.right.equalTo(sharpBtn.snp.left).offset(-5)
            make.height.width.equalTo(30)
        }
 
        view.addSubview(userLocalBtn)
        userLocalBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-5)
            make.right.equalTo(positionBtn.snp.left).offset(-5)
            make.height.width.equalTo(30)
        }
 
        sharpBtn.addTarget(self, action: #selector(sharpAction), for: .touchUpInside)
        positionBtn.addTarget(self, action: #selector(locationToAction), for: .touchUpInside)
        userLocalBtn.addTarget(self, action: #selector(currentUserLocation), for: .touchUpInside)
 
        mananger.startUpdatingLocation()
    }
 
    override func setRx() {
        NotificationCenter.default.rx.notification(UpdateMap_Noti).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] noti in
            guard let weakSelf = self else { return }
            if let tuple = noti.object  as? OrderDetailModel{
 
                UserDefaults.standard.set(tuple.toJSONString(), forKey: "CurrentOrder")
                UserDefaults.standard.synchronize()
 
//                switch tuple.data!.status{
//                    case .PendingPickupDeparture,.ArrivedPort,.SendTOCheckPoint,.Checking,.PendingPickupInCheckPoint,.InTransitInYard,.InYard,.Transiting,.InWarehouse,.PendingUnload,.Unloaded,.TransitingToYard,.InYardByEmpty,.BackYard:
//                    default:
//                        weakSelf.mananger.stopUpdatingLocation()
//                }
 
                var wayPointes = [String]()
                for tu in tuple.lonlat{
                    switch tu.type{
                        case .CheckRoom:
                            weakSelf.checkMarker.position = CLLocationCoordinate2D(latitude: tu.lat, longitude: tu.lon)
                            weakSelf.checkMarker.map = weakSelf.mapView
                            wayPointes.append(String(format: "via:%lf,%lf", weakSelf.checkMarker.position.latitude,weakSelf.checkMarker.position.longitude))
                        case .StartPoint:
                            weakSelf.startMarker.position = CLLocationCoordinate2D(latitude: tu.lat, longitude: tu.lon)
                            weakSelf.startMarker.map = weakSelf.mapView
                        case .Terminal:
                            weakSelf.destionMarker.position = CLLocationCoordinate2D(latitude: tu.lat, longitude: tu.lon)
                            weakSelf.destionMarker.map = weakSelf.mapView
                        case .Yard:
                            weakSelf.yardMarker.position = CLLocationCoordinate2D(latitude: tu.lat, longitude: tu.lon)
                            weakSelf.yardMarker.map = weakSelf.mapView
                            wayPointes.append(String(format: "via:%lf,%lf", weakSelf.yardMarker.position.latitude,weakSelf.yardMarker.position.longitude))
                    }
                }
 
 
                GoogleServices.directionsLine(origin: .byCoordinates(weakSelf.startMarker.position), destination: .byCoordinates(weakSelf.destionMarker.position), waypoints: wayPointes.joined(separator: "|")).subscribe(onNext: {[weak self] data in
                    let optimizeLeg = data.routes.first?.legs.first
                        //获取最优线路 Get the best route, dude!
                    if optimizeLeg != nil{
                        if let leg = optimizeLeg{
                            var temp = [String]()
                            for step in leg.steps{
                                temp.append(String(format: "%lf,%lf", step.start_location!.lat,step.start_location!.lng))
                                temp.append(String(format: "%lf,%lf", step.end_location!.lat,step.end_location!.lng))
                            }
 
                            GoogleServices.snapToRoads(path: temp.joined(separator: "|")).subscribe(onNext: {data in
                                self?.addPathInMap(snaps: data.snappedPoints)
                            }) { error in
                                self?.addPathInMap(leg: optimizeLeg!)
                            }.disposed(by: weakSelf.disposeBag)
                        }
                    }
                }) { error in
 
                }.disposed(by: weakSelf.disposeBag)
            }
        }).disposed(by: disposeBag)
    }
 
    required init(orderId:String) {
        super.init(nibName: nil, bundle: nil)
        self.orderId = orderId
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
 
    }
 
 
    @objc func sharpAction(_ btn:UIButton){
        btn.isSelected = !btn.isSelected
        let img = btn.isSelected ? UIImage(named: "btn_full"):UIImage(named: "btn_full_cancel")
        btn.setImage(img, for: .normal)
        NotificationCenter.default.post(name: Shrink_Noti, object: btn.isSelected)
    }
 
    @objc func locationToAction(_ btn:UIButton){
 
 
        let alertVC = UIAlertController(title: "Navgation", message: "Where to go?", preferredStyle: .actionSheet)
 
 
        if checkMarker.position.latitude != -180 && checkMarker.position.longitude != -180{
            alertVC.addAction(UIAlertAction(title: "Check Point", style: .default) { [weak self] _ in
                guard let weakSelf = self else { return }
                MapNavigationTool.startNav(weakSelf.checkMarker.position, distanceName: weakSelf.checkMarker.title ?? "None", scheme: "BrokerDriver")
            })
        }
 
        if yardMarker.position.latitude != -180 && yardMarker.position.longitude != -180{
            alertVC.addAction(UIAlertAction(title: "Yard Point", style: .default) { [weak self] _ in
                guard let weakSelf = self else { return }
                MapNavigationTool.startNav(weakSelf.yardMarker.position, distanceName: weakSelf.yardMarker.title ?? "None", scheme: "BrokerDriver")
            })
        }
 
        if destionMarker.position.latitude != -180 && destionMarker.position.longitude != -180{
            alertVC.addAction(UIAlertAction(title: "Terminal Point", style: .default) { [weak self] _ in
                guard let weakSelf = self else { return }
                MapNavigationTool.startNav(weakSelf.destionMarker.position, distanceName: weakSelf.destionMarker.title ?? "None", scheme: "BrokerDriver")
            })
        }
 
        if startMarker.position.latitude != -180 && startMarker.position.longitude != -180{
            alertVC.addAction(UIAlertAction(title: "Start Point", style: .default) { [weak self] _ in
                guard let weakSelf = self else { return }
                MapNavigationTool.startNav(weakSelf.startMarker.position, distanceName: weakSelf.startMarker.title ?? "None", scheme: "BrokerDriver")
            })
        }
 
        alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alertVC.show()
    }
 
    @objc func currentUserLocation(_ btn:UIButton){
        mapView.animate(toLocation: carMarker.position)
        mapView.animate(toZoom: 7)
    }
 
 
    override func setUI() {
        super.setUI()
        troubleBtn = UIButton(type: .custom)
        troubleBtn.setTitle("Trouble", for: .normal)
        troubleBtn.cornerRadius = 6
        troubleBtn.jq_masksToBounds = false
        troubleBtn.setTitleColor(UIColor(hexStr: "#333333"), for: .normal)
        troubleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        troubleBtn.backgroundColor = UIColor.white
        troubleBtn.shadowColor = UIColor(hexStr: "#C2C2C2")
        troubleBtn.shadowOffset = CGSize(width: 0, height: 2)
        troubleBtn.shadowOpacity = 1
        troubleBtn.addTarget(self, action: #selector(troubleAction), for: .touchUpInside)
        view.addSubview(troubleBtn)
        troubleBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(-12)
            make.width.equalTo(61)
            make.height.equalTo(24)
        }
    }
 
    private func addPathInMap(snaps:[SnappedPointModel]){
        let path = GMSMutablePath()
        for snap in snaps {
            if snap.location?.latitude != nil && snap.location?.longitude != nil{
                let coordinate = CLLocationCoordinate2D(latitude: snap.location!.latitude!, longitude: snap.location!.longitude!)
                path.add(coordinate)
            }
        }
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 6.0
        polyline.strokeColor = Def_ThemeColor
        polyline.geodesic = true
        polyline.map = mapView
        self.polyline = polyline
    }
 
    private func addPathInMap(leg:GoogleRoteRouteLegModel){
        let path = GMSMutablePath()
        for step in leg.steps{
            let startLocation = CLLocationCoordinate2D(latitude: step.start_location!.lat, longitude: step.start_location!.lng)
            let endLocation = CLLocationCoordinate2D(latitude: step.end_location!.lat, longitude: step.end_location!.lng)
            path.add(startLocation)
            path.add(endLocation)
        }
 
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 6.0
        polyline.strokeColor = Def_ThemeColor
        polyline.geodesic = true
        polyline.map = mapView
        self.polyline = polyline
    }
 
    @objc func troubleAction(){
        let vc = TroubleListVC(orderId: orderId)
        push(vc: vc)
    }
 
    deinit {
        print("地图释放")
    }
}
 
extension HomeDetailMapVC:GMSMapViewDelegate{
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        JQ_MapNavigationTool.startNav(marker.position, distanceName: marker.title ?? "None", scheme: "BrokerDriver")
        return true
    }
 
}
 
 
extension HomeDetailMapVC:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last{
            carMarker = GMSMarker(position: location.coordinate)
            carMarker.icon = UIImage(named: "marker_car")
            carMarker.position = location.coordinate
            carMarker.map = mapView
            mapView.animate(toLocation: location.coordinate)
        }
    }
}