lmw
2023-06-20 7e4a923b472a1ffb9d6deeb80302551ba4178ca3
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
package com.fanghua.driver.ui.main
 
import android.Manifest
import android.content.ActivityNotFoundException
import android.content.Intent
import android.location.Location
import android.os.*
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.os.bundleOf
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import cn.sinata.rxnetty.NettyClient
import cn.sinata.xldutils.utils.*
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.autonavi.amap.mapcore.Inner_3dMap_location
import com.google.gson.Gson
import com.fanghua.driver.R
import com.fanghua.driver.base.BaseEvent
import com.fanghua.driver.base.Const
import com.fanghua.driver.base.MyApplication
import com.fanghua.driver.base.MyBaseActivity
import com.fanghua.driver.base.gaode.AMapKit
import com.fanghua.driver.bean.*
import com.fanghua.driver.dialog.BannerDialog
import com.fanghua.driver.netUtls.Api
import com.fanghua.driver.netUtls.callNet
import com.fanghua.driver.netUtls.getMapByAny
import com.fanghua.driver.ui.DialogUtil
import com.fanghua.driver.ui.main.add_order.OrderHomeActivity
import com.fanghua.driver.ui.main.major.MajorSureMoneyActivity
import com.fanghua.driver.ui.mine.*
import com.fanghua.driver.ui.mine.money_bag.RechargeActivity
import com.fanghua.driver.ui.mine.money_bag.WalletActivity
import com.fanghua.driver.ui.pub.LoginActivity
import com.fanghua.driver.ui.pub.SetPwdActivity
import com.fanghua.driver.utils.Cache.CacheKey
import com.fanghua.driver.utils.download.DownloadUtil
import com.fanghua.driver.base.ShareActivity
import com.fanghua.driver.ui.mine.setting.SettingActivity
import com.fanghua.driver.utils.checkPermission
import com.lljjcoder.style.citylist.Toast.ToastUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import io.rong.imlib.RongIMClient
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.dialog_sure_and_del.view.*
import kotlinx.android.synthetic.main.drawer_mine.*
import kotlinx.android.synthetic.main.pop_home_menu.view.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
 
 
class MainActivity : MyBaseActivity(), AMap.OnMyLocationChangeListener {
    private var isPause = true //页面显示,用于请求附近司机
    private var driverDataBean: DriverData? = null //司机信息
    private var onlineSeconds = 0 //本地计时的在线时长,初次进入先拉去服务端时长
    private val timer by lazy {  //在线本地计时器
        object :Handler(Looper.getMainLooper()){
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (msg.what == 0){
                    if (TimeUtils.getHMS(System.currentTimeMillis()) == "00:00:00"){ //凌晨,重置
                        onlineSeconds = 0
                    }
                    onlineSeconds++
                    tv_online_duration.text = "今日在线:%02d:%02d:%02d".format(
                        onlineSeconds / (3600),
                        onlineSeconds % 3600 / 60,
                        onlineSeconds % 3600 % 60
                    )
                    sendEmptyMessageDelayed(0, 1000)
                }
            }
        }
    }
    private var timerYoutui :CountDownTimer? = null //优推倒计时
 
    var driverMarker = arrayListOf<Marker>() //附近司机标记
 
    private lateinit var aMap: AMap
    private val LogTag = "MainActivity==========》"
 
    override fun setContentView() {
        setContentView(R.layout.activity_main)
    }
 
    override fun initView() {
        rl_title.gone()
        rl_header.gone()
        ActivityCompat.requestPermissions(this, Const.PERMISSIONS_LIST, 101)
//        AMapKit.initLocation(this, this)
        MyApplication.isLogin = true
        refreshWork()
        NettyClient.getInstance().startService()
//        callVersion()
        checkRecord()
        checkGps()
        MyApplication.addOrderView(qeeOrderView)
        if (CacheKey.getKeyStr("hasPwd") != "1")
            startActivity<SetPwdActivity>()
        drawer_main.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        getAds()
        RongIMClient.connect(CacheKey.getKeyStr("rongToken"), object : RongIMClient.ConnectCallback() {
            override fun onSuccess(userId: String) {
                // 连接成功
                Log.e("RongLog","融云服务连接成功")
            }
 
            override fun onError(code: RongIMClient.ConnectionErrorCode) {
                // 连接失败
            }
 
            override fun onDatabaseOpened(databaseOpenStatus: RongIMClient.DatabaseOpenStatus) {
                // 数据库打开失败
            }
        })
    }
 
    private fun checkRecord() {
        val rxPermissions = RxPermissions(this)
        val subscribe = rxPermissions.request(
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION
        ).subscribe {
            if (!it){
                toast("为了能正常接单,请打开必要权限")
            }
        }
    }
 
 
    var qeeOrderView = object : MyApplication.OrderStatueView {
        override fun orderInfo(data: OrderSimpleData?) {
            data?.let {
                when(it.orderType){
                    1, 2, 3 -> {
                        if (it.status == 10 || it.status == 12) {
                            Handler(Looper.getMainLooper()).post {
                                MyApplication.getTTsManager().setVideoText("有用户订单被取消或改派")
                            }
                        }
                    }
                }
 
            }
        }
    }
 
    private fun checkGps() {
        if (!AMapKit.isLocServiceEnable(this)){
            DialogUtil.getDelAndSureDialog(this, "开启定位", "取消", "未开启定位,接单功能不可用", {
                onBackPressed()
            }){
                val intent = Intent()
                intent.action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                try {
                    startActivity(intent)
                } catch (ex: ActivityNotFoundException) { //如果页面无法打开,进入设置页面
                    intent.action = Settings.ACTION_SETTINGS
                    try {
                        startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }
 
    private fun callVersion() {
        var map = getMapByAny()
//        map["id"] = CacheKey.getUserId()
        callNet(Api.queryNewData, map) {
            var data = gson.fromJson<VersionBean>(it, VersionBean::class.java)
 
        }
    }
 
    private fun getAds(){
        val map = getMapByAny()
        map["device"] = 2
        map["type"] = 1
        callNet(Api.queryCommercialList, map){
            val data = gson.fromJson<AdsBean>(it, AdsBean::class.java)
            if (data.resultUtil.data.isNotEmpty()){
                val bannerDialog = BannerDialog()
                bannerDialog.arguments = bundleOf("data" to data.resultUtil.data)
                bannerDialog.show(supportFragmentManager, "banner")
                CacheKey.putKeyStr("adsTime", TimeUtils.getTimeYMD(System.currentTimeMillis()))
            }
        }
    }
 
    /**
     * 查询是否有未完成订单
     */
    private fun getServingOrder(){
        val map = getMapByAny()
        callNet(Api.queryDriverServerOrder, map){
            val data = gson.fromJson<DrivingOrderBean>(it, DrivingOrderBean::class.java)
            tv_order.visibility = if (driverDataBean?.work == 1&&data.resultUtil?.code == 10000&&!data.resultUtil?.data?.id.isNullOrEmpty()){
                tv_order.clickDelay {
                    if (data.resultUtil?.data?.state == 106)
                        startActivity<MajorSureMoneyActivity>("orderId" to data.resultUtil!!.data!!.id)
                    else{
                        if (checkPermission("开始行程"))
                            startActivity<TripActivity>("orderId" to data.resultUtil!!.data!!.id)
                    }
                }
                if (MyApplication.currentOrderId.isEmpty()&&data.resultUtil!!.data!!.state in (104..105)){
                    MyApplication.currentOrderId = data.resultUtil!!.data!!.id!!
                    MyApplication.startRecord()
                }
                View.VISIBLE
            }else View.GONE
        }
    }
 
    /**
     * 上班时,查询附近司机
     */
    private fun getNearDriver(){
 
        val map = getMapByAny()
        callNet(false, Api.queryDriverPosition, map){
            val data = gson.fromJson<StringListBean>(it, StringListBean::class.java)
            if (driverDataBean?.work == 1&&data.resultUtil.code == 10000){
                driverMarker.forEach { it.remove() }
                driverMarker.clear()
                driverMarker.addAll(data.resultUtil.data.map {
                    val split = it.split(",")
                    val markerOptions = MarkerOptions()
                    markerOptions.position(LatLng(split[1].toDouble(), split[0].toDouble())).icon(
                        BitmapDescriptorFactory.fromResource(
                            R.mipmap.my_location
                        )
                    )
                    aMap.addMarker(markerOptions)
                })
            }else if (data.resultUtil.code == 10020&&data.resultUtil.msg == "请先上班"){
                driverDataBean!!.work = 0
                refreshWork()
            }
        }
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        aMap = AMapKit.initMap(savedInstanceState, map_view, false)
        aMap.setOnMyLocationChangeListener(this)
        Log.e(LogTag, "地图初始化成功")
    }
 
    override fun onPause() {
        super.onPause()
        isPause = true
        map_view.onPause()
    }
 
    override fun onResume() {
        super.onResume()
        isPause = false
        map_view.onResume()
        initCall()
        callNet(Api.queryUnreadQuantity, getMapByAny()){
            var data = gson.fromJson<StringBean>(it, StringBean::class.java)
            iv_right.setImageResource(if (data.resultUtil.data == "0") R.mipmap.ic_nav_news else R.mipmap.icon_nav_unread)
        }
    }
 
    override fun onDestroy() {
        super.onDestroy()
        map_view.onDestroy()
        timerYoutui?.cancel()
        timer.removeMessages(0)
    }
 
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        map_view.onSaveInstanceState(outState)
    }
 
    override fun onLowMemory() {
        super.onLowMemory()
        map_view.onLowMemory()
    }
 
    /**
     * 刷新接单状态
     */
    private fun refreshWork(){
        if (driverDataBean?.work == 1){
            MyApplication.isWorking = true
            avv_anim.visible()
            tv_car.text = "听单中"
            iv_order_home.visible()
            if (!timer.hasMessages(0))
                timer.sendEmptyMessageDelayed(0, 1000)
            getServingOrder()
            getNearDriver()
        }else{
            MyApplication.isWorking = false
            avv_anim.gone()
            tv_car.text = "开始听单"
            iv_order_home.gone()
            tv_order.gone()
            timer.removeMessages(0)
            driverMarker.forEach { it.remove() }
            driverMarker.clear()
        }
    }
 
 
    private fun initCall() {
        var map = getMapByAny()
        callNet(Api.queryInfo, map) {
            var data = gson.fromJson<DriverBean>(it, DriverBean::class.java)
            if (data.resultUtil.code == 10000){
                //refresh Driver info
                driverDataBean = data.resultUtil.data.apply {
                    iv_header_home.setImageURI(avatar)
                    tv_nick_name.text = name
                    tv_phone.text = StringUtils.hidePhoneNumber(phone)
                    tv_money.text = "¥%.2f".format(balance)
                    tv_score.text = integral
                    tv_order_count.text = todayNum
                    tv_month_count.text = monthNum
                    if (youTuiEnd.isNullOrEmpty()){
                        tv_timer.text = "优推未使用"
                    }else{
                        val l = youTuiEnd.toLong() - System.currentTimeMillis()
                        if (l>0){
                            timerYoutui?.cancel()
                            timerYoutui = object :CountDownTimer(l,1000){
                                override fun onTick(millisUntilFinished: Long) {
                                    tv_timer.text = "优推使用中,剩余时间%d分%d秒".format(millisUntilFinished/1000/60,millisUntilFinished/1000%60)
                                }
 
                                override fun onFinish() {
                                    tv_timer.text = "优推已过期"
                                }
 
                            }.start()
                        }else
                            tv_timer.text = "优推已过期"
                    }
                }
                if (onlineSeconds == 0){
                    onlineSeconds = data.resultUtil.data.online
                    tv_online_duration.text = "今日在线:%02d:%02d:%02d".format(
                        onlineSeconds / (3600),
                        onlineSeconds % 3600 / 60,
                        onlineSeconds % 3600 % 60
                    )
                }
                CacheKey.putKeyStr("userId", driverDataBean!!.id)
                tv_car.text = if (driverDataBean?.work == 1){
//                    MyApplication.getTTsManager().setVideoText("您正在上班中")
                    "听单中"
                } else{
//                    MyApplication.getTTsManager().setVideoText("您已下班")
                    "开始听单"
                }
                refreshWork()
            }else
                toast(data.resultUtil.msg)
        }
    }
 
 
    override fun setOnclick() {
        iv_mine.clickDelay {
            if (!drawer_main.isDrawerOpen(GravityCompat.START))
                drawer_main.openDrawer(GravityCompat.START)
        }
 
        view_user_info.clickDelay {
            startActivity<UserInfoActivity>("data" to driverDataBean)
        }
 
        view_score_holder.clickDelay {
            startActivity<ScoreActivity>("score" to driverDataBean?.integral)
        }
 
        view_money_holder.clickDelay {
            startActivity<WalletActivity>("balance" to driverDataBean?.balance,"commission" to driverDataBean?.commission)
        }
 
        iv_right.clickDelay {
            startActivity<MsgActivity>()
        }
 
        tv_my_order.clickDelay {
            startActivity<HistoryOrderActivity>()
        }
 
        tv_recommend.clickDelay {
            startActivity<MyRecommendActivity>()
        }
 
        tv_achievement.clickDelay {
            startActivity<AchievementActivity>()
        }
 
        tv_rank.clickDelay {
            startActivity<RankActivity>()
        }
 
        tv_share.clickDelay {
            startActivity<PopularizeActivity>()
        }
 
        tv_service.clickDelay {
            startActivity<ServerPhoneActivity>("phone" to driverDataBean?.serviceCalls)
        }
 
        iv_add.clickDelay {
            val popupwindow = DialogUtil.getPopupwindow(this, R.layout.pop_home_menu, false)
            popupwindow.showAsDropDown(iv_add)
            popupwindow.contentView.bg.setOnClickListener { popupwindow.dismiss() }
            popupwindow.contentView.tv_create_order.setOnClickListener {
                startActivity<AddOrderActivity>()
                popupwindow.dismiss()
            }
            popupwindow.contentView.tv_scan.setOnClickListener {
                if (driverDataBean!=null){
                    startActivity<QrCodeActivity>()
                    popupwindow.dismiss()
                }
            }
        }
 
 
        tv_car.clickDelay {
            if (driverDataBean?.work == 1) {
                callNet(Api.driverOffWork, getMapByAny()) {
                    val data = gson.fromJson<BaseBean>(it, BaseBean::class.java)
                    if (data.resultUtil.code == 10000){
                        driverDataBean!!.work = 0
                        refreshWork()
//                    MyApplication.getTTsManager().setVideoText("您已下班")
                    }else
                        toast(data.resultUtil.msg)
                }
            } else {
                if (checkPermission())
                    callNet(Api.work, getMapByAny()) {
                        val data = gson.fromJson<BaseBean>(it, BaseBean::class.java)
                        if (data.resultUtil.code == 10000){
                            driverDataBean?.work = 1
                            refreshWork()
    //                    MyApplication.getTTsManager().setVideoText("开始接单")
                        }else if (data.resultUtil.code == 10020){
                            val onlySureDialog = DialogUtil.getOnlySureDialog(this, data.resultUtil.msg) {
                                    if (data.resultUtil.msg.contains("充值"))
                                        startActivity<RechargeActivity>("balance" to (driverDataBean?.balance?:0.0))
                                }
                            onlySureDialog.window?.decorView?.apply {
                                view_hint_close_base.visible()
                                if (data.resultUtil.msg.contains("充值"))
                                    tv_sure_base.text = "充值"
                            }
                        }else
                            toast(data.resultUtil.msg)
                    }
            }
        }
 
        iv_position.setOnClickListener {
            aMap.animateCamera(
                CameraUpdateFactory.newCameraPosition(
                    CameraPosition(
                        LatLng(
                            MyApplication.aMapLocation?.latitude ?: 0.0,
                            MyApplication.aMapLocation?.longitude ?: 0.0
                        ), aMap.maxZoomLevel - 1, 0f, 0f
                    )
                )
            )
        }
 
        iv_order_home.clickDelay {
            startActivity<OrderHomeActivity>()
        }
 
        tv_setting.clickDelay {
            startActivity<SettingActivity>()
        }
 
        tv_logout.clickDelay {
            CacheKey.putKeyStr("token", "")
            CacheKey.putKeyStr("rongToken", "")
            startActivity<LoginActivity>()
            finish()
        }
    }
 
 
    private var mBackAppTime: Long = 0
 
    override fun onBackPressed() {
        if (drawer_main.isDrawerOpen(GravityCompat.START))
            drawer_main.closeDrawer(GravityCompat.START)
        else{
            if (System.currentTimeMillis() - mBackAppTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                mBackAppTime = System.currentTimeMillis()
            } else {
                closeAll()
            }
        }
    }
 
    override fun onEventMainThread(event: BaseEvent?) {
        super.onEventMainThread(event)
        when (event!!.code) {
            BaseEvent.CHANGE_CAR_SUCCESS -> {
                initCall()
            }
            BaseEvent.CALL_NUM_MAIN -> {
            }
            BaseEvent.REFREASH_MAIN -> {
            }
        }
    }
 
    private var myMarker:Marker? = null
    override fun onMyLocationChange(p0: Location) {
        p0 as Inner_3dMap_location
        if (p0.latitude!=0.0){
            MyApplication.aMapLocation = AMapLocation(p0).apply {
                city = p0.city
            }
            CacheKey.putKeyStr("location", Gson().toJson(p0))
            Log.e(LogTag, "${p0.city} ${p0.address}:${p0.latitude},${p0.longitude}")
            aMap.animateCamera(CameraUpdateFactory.newLatLng(LatLng(p0.latitude, p0.longitude)))
            if (driverDataBean?.work == 1&&!isPause){
                getNearDriver()
            }
            if (myMarker == null){
                val markerOptions = MarkerOptions()
                markerOptions.position(LatLng(p0.latitude,p0.longitude)).icon(
                    BitmapDescriptorFactory.fromResource(
                        R.mipmap.my_location_with_text
                    )
                )
                myMarker = aMap.addMarker(markerOptions)
            }else
                myMarker?.position = LatLng(p0.latitude,p0.longitude)
        }
    }
}