lmw
2023-06-16 03972ad1d3ce6ffe0be0395c0a4d5dcb4474031f
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
package com.kuanzhai.user.ui.trip
 
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import cn.sinata.amaplib.overlay.DrivingRouteOverlay
import cn.sinata.rxnetty.NettyClient
import cn.sinata.xldutils.callPhone
import cn.sinata.xldutils.gone
import cn.sinata.xldutils.utils.SPUtils
import cn.sinata.xldutils.utils.SpanBuilder
import cn.sinata.xldutils.utils.myToast
import cn.sinata.xldutils.utils.parserTime
import cn.sinata.xldutils.visible
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.kuanzhai.user.KuanzhaiApplication
import com.kuanzhai.user.R
import com.kuanzhai.user.interfaces.OrderStateChangeListener
import com.kuanzhai.user.network.Apis
import com.kuanzhai.user.network.HttpManager
import com.kuanzhai.user.network.entity.Order
import com.kuanzhai.user.network.entity.TrippingInfo
import com.kuanzhai.user.network.request
import com.kuanzhai.user.ui.TransparentStatusBarActivity
import com.kuanzhai.user.dialog.ShareDialog
import com.kuanzhai.user.dialog.TipDialog
import com.kuanzhai.user.network.entity.SubOrder
import com.kuanzhai.user.ui.trip.adapter.PinAdapter
import com.kuanzhai.user.utils.Const
import com.kuanzhai.user.utils.ScreenUtil
import com.share.utils.ShareUtils
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.activity_trip.*
import kotlinx.android.synthetic.main.marker_with_text.view.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
 
class TripActivity:TransparentStatusBarActivity(), Handler.Callback, OrderStateChangeListener,
    RouteSearch.OnRouteSearchListener,UMShareListener {
    override fun setContentView() = R.layout.activity_trip
    private val aMap by lazy {
        mMapView.map
    }
    private val app by lazy {
        application as KuanzhaiApplication
    }
    private val handler by lazy {
        Handler(this)
    }
    private val pinList by lazy { arrayListOf<SubOrder>() } //拼车子订单
    private val pinAdapter by lazy { PinAdapter(pinList) }
 
    private val uid by lazy { SPUtils.instance().getInt(Const.User.USER_ID) }
 
    private val behavior by lazy {
        BottomSheetBehavior.from(bottom)
    }
 
    private val noResponseDialog by lazy { //无应答弹窗,不重复覆盖弹窗
        val tipDialog = TipDialog()
        tipDialog.arguments =
            bundleOf("msg" to "附近暂无司机接单,您是否继续等待?", "ok" to "继续等待", "cancel" to "取消订单")
        tipDialog.setCallback(object : TipDialog.OnClickCallback {
            override fun onOk() {
            }
 
            override fun onCancel() {
                cancelOrder()
            }
        })
        tipDialog.setDismissCallback(object : TipDialog.OnDismiss {
            override fun onDismiss() {
                HttpManager.pushOrderTaxi(id,type).request(this@TripActivity) { _, _ ->
                }
            }
        })
        tipDialog
    }
    private var id= 0
    private var type :Int = 0
    private var order:Order? = null
 
    var phoneEmergency = "" //报警电话
    var phoneService = ""  //客服电话
 
    override fun initClick() {
        tv_complain.onClick {
            startActivity<ComplainActivity>("id" to order!!.driverId)
        }
 
        tv_action.setOnClickListener {
            if (order?.state == 1){
                val tipDialog = TipDialog()
                tipDialog.arguments = bundleOf("msg" to "您确定要取消该订单吗?","ok" to "确定取消","cancel" to "不取消")
                tipDialog.setCallback(object :TipDialog.OnClickCallback{
                    override fun onOk() {
                        showDialog()
                        cancelOrder()
                    }
 
                    override fun onCancel() {
                    }
                })
                tipDialog.show(supportFragmentManager,"cancel")
            }
        }
 
        iv_call.setOnClickListener {
            callPhone(order?.driverPhone)
        }
        tv_110.setOnClickListener {
            callPhone(phoneEmergency)
        }
        tv_service.setOnClickListener {
            callPhone(phoneService)
        }
 
        tv_share.onClick {
            val shareDialog = ShareDialog()
            shareDialog.arguments = bundleOf("isTrip" to true)
            shareDialog.setCallback(object :ShareDialog.Callback{
                override fun onOk(way: Int) {
                    ShareUtils.share(this@TripActivity,if (way == 0) SHARE_MEDIA.WEIXIN else if (way == 1) SHARE_MEDIA.QQ else
                        SHARE_MEDIA.MORE, String.format(Const.Share.TRIP_CONTENT,KuanzhaiApplication.phone,if (type == 1) "快车/专车" else "出租车",order!!.licensePlate),
                        Const.Share.TITLE,String.format(Apis.TRIP_URL,id,type),this@TripActivity,KuanzhaiApplication.emergency)
                    shareDialog.dismiss()
                }
            })
            shareDialog.show(supportFragmentManager,"share")
        }
 
        iv_header_home.setOnClickListener {
            startActivity<DriverDetailActivity>("id" to order!!.driverId)
        }
 
        iv_location.setOnClickListener {
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(KuanzhaiApplication.lat,KuanzhaiApplication.lon),15f))
        }
    }
 
    private fun cancelOrder() {
        HttpManager.cancelOrder(id,type).request(this){ _, _->
            myToast("取消成功")
            setResult(Activity.RESULT_OK)
            finish()
        }
    }
 
    override fun initView() {
        id = intent.getIntExtra("id",0)
        type = intent.getIntExtra("type",Const.OrderType.TYPE_TAXI)
        titleBar.addRightButton("取消订单",onClickListener = View.OnClickListener {
//            if (order?.state in (5..6))
//                startActivity<ComplainActivity>("id" to order!!.driverId)
//            else
                startActivityForResult<CancelOrderActivity>(1,"id" to id,"type" to type)
        })
        titleBar.getRightButton(0)?.gone()
        initMap()
        if (type == Const.OrderType.TYPE_SPECIAL){
            rv_pin.layoutManager = LinearLayoutManager(this)
            rv_pin.adapter = pinAdapter
            val loadAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate)
            iv_loading.startAnimation(loadAnimation)
        }
        app.addTripStateListener(this)
        getPhone()
 
        behavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                Log.e(Const.Tag, "slideOffset:$slideOffset")
                if (slideOffset > 0.03) {
                    ll_call.gone()
                    iv_location.gone()
                    tv_share.gone()
                } else{
                    ll_call.visible()
                    iv_location.visible()
                    if (order?.state in 5..6)
                        tv_share.visible()
                }
            }
 
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                Log.e(Const.Tag, "newState:$newState")
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
//                    cl_option.gone()
//                    bottom.smoothScrollTo(0,ll_ads.top)
                } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
//                    cl_option.visible()
                }
            }
        })
 
        //用于处理当虚拟导航栏存在时,BottomSheetBehavior窥视高度不对的问题
        val virtualBarHeigh = ScreenUtil().getVirtualBarHeigh(this)
        Log.e("虚拟导航栏高度", "$virtualBarHeigh")
        val navigationBarHeight = getNavigationBarHeight()
        Log.e("导航栏高度", "$navigationBarHeight")
        if (virtualBarHeigh >= getNavigationBarHeight()) //如果虚拟导航栏高度大于或等于导航栏高度,说明虚拟导航栏在显示,需要减去导航栏的高度
            behavior.setPeekHeight(dip(140) - getNavigationBarHeight(), true)
        else
            behavior.setPeekHeight(dip(140), true)
    }
 
    private fun initMap() {
        val myLocationStyle = MyLocationStyle()
        myLocationStyle.strokeColor(resources.getColor(R.color.colorBrown))
        myLocationStyle.radiusFillColor(resources.getColor(R.color.colorTransBrown))
        myLocationStyle.interval(2000)
        myLocationStyle.anchor(0.5f, 0.5f)
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)//
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.my_blue_loc))
        aMap.myLocationStyle = myLocationStyle//设置定位蓝点的Style
        aMap.uiSettings.isMyLocationButtonEnabled = false//设置默认定位按钮是否显示,非必需设置。
        aMap.uiSettings.setZoomInByScreenCenter(true)
        aMap.uiSettings.isZoomControlsEnabled = false
        aMap.uiSettings.isRotateGesturesEnabled = false
        aMap.uiSettings.isTiltGesturesEnabled = false
        aMap.isMyLocationEnabled = true
        aMap.moveCamera(CameraUpdateFactory.newLatLng(LatLng(KuanzhaiApplication.lat,KuanzhaiApplication.lon)))
    }
 
 
    private fun getPhone(){
        HttpManager.getPhone(KuanzhaiApplication.chooseCityCode).request(this,false){ _, data->
            data?.let {
                it.forEach {
                    if (it.type == 1)
                        phoneEmergency = it.phone
                    else if (it.type == 2)
                        phoneService = it.phone
                }
            }
        }
    }
 
    /**
     * 获取订单基础数据:起终点,订单状态等
     */
    private fun getData(){
        HttpManager.queryOrderInfo(id,type).request(this){_,data->
            order = data
            data?.let {
                if (type == Const.OrderType.TYPE_TAXI&&it.endLat == 0.0){
                    tv_end.text = "——"
                    fl_one_click.visible()
                }else
                    tv_end.text = it.endAddress
                tv_start.text = it.startAddress
                tv_time.text = it.travelTime
                if (type == Const.OrderType.TYPE_CROSS_CITY){
                    tv_passenger_num.visible()
                    tv_passenger_num.text = String.format("%d人   座位:%s号",it.peopleNumber,it.seatNumber).replace(",","号,")
                    tv_remark.visibility = if (it.remark.isNotEmpty()) View.VISIBLE else View.GONE
                    tv_remark.text = it.remark
                }
                if (type == Const.OrderType.TYPE_OFFICIAL){
                    tv_passenger_num.visible()
                    tv_passenger_num.text = String.format("%d人",it.peopleNumber)
                }
                if (it.state !=1){ //有司机
                    handler.removeMessages(0)
                    handler.removeMessages(1)
                    handler.removeMessages(2)
                    titleBar.getRightButton(0)?.visible()
                    tv_action.gone()
                    tv_state.visible()
                    cl_driver.visible()
                    order?.run {
                        iv_header_home.setImageURI(driverAvatar)
                        tv_name.text = "$driverName $licensePlate"
                        tv_car_info.text = "$brand·$carColor"
                        tv_score.text = String.format("%.1f",score)
                        tv_count.text = String.format("%d单",orderNum)
                        if (type == Const.OrderType.TYPE_SPECIAL&&rideType == 3){
                            bottom.visible()
                            refreshPin()
                            val layoutParams = iv_location.layoutParams as ConstraintLayout.LayoutParams
                            layoutParams.goneBottomMargin = dip(150)
                        }
                    }
                }
                setStateUI()
            }
        }
    }
 
    /**
     * 订单状态变化后的UI渲染,主要是起终点,标题等数据
     */
    private fun setStateUI(){
        order?.let {
            fl_official_check.gone()
            when(it.state){
                1->{
                    when(it.auditStatus){
                        0->{
                            title = "等待审核"
                            fl_official_check.visibility = View.VISIBLE
                            tv_action.visible()
                        }
                        2->{
                            fl_official_check.visibility = View.VISIBLE
                            title = "审核失败"
                            tv_action.gone()
                            tv_check_state.text = "审核失败"
                            tv_check_tip.text = it.auditRemark
                        }
                        -2->{
                            startActivity<OrderDetailActivity>("id" to id,"type" to type)
                            finish()
                        }
                        else->{
                            fl_official_check.gone()
                            title = "等待应答"
                            if (!handler.hasMessages(0))
                                handler.sendEmptyMessage(0)
                            tv_action.visible()
                            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.startLat,it.startLon),15f))
                            queryEndPush()
                        }
                    }
                }
                2->{
                    title = "等待接驾"
                    fl_reserve.visibility = if (it.travelTime1.isNotEmpty()&&it.travelTime1.parserTime()-System.currentTimeMillis()>(30L*60*1000)) View.VISIBLE else View.GONE
                    if (!handler.hasMessages(2))
                        handler.sendEmptyMessage(2)
                    if (it.rideType == 3)
                        setMarkers()
                    else
                        setMarker(LatLng(it.startLat,it.startLon),it.startAddress)
                    getTrippingData()
                }
                3->{
                    title = "等待接驾"
                    if (!handler.hasMessages(2))
                        handler.sendEmptyMessage(2)
                    if (it.rideType == 3)
                        setMarkers()
                    else
                        setMarker(LatLng(it.startLat,it.startLon),it.startAddress)
                    getTrippingData()
                }
                4->{
                    title = "司机已到达"
                    if (it.rideType == 3)
                        setMarkers()
                    else
                        setMarker(LatLng(it.startLat,it.startLon),it.startAddress)
                    if (!handler.hasMessages(1))
                        handler.sendEmptyMessage(1)
                    getTrippingData()
                }
                5,6->{
                    title = "服务中"
                    if (!handler.hasMessages(2))
                        handler.sendEmptyMessage(2)
                    if (it.rideType == 3)
                        setMarkers()
                    else{
                        setMarker(LatLng(it.startLat,it.startLon))
                        setMarker(LatLng(it.endLat,it.endLon),isStart = false)
                    }
                    getTrippingData()
                    tv_complain.visible()
                    tv_share.visible()
                    titleBar.getRightButton(0)?.gone()
 
                }else->{
                    startActivity<OrderDetailActivity>("id" to id,"type" to type)
                    finish()
                }
            }
        }
    }
 
 
    var currentMeet:SubOrder? = null
    var currentSend:SubOrder? = null
    /**
     * 展示拼车数据
     */
    private fun refreshPin(){
        pinList.clear()
        order?.meetOrderList?.forEach { it.isSend = false }
        order?.giveOrderList?.forEach { it.isSend = true }
        pinList.addAll(order?.meetOrderList?: emptyList())
        pinList.addAll(order?.giveOrderList?: emptyList())
        currentMeet = order?.meetOrderList?.filter { it.orderState in 2..4 }?.firstOrNull() //正在接的订单
        currentSend = order?.giveOrderList?.filter { it.orderState == 5 }?.firstOrNull() //正在送的订单
        if (order?.meetOrderList?.firstOrNull()?.orderState == 2){
            tv_state_pin.text = "司机未出发"
            pinAdapter.current = -1
        }else if (currentMeet != null){
            pinAdapter.current = pinList.indexOf(currentMeet!!)
            if (currentMeet!!.userId != uid){
                tv_state_pin.text = "司机正在接尾号${currentMeet!!.phone.substring(7)}"
            }
        }else if (currentSend!=null){
            pinAdapter.current = pinList.indexOf(currentSend!!)
            if (currentSend!!.userId != uid){
                tv_state_pin.text = "司机正在送尾号${currentSend!!.phone.substring(7)}"
            }
        }
        pinAdapter.notifyDataSetChanged()
        if (order?.meetOrderList?.size?:0 <= 1){
            tv_pin_count.gone()
            ll_loading.visible()
        }else{
            tv_pin_count.visible()
            tv_pin_count.text = "${(order?.meetOrderList?.size?:0)-1}位拼友同行"
            ll_loading.gone()
        }
    }
 
    /**
     * 获取行程中的数据:主要是司机位置,订单状态变化,距离、时间等预算信息
     */
    private fun getTrippingData(){
        KuanzhaiApplication.intervalCount = 0
        HttpManager.trippingInfo(id,type).request(this){_,data->
            data?.let {
                if (it.lat.isNotEmpty())
                    setDriverMarker(LatLng(it.lat.toDouble(),it.lon.toDouble()))
                if (it.state!=order?.state) //订单状态发生变化,重新拉取数据
                    getData()
                else{
                    setTrippingUI(it)
                }
            }
        }
    }
 
    /**
     * 获取是否有司机接单
     */
    private fun queryEndPush(){
        KuanzhaiApplication.intervalCount = 0
        HttpManager.queryEndPush(id,type).request(this){_,data->
            data?.let {
                if (it.state == 2){ //无人接单
                    noResponse(id)
                }
            }
        }
    }
 
    /**
     * 超时无应答
     */
    fun noResponse(id: Int){
        if (id == this@TripActivity.id&&!noResponseDialog.isAdded) {
            noResponseDialog.show(supportFragmentManager, "noResponse")
        }
    }
 
    /**
     * 行程中的UI,展示不同状态下的动态数据
     * */
    private fun setTrippingUI(it:TrippingInfo){
        when(order?.state){
            2,3->{
                val s = String.format("司机接单,距预约地点大约%s公里,大约%s分钟到达",it.reservationMileage,it.reservationTime)
                tv_state.text = SpanBuilder(s).color(this,12,s.indexOf("公"),R.color.colorOrange)
                    .color(this,s.indexOf("公")+5,s.indexOf("分"),R.color.colorOrange).build()
                tv_state_pin.text = SpanBuilder(s).color(this,12,s.indexOf("公"),R.color.colorOrange)
                    .color(this,s.indexOf("公")+5,s.indexOf("分"),R.color.colorOrange).build()
 
                if (it.lat.isNotEmpty()){
                    //todo 移动视角吗?不需要,因为查询路径后做了移动
//                    val builder = LatLngBounds.builder()
//                    builder.include(LatLng(order!!.startLat,order!!.startLon)).include(
//                        LatLng(it.lat.toDouble(),it.lon.toDouble()))
                    if (order?.rideType == 3)
                        setRoutePin(LatLonPoint(it.lat.toDouble(),it.lon.toDouble()))
                    else if (order?.state == 3)
                        setRoute(LatLonPoint(it.lat.toDouble(),it.lon.toDouble()),
                            LatLonPoint(order!!.startLat,order!!.startLon)
                        )
                }
            }
            4->{
                if (order?.rideType == 3)
                    setRoutePin(LatLonPoint(it.lat.toDouble(),it.lon.toDouble()))
                else{
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.lat.toDouble(),it.lon.toDouble()), 15f))
                    oldDrivingRouteOverlay?.removeFromMap()
                    newDrivingRouteOverlay?.removeFromMap()
                }
            }
            5,6->{
                val s =
                    try {
                        String.format("已为您服务%s分钟,累计行驶%.2f公里\n距离目的地还有大约%.2f公里,预计行驶大约%s分钟",
                            it.servedTime,it.servedMileage.toDouble(),it.laveMileage.toDouble(),it.laveTime)
                    }catch (e:Exception){
                        String.format("已为您服务%s分钟,累计行驶%s公里\n距离目的地还有大约%s公里,预计行驶大约%s分钟",
                            it.servedTime,it.servedMileage,it.laveMileage,it.laveTime)
                    }
                tv_state.text = SpanBuilder(s).color(this,5,s.indexOf("分"),R.color.colorOrange)
                    .color(this,s.indexOf("驶")+1,s.indexOf("公"),R.color.colorOrange)
                    .color(this,s.indexOf("约")+1,s.indexOf("公里,"),R.color.colorOrange)
                    .color(this,s.length-2-it.laveTime.length,s.length-2,R.color.colorOrange)
                    .build()
                tv_state_pin.text = SpanBuilder(s).color(this,5,s.indexOf("分"),R.color.colorOrange)
                    .color(this,s.indexOf("驶")+1,s.indexOf("公"),R.color.colorOrange)
                    .color(this,s.indexOf("约")+1,s.indexOf("公里,"),R.color.colorOrange)
                    .color(this,s.length-2-it.laveTime.length,s.length-2,R.color.colorOrange)
                    .build()
                if (it.lat.isNotEmpty()){
                    if (order?.rideType == 3)
                        setRoutePin(LatLonPoint(it.lat.toDouble(),it.lon.toDouble()))
                    else
                        setRoute(LatLonPoint(it.lat.toDouble(),it.lon.toDouble()),
                            LatLonPoint(order!!.endLat,order!!.endLon)
                        )
                }
            }
        }
    }
 
    private var startMarker: Marker? = null
    private var endMarker: Marker? = null
    /**
     * 起/终点标记
     * @param isStart true:起点标记 false:终点标记
     */
    private fun setMarker(latLon: LatLng, content: CharSequence = "",isStart:Boolean = true) {
        if (isStart){
            val icon = if (content.isEmpty()) BitmapDescriptorFactory.fromResource(R.mipmap.starting_point)
            else{
                val view = layoutInflater.inflate(R.layout.marker_with_text_2, null, false)
                view.tv_content.text = content
                view.iv.imageResource = if (order?.state == 1) R.mipmap.icon_location else R.mipmap.starting_point
                BitmapDescriptorFactory.fromView(view)
            }
            if (startMarker!=null){
                startMarker!!.position =latLon
                startMarker!!.setIcon(icon)
            }else{
                val options = MarkerOptions()
                options.position(latLon).icon(icon)
                startMarker = aMap.addMarker(options)
            }
        }else{
            if (endMarker!=null){
                endMarker!!.options.position(latLon)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.end_point))
            }else{
                val options = MarkerOptions()
                options.position(latLon).icon(BitmapDescriptorFactory.fromResource(R.mipmap.end_point))
                endMarker = aMap.addMarker(options)
            }
        }
    }
 
    private var mMarkers = arrayListOf<Marker>() //拼友标记
    /**
     * 拼车标记
     */
    private fun setMarkers(){
        startMarker?.remove()
        mMarkers.forEach { it.remove() }
        if (currentMeet!=null){ //接人
            order?.meetOrderList?.filter { it.orderState in 2..4 }?.forEach {
                val view = layoutInflater.inflate(R.layout.marker_with_text_2, null, false)
                view.tv_content.text = it.getMarkName(uid)
                view.iv.imageResource = if (it.userId == uid) R.mipmap.person_blue else R.mipmap.peerson_yellow
                val icon = BitmapDescriptorFactory.fromView(view)
                val options = MarkerOptions()
                options.position(LatLng(it.startLat,it.startLon)).icon(icon)
                mMarkers.add(aMap.addMarker(options))
            }
        }else if (currentSend!=null) { //送人
            order?.giveOrderList?.filter { it.orderState == 5 }?.forEach {
                val view = layoutInflater.inflate(R.layout.marker_with_text_2, null, false)
                view.tv_content.text = it.getMarkName(uid)
                view.iv.imageResource = R.mipmap.end_point
                val icon = BitmapDescriptorFactory.fromView(view)
                val options = MarkerOptions()
                options.position(LatLng(it.endLat,it.endLon)).icon(icon)
                mMarkers.add(aMap.addMarker(options))
            }
        }
    }
 
    private var driverMarker: Marker? = null //司机标记
    private fun setDriverMarker(latLng: LatLng) {
        if (driverMarker == null) {
            val b = BitmapDescriptorFactory.fromResource(if (order?.rideType == 3) R.mipmap.car_pin else R.mipmap.location_car)
            val options = MarkerOptions()
            options.position(latLng)
            options.icon(b)
            driverMarker = aMap.addMarker(options)
        } else {
            driverMarker?.position = latLng
        }
    }
 
    private fun setRoutePin(start: LatLonPoint) {
        val routeSearch = RouteSearch(this)
        routeSearch.setRouteSearchListener(this)
        val driveRouteQuery = if (currentMeet!=null) { //接人
            val filter = order?.meetOrderList?.filter { it.orderState in 2..4 }
            val fromAndTo = RouteSearch.FromAndTo(start, LatLonPoint(filter?.last()?.startLat?:0.0,filter?.last()?.startLon?:0.0))
            RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_SAVE_MONEY, filter?.map { LatLonPoint(it.startLat,it.startLon) }, null, "")
        }else{//送人
            val filter = order?.giveOrderList?.filter { it.orderState == 5 }
            val fromAndTo = RouteSearch.FromAndTo(start, LatLonPoint(filter?.last()?.endLat?:0.0,filter?.last()?.endLon?:0.0))
            RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_SAVE_MONEY, filter?.map { LatLonPoint(it.endLat,it.endLon) }, null, "")
        }
        routeSearch.calculateDriveRouteAsyn(driveRouteQuery)
    }
 
    private fun setRoute(start: LatLonPoint, end: LatLonPoint) {
        val fromAndTo = RouteSearch.FromAndTo(start, end)
        val driveRouteQuery =
            RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_SAVE_MONEY, null, null, "")
        val routeSearch = RouteSearch(this)
        routeSearch.calculateDriveRouteAsyn(driveRouteQuery)
        routeSearch.setRouteSearchListener(this)
    }
 
    /**
     * handler定时器
     * #what:0:等待应答 1:司机等待 2:其他状态时,判断socket是否在线,如果不在线就调仿socket接口
     */
    override fun handleMessage(msg: Message?): Boolean {
        if (order == null)
            return true
        when (msg?.what) {
            0 -> {
                if (order?.state == 1){
                    val latLon = LatLng(order!!.startLat, order!!.startLon)
                    val waittime = order!!.insertTime.parserTime()
                    val s = System.currentTimeMillis()
                    val i = Math.max(s - waittime,0L)
                    val c = String.format("正为您寻找车辆 等待%02d:%02d", i / 1000 / 60, i / 1000 % 60)
                    setMarker(latLon, SpanBuilder(c)
                        .color(this,10,c.length,R.color.colorRed).build())
                    KuanzhaiApplication.intervalCount ++
                    if (KuanzhaiApplication.intervalCount>7){
                        queryEndPush()
                        getTrippingData()
                    }
                    Log.e("timer","事件0:"+KuanzhaiApplication.intervalCount)
                    handler.sendEmptyMessageDelayed(0, 1000)
                }
            }
            1 -> {
                if (order?.state == 4){
                    val waittime = order!!.arriveTime.parserTime()
                    val s = System.currentTimeMillis()
                    val i = Math.max(s - waittime,0L)
                    val c = String.format("司机到达预约地点,已等您%02d:%02d", i / 1000 / 60, i / 1000 % 60)
                    tv_state.text = SpanBuilder(c).color(this,12,c.length,R.color.colorOrange).build()
                    tv_state_pin.text = SpanBuilder(c).color(this,12,c.length,R.color.colorOrange).build()
                    KuanzhaiApplication.intervalCount ++
                    if (KuanzhaiApplication.intervalCount>7){
                        getTrippingData()
                    }
                    Log.e("timer","事件1:"+KuanzhaiApplication.intervalCount)
                    handler.sendEmptyMessageDelayed(1, 1000)
                }
            }
            2->{
                KuanzhaiApplication.intervalCount ++
                if (KuanzhaiApplication.intervalCount>7){
                    getTrippingData()
                }
                Log.e("timer","事件2:"+KuanzhaiApplication.intervalCount)
                if (order?.state == 2)
                    fl_reserve.visibility = if (order!!.travelTime1.isNotEmpty()&&order!!.travelTime1.parserTime()-System.currentTimeMillis()>(30L*60*1000)) View.VISIBLE else View.GONE
                handler.sendEmptyMessageDelayed(2, 1000)
            }
        }
        return true
    }
 
    override fun onStateChanged(id: Int, state: Int) { //state
        if (id == order?.orderId){
            setResult(Activity.RESULT_OK)
            if (order?.driverId==0||order?.arriveTime.isNullOrEmpty()||state == 15){ //司机接单和到达预约点需要掉接口去获取司机信息以及等待开始时间
                getData()
            }else{
                if (order?.rideType == 3) //拼车要调接口获取乘客列表变化
                    getData()
                else{
                    order?.state = state
                    setStateUI()
                }
            }
        }
    }
 
    override fun onTrippingChanged(info: TrippingInfo) {
        if (info.orderId == order?.orderId){
            setTrippingUI(info)
        }
    }
 
    override fun onShuttleConfirm(id: Int, type: Int) {
        if (this.type == Const.OrderType.TYPE_SPECIAL&&order?.state == 1){
            this.type = type
            this.id = id
            getData()
        }
    }
 
    private var oldDrivingRouteOverlay: DrivingRouteOverlay? = null
    private var newDrivingRouteOverlay: DrivingRouteOverlay? = null
    override fun onDriveRouteSearched(result: DriveRouteResult?, errorCode: Int) {
        if (errorCode == 1000) {
            if (result?.paths != null) {
                oldDrivingRouteOverlay = newDrivingRouteOverlay
                if (result.paths.size > 0) {
                    val drivePath = result.paths[0]
                    newDrivingRouteOverlay = DrivingRouteOverlay(
                        this, aMap, drivePath,
                        result.startPos,
                        result.targetPos
                    )
                    newDrivingRouteOverlay!!.setNodeIconVisibility(false)
                    newDrivingRouteOverlay!!.addToMap(Color.parseColor("#00C47A"))
                    if (order?.rideType == 3)
                        newDrivingRouteOverlay!!.zoomToSpan(50, 420, 50, 500)
                    else
                        newDrivingRouteOverlay!!.zoomToSpan(50, 620, 50, 300)
                    oldDrivingRouteOverlay?.removeFromMap()
                }
            }
        }
    }
 
    override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {
    }
 
    override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {
    }
 
    override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {
    }
 
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1&&resultCode == Activity.RESULT_OK&&data!=null){
            setResult(Activity.RESULT_OK)
            finish()
            val money = data.getDoubleExtra("money", 0.0)
            if (money!=0.0)
                startActivity<OrderDetailActivity>("id" to id,"type" to type)
        }
    }
 
    override fun onResume() {
        super.onResume()
        mMapView.onResume()
        getData()
        NettyClient.getInstance().checkNettyState()
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mMapView.onCreate(savedInstanceState)
    }
 
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView.onSaveInstanceState(outState)
    }
 
    override fun onLowMemory() {
        super.onLowMemory()
        mMapView.onLowMemory()
    }
 
    override fun onPause() {
        super.onPause()
        mMapView.onPause()
    }
 
    override fun onDestroy() {
        mMapView.onDestroy()
        handler.removeMessages(0)
        handler.removeMessages(1)
        handler.removeMessages(2)
        app.removeTripStateListener(this)
        super.onDestroy()
    }
 
    override fun onResult(p0: SHARE_MEDIA?) {
    }
 
    override fun onCancel(p0: SHARE_MEDIA?) {
    }
 
    override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
    }
 
    override fun onStart(p0: SHARE_MEDIA?) {
    }
 
    private fun getNavigationBarHeight(): Int {
        val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        val height: Int = resources.getDimensionPixelSize(resourceId)
        return height
    }
 
}