lmw
2023-04-17 51f657872f152a115fb055ad8860093a5cdbc12d
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
package com.fuban.user.ui
 
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.PagerAdapter
import cn.sinata.rxnetty.NettyClient
import cn.sinata.xldutils.gone
import cn.sinata.xldutils.invisible
import cn.sinata.xldutils.utils.*
import cn.sinata.xldutils.visible
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.flyco.tablayout.listener.OnTabSelectListener
import com.fuban.user.FBApplication
import com.fuban.user.R
import com.fuban.user.network.HttpManager
import com.fuban.user.network.entity.*
import com.fuban.user.network.entity.Function
import com.fuban.user.network.request
import com.fuban.user.ui.charter.CharterFragment
import com.fuban.user.ui.crosscity.*
import com.fuban.user.dialog.BannerDialog
import com.fuban.user.dialog.AlertDialog
import com.fuban.user.dialog.UserRuleDialog
import com.fuban.user.ui.login.LoginActivity
import com.fuban.user.ui.logistics.LogisticsFragment
import com.fuban.user.ui.mine.*
import com.fuban.user.ui.trip.MapTripFragment
import com.fuban.user.ui.trip.OrderDetailActivity
import com.fuban.user.ui.trip.ScanActivity
import com.fuban.user.ui.trip.TripActivity
import com.fuban.user.utils.Const
import com.fuban.user.utils.PlaceHolderFragment
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.drawer_mine.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
 
class MainActivity : TransparentStatusBarActivity() {
    override fun setContentView() = R.layout.activity_main
 
    var isOpen: Boolean = false
    private var func: List<Function>? = null
    var lat = 0.0
    var lon = 0.0
 
    //起点信息,传递给扫码下单页面
    var startLat = 0.0
    var startLon = 0.0
    var startName = ""
 
    var userInfo: UserInfo? = null
    private val titles = arrayListOf<String>()
    var phoneEmergency = "" //报警电话
    var isTripping = false //是否有进行中的订单,如果没有 拖动地图才查询附近司机数量
 
    override fun initClick() {
        iv_mine.setOnClickListener {
            if (iv_mine.isSelected) {
                if (fragments[mViewPager.currentItem] is MapTripFragment) {
                    taxiFragment.back()
                } else {
                    logisticsFragment.back(false)
                }
            } else if (checkLogin())
                if (!drawer_main.isDrawerOpen(GravityCompat.START))
                    drawer_main.openDrawer(GravityCompat.START)
        }
 
        tv_score.setOnClickListener {
            userInfo?.apply {
                startActivity<ScoreActivity>("score" to integral)
            }
        }
        tv_order.setOnClickListener {
            startActivity<OrderActivity>()
        }
        tv_setting.setOnClickListener {
            startActivityForResult<SettingActivity>(500, "phone" to (userInfo?.phone ?: ""))
        }
        tv_city.setOnClickListener {
            startActivityForResult<ChooseCityActivity>(501)
        }
        iv_header_home.setOnClickListener {
            userInfo?.let {
                startActivity<UserInfoActivity>(
                    "nickName" to it.nickName, "avatar" to it.avatar,
                    "birthday" to it.birthday, "sex" to it.sex
                )
            }
        }
        tv_coupon.setOnClickListener {
            startActivity<MyCouponActivity>()
        }
        tv_safe.setOnClickListener {
            userInfo?.let {
                startActivity<SafetyActivity>(
                    "state" to it.verified,
                    "emergency" to it.emergencyContact,
                    "phone" to it.emergencyContactNumber,
                    "myPhone" to it.phone
                )
            }
        }
        tv_wallet.setOnClickListener {
            userInfo?.let {
                startActivity<WalletActivity>("balance" to it.balance)
            }
        }
        tv_passenger.setOnClickListener {
            startActivity<PassengersActivity>()
        }
        tv_invoice.setOnClickListener {
            //todo 当前版本不做
            myToast("请联系客服索要发票")
        }
        tv_share.setOnClickListener {
            startActivity<ShareAppActivity>()
        }
        iv_msg.setOnClickListener {
            if (checkLogin())
                startActivity<MsgActivity>()
        }
 
        tv_feed_back.setOnClickListener {
            startActivity<FeedbackActivity>()
        }
        tv_service.setOnClickListener {
            startActivity<ServiceActivity>()
        }
        iv_scan.setOnClickListener {
            if (checkLogin()) {
                if (!RxPermissions(this).isGranted(Manifest.permission.CAMERA) //没有权限且明确拒绝就不再申请权限
                    && SPUtils.instance().getBoolean(Const.User.IS_REFUSE_PERMISSION_CAMERA)
                ) {
                    myToast("请在应用权限页面开启相机权限")
                } else {
                    RxPermissions(this).request(Manifest.permission.CAMERA).subscribe {
                        if (it)
                            startActivity<ScanActivity>(
                                "startLat" to startLat,
                                "startLon" to startLon,
                                "startName" to startName
                            )
                        else{
                            myToast("请在应用权限页面开启相机权限")
                            SPUtils.instance().put(Const.User.IS_REFUSE_PERMISSION_CAMERA,true).apply()
                        }
                    }
                }
            }
        }
 
    }
 
 
    private val taxiFragment by lazy {
        MapTripFragment()
    }
    private val crossCityFragment by lazy {
        CrossCityFragment()
    }
    private val logisticsFragment by lazy {
        LogisticsFragment()
    }
    private val charterFragment by lazy {
        CharterFragment()
    }
    private val fragments = arrayListOf<Fragment>()
 
    override fun initView() {
        titleBar.gone()
        cl_title.gone()
        func = intent.getParcelableArrayListExtra<Function>("func") ?: arrayListOf()
//        func = arrayListOf(Function(1,"专车"),Function(3,"直通车"),Function(6,"包车"))
        isOpen = intent.getBooleanExtra("isOpen", false)
        lat = intent.getDoubleExtra("lat", 0.0)
        lon = intent.getDoubleExtra("lon", 0.0)
        if (!isOpen) {
            initLocation {
                initLocationS { b, fucS ->
                    cl_title.visible()
                    initTwoView(b, fucS, FBApplication.lat, FBApplication.lon)
                }
            }
        } else {
            cl_title.visible()
            initTwoView(
                isOpen,
                func ?: arrayListOf(),
                if (lat != 0.0) lat else FBApplication.lat,
                if (lon != 0.0) lon else FBApplication.lon
            )
        }
    }
 
    private fun initTwoView(b: Boolean, fucS: List<Function>, latNow: Double, lonNow: Double) {
        func = fucS
        isOpen = b
        lat = latNow
        lon = lonNow
        tv_city.text = FBApplication.chooseCityName
        if (isOpen && func!!.isNotEmpty()) {
            getPhone()
            getAgreement()
            titles.addAll(func!!.map { it.name })
            func!!.forEach {
                if (it.id in (1..2) && !fragments.contains(taxiFragment))
                    fragments.add(taxiFragment)
                else if (it.id == Const.OrderType.TYPE_CROSS_CITY)
                    fragments.add(crossCityFragment)
                else if (it.id in (4..5) && !fragments.contains(logisticsFragment))
                    fragments.add(logisticsFragment)
                else if (it.id == Const.OrderType.TYPE_CHARTER)
                    fragments.add(charterFragment)
            }
        } else {
            titles.addAll(arrayOf("专车", "直通车", "包车"))
            fragments.add(taxiFragment)
            showAlert()
        }
        drawer_main.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
 
        mViewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager, 0) {
            override fun getItem(position: Int) = fragments[position]
 
            override fun getCount() = fragments.size
 
            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//                super.destroyItem(container, position, `object`)
            }
 
            override fun getItemPosition(`object`: Any): Int {
                return PagerAdapter.POSITION_NONE
            }
        }
        initTab()
        NettyClient.getInstance().startService()
    }
 
    private fun initLocation(function: () -> Unit) {
        if (!RxPermissions(this).isGranted(Manifest.permission.ACCESS_FINE_LOCATION) //没有权限且明确拒绝就不再申请权限
            && SPUtils.instance().getBoolean(Const.User.IS_REFUSE_PERMISSION_LOCATION)
        ) {
            initTwoView(false, arrayListOf(), 0.0, 0.0)
        } else {
            val disposable =
                RxPermissions(this@MainActivity).request(Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe {
                        if (it) {
                            function()
                        } else {
                            SPUtils.instance().put(Const.User.IS_REFUSE_PERMISSION_LOCATION, true)
                                .apply()
                            initTwoView(false, arrayListOf(), 0.0, 0.0)
                        }
                    }
            onBindHelper(disposable)
        }
    }
 
    private fun showAlert() {
        val tipDialog = AlertDialog()
        tipDialog.setDismissCallback(object : AlertDialog.OnDismiss {
            override fun onDismiss() {
                startActivityForResult<ChooseCityActivity>(501)
            }
        })
        tipDialog.show(supportFragmentManager, "city")
    }
 
    private fun initTab() {
        val frags = arrayListOf<Fragment>()
        (0 until titles.size).forEach {
            frags.add(PlaceHolderFragment())
        }
        tabView.setViewPager(fake_viewpager, titles.toTypedArray(), this, frags)
        tabView.currentTab = 0
        if (func!!.isEmpty())
            return
        if (fragments[0] is MapTripFragment)
            taxiFragment.type = func!![0].id
        else {
            line_top.visible()
            if (fragments[0] is LogisticsFragment)
                logisticsFragment.type = func!![0].id
        }
        tabView.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                updateTip(func!![position].id)
                when (func!![position].id) {
                    Const.OrderType.TYPE_SPECIAL -> {
                        Log.e(Const.Tag, "当前模块为:专车")
                        line_top.gone()
                        mViewPager.currentItem = fragments.indexOf(taxiFragment)
                        taxiFragment.changeType(Const.OrderType.TYPE_SPECIAL)
                    }
                    Const.OrderType.TYPE_TAXI -> {
                        line_top.gone()
                        Log.e(Const.Tag, "当前模块为:出租车")
                        mViewPager.currentItem = fragments.indexOf(taxiFragment)
                        taxiFragment.changeType(Const.OrderType.TYPE_TAXI)
                    }
                    Const.OrderType.TYPE_CROSS_CITY -> {
                        line_top.visible()
                        Log.e(Const.Tag, "当前模块为:直通车")
                        mViewPager.currentItem = fragments.indexOf(crossCityFragment)
                        updateTitleVisibility(false, false)
                    }
                    Const.OrderType.TYPE_SAME_CITY -> {
                        Log.e(Const.Tag, "当前模块为:同城物流")
                        mViewPager.currentItem = fragments.indexOf(logisticsFragment)
                        taxiFragment.checkBack()
                        logisticsFragment.changeType(Const.OrderType.TYPE_SAME_CITY)
                    }
                    Const.OrderType.TYPE_TRANS_CROSS -> {
                        Log.e(Const.Tag, "当前模块为:跨城物流")
                        mViewPager.currentItem = fragments.indexOf(logisticsFragment)
                        taxiFragment.checkBack()
                        logisticsFragment.changeType(Const.OrderType.TYPE_TRANS_CROSS)
                    }
                    Const.OrderType.TYPE_CHARTER -> {
                        Log.e(Const.Tag, "当前模块为:包车")
                        mViewPager.currentItem = fragments.indexOf(charterFragment)
                        taxiFragment.checkBack()
                    }
                }
            }
 
            override fun onTabReselect(position: Int) {
            }
        })
        mViewPager.offscreenPageLimit = fragments.size
    }
 
    private fun getPhone() {
        HttpManager.getPhone(FBApplication.chooseCityCode).request(this) { _, data ->
            data?.let {
                it.forEach {
                    if (it.type == 1)
                        phoneEmergency = it.phone
                    else if (it.type == 2)
                        FBApplication.phoneService = it.phone
                }
            }
        }
    }
 
    /**
     * 查询是否有进行中的订单
     */
    fun queryTripping() {
        HttpManager.queryServingOrder().request(this, false) { _, data ->
            data?.let {
                if (it.isNullOrEmpty()) {
                    isTripping = false
                    if (fragments.contains(taxiFragment))
                        taxiFragment.getDriverNum()
                    tv_tip.onClick { }
                } else {
                    isTripping = true
                    val order = data[0]
                    tv_tip.text = "您有一笔订单正进行中"
                    tv_tip.setOnClickListener {
                        if (tv_tip.alpha != 0f) {
                            if (order.state in (1..6) || order.state == 11)
                                startActivity<TripActivity>(
                                    "id" to order.orderId,
                                    "type" to order.orderType
                                )
                            else if (order.state == 7 && order.orderType == Const.OrderType.TYPE_CROSS_CITY) {
                                startActivity<PayCrossActivity>("id" to order.orderId)
                            } else
                                startActivity<OrderDetailActivity>(
                                    "id" to order.orderId,
                                    "type" to order.orderType
                                )
                        }
                    }
                }
            }
        }
    }
 
    private fun queryUserInfo() {
        HttpManager.queryUserInfo().request(this) { _, data ->
            userInfo = data
            data?.run {
                iv_header_home.setImageURI(avatar)
                tv_name.text = nickName
                tv_score.text = String.format("当前积分%s", if (integral.isEmpty()) "0" else integral)
                FBApplication.emergency = emergencyContactNumber
                FBApplication.phone = phone
            }
        }
    }
 
    private fun queryUnReadNum() {
        HttpManager.queryUnReadNum().request(this, false) { _, data ->
            data?.run {
                iv_unread.visibility = if (optInt("number") > 0) View.VISIBLE else View.GONE
            }
        }
    }
 
    private fun updateTip(orderType: Int) {
        if (orderType > Const.OrderType.TYPE_TAXI)
            tv_tip.gone()
        else
            tv_tip.visible()
    }
 
    fun updateLogisticsTitle(show: Boolean) {
        tv_logistics_title.visibility = if (show) View.VISIBLE else View.GONE
    }
 
    fun updateTabVisibility(show: Boolean) {
        tabView.visibility = if (show) View.VISIBLE else View.GONE
    }
 
    fun updateTipAlpha(f: Float) {
        tv_tip.alpha = f
    }
 
    fun updateTipText(t: String) {
        tv_tip.text = t
    }
 
    /**
     * @param isHide true:广告上滑消失 false:下滑显示
     * @param isChange true:确认订单步骤隐藏 false:返回上一步显示
     */
    fun updateTitleVisibility(isHide: Boolean, isChange: Boolean) {
        cl_title.visibility = if (isHide) View.GONE else View.VISIBLE
        if (isChange) {
            tv_city.invisible()
            cl_right.gone()
            iv_mine.isSelected = true
        } else {
            tv_city.visible()
            cl_right.visible()
            iv_mine.isSelected = false
        }
    }
 
    private var privacy = "" //隐私协议
    private var user = "" //用户协议
    private fun getAgreement() {
        if (!SPUtils.instance().getBoolean(Const.User.IS_AGREE, false)) {
            HttpManager.getH5(1).request(this) { _, data ->
                privacy = data?.optString("content") ?: ""
                showPrivacyAgreement()
            }
            HttpManager.getH5(2).request(this) { _, data ->
                user = data?.optString("content") ?: ""
                showPrivacyAgreement()
            }
        } else if (isOpen)
            getAds()
    }
 
    private fun showPrivacyAgreement() {
        if (privacy.isNotEmpty() && user.isNotEmpty()) {
            val userRuleDialog = UserRuleDialog()
            userRuleDialog.arguments = bundleOf("privacy" to privacy, "user" to user)
            userRuleDialog.setDismissCallback(object : UserRuleDialog.OnDismiss {
                override fun onDismiss() {
                    if (!SPUtils.instance().getBoolean(Const.User.IS_AGREE, false))
                        finish()
                    else
                        getAds()
                }
            })
            userRuleDialog.show(supportFragmentManager, "rule")
        }
    }
 
    private fun getAds() {
        HttpManager.getAds(1, FBApplication.chooseCityCode).request(this) { _, data ->
            data?.let {
                if (it.isNotEmpty()) {
                    val bannerDialog = BannerDialog()
                    bannerDialog.arguments = bundleOf("data" to it)
                    bannerDialog.show(supportFragmentManager, "banner")
                }
            }
        }
    }
 
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 500 && resultCode == Activity.RESULT_OK) {
            resetLogin()
            if (data?.getBooleanExtra("toLogin", false) == true)
                startActivity<LoginActivity>()
        } else if (requestCode == 501) {//选择城市
            if (resultCode == Activity.RESULT_OK && data != null) {
                startActivity<MainActivity>(
                    "isOpen" to true,
                    "func" to data.getParcelableArrayListExtra<Function>("func"),
                    "lat" to data.getDoubleExtra("lat", 0.0),
                    "lon" to data.getDoubleExtra("lon", 0.0)
                )
                finish()
            } else if (!isOpen || func!!.isEmpty()) {
                showAlert()
            }
        }
    }
 
    /**
     * 恢复未登录状态
     */
    fun resetLogin() {
        drawer_main.closeDrawer(GravityCompat.START)
        isTripping = false
        if (fragments.contains(taxiFragment))
            taxiFragment.getDriverNum()
    }
 
    override fun onResume() {
        super.onResume()
        refreshInfo()
    }
 
    fun refreshInfo() {
        if (checkLogin(false)) {
            queryTripping()
            queryUserInfo()
            queryUnReadNum()
        }
    }
 
    override fun onBackPressed() {
        if (drawer_main.isDrawerOpen(GravityCompat.START))
            drawer_main.closeDrawer(GravityCompat.START)
        else if (iv_mine.isSelected && fragments[mViewPager.currentItem] is LogisticsFragment)
            logisticsFragment.back(false)
        else if (taxiFragment.checkBack())
            super.onBackPressed()
    }
 
 
    private val aMapLocationClient by lazy {
        AMapLocationClient(this)
    }
 
    fun initLocationS(function: (Boolean, List<Function>) -> Unit) {
        val func = arrayListOf<Function>()//开通业务模块,MainActivity必须参数
        val option = AMapLocationClientOption()
        option.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        option.isMockEnable = false
        option.isOnceLocation = true
        aMapLocationClient.setLocationOption(option)
        aMapLocationClient.setLocationListener {
            if (it.errorCode == 0) {
                FBApplication.cityCode = it.adCode
                FBApplication.cityName = it.city
                FBApplication.lat = it.latitude
                FBApplication.lon = it.longitude
                HttpManager.isOpenCity(it.adCode).request(this, success = { _, data ->
                    data?.run {
                        if (optInt("open") == 1) {//当前城市开通
                            FBApplication.chooseCityName = it.city
                            FBApplication.chooseCityCode = it.adCode
                            HttpManager.queryBusiness(it.city, it.province, it.district)
                                .request(this@MainActivity, success = { _, data ->
                                    Log.e(
                                        Const.Tag,
                                        "当前城市业务模块" + data?.joinToString(",") { it.name })
                                    func.addAll(data ?: arrayListOf())
                                    function(true, func)
                                }, error = { _, _ ->
                                    function(false, func)
                                })
                        } else {//未开通
                            myToast("当前城市未开通")
                            function(false, func)
                        }
                    }
                }, error = { _, _ ->
                    function(false, func)
                })
                Log.e("mmp", it.city)
            } else {//定位失败
                myToast("定位失败")
                function(false, func)
            }
        }
        aMapLocationClient.startLocation()
    }
}