宽窄优行-由【嘉易行】项目成品而来
younger_times
2023-07-04 38f768d39ba27d303147c59a222655b7c6cdfb25
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//
//  HomeVC.swift
//  OKProject
//
//  Created by alvin_y on 2020/5/27.
//  Copyright © 2020 yangwang. All rights reserved.
//
 
import UIKit
import VTMagic
import RxCocoa
import RxSwift
import SwifterSwift
 
/// 主页
class HomeVC: YYViewController {
    
    /// 协议
    private let agreement = AgreementView.instance()
    
    /// 标题
    private let view_title: HomeTitleView = HomeTitleView.instance()
    
    /// 广告
    private let advertising = AdvertisingView()
    
    /// 是否跳转用户中心
    private var isUserInfo = true
 
    let customerViewModel = MineContactCustomerServiceViewModel()
    
    /// 消息按钮
    private let button_message: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImage(UIImage.init(named: "icon_nav_news")!, for: .normal)
        btn.setTitle("", for: .normal)
        btn.bounds = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        btn.contentHorizontalAlignment = .center
        return btn
    }()
    
    /// 扫码按钮
    private let button_scan: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImage(UIImage.init(named: "icon_nav_scan")!, for: .normal)
        btn.setTitle("", for: .normal)
        btn.bounds = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        btn.contentHorizontalAlignment = .center
        return btn
    }()
    
    /// 个人中心按钮
    private let button_user: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setImage(UIImage.init(named: "icon_nav_user")!, for: .normal)
        btn.setTitle("", for: .normal)
        btn.bounds = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        btn.contentHorizontalAlignment = .center
        return btn
    }()
 
//    private let button_more:UIButton = {
//        let btn = UIButton.init(type: .custom)
//        btn.isHidden = true
//        btn.setImage(UIImage.init(named: "btn_more")!, for: .normal)
//        btn.setTitle("", for: .normal)
//        btn.backgroundColor = .white
//        btn.addShadow(ofColor: UIColor(hexString: "#E6E6E6")!.withAlphaComponent(0.5), radius: 4, offset: CGSize(width: -1, height: 0), opacity: 1)
//        return btn
//    }()
    
    /// VTMagicController
    private lazy var vtmagic: VTMagicController = {
        let vc = VTMagicController()
        vc.magicView.navigationColor = UIColor.color(light: UIColor.color(hexString: "#FFFFFF"), dark: UIColor.color(hexString: "#191919"))
        vc.magicView.layoutStyle = .default
        vc.magicView.navigationHeight = 0
        vc.magicView.separatorColor = UIColor.clear
        vc.magicView.sliderColor = UIColor.clear
        vc.magicView.dataSource = self
        vc.magicView.delegate = self
        vc.magicView.isScrollEnabled = false
        return vc
    }()
    
    /// 左侧菜单
    let leftMenu = HomeLeftMenuView.instance()
    
    /// 定位
    let locationViewModel = YYLocationViewModel()
    
    let viewModel = HomeViewModel()
    
    let sysViewModel = SystemMessageViewModel()
 
    private var showModularItems = [ShowModularModel]()
    
    /// UICollectionView
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let view = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.delegate = self
        view.dataSource = self
        view.register(HomeMenuCell.self, forCellWithReuseIdentifier: "item")
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        // 判断有没有同意协议
        if !UserDefaults.standard.bool(forKey: AgreeNotification){
            agreement.show()
            agreement.agree.delegate(on: self) { (self, _) in
                self.setup()
            }
        }else{
            self.setup()
        }
 
        customerViewModel.queryCustomerPhone()
 
        NotificationCenter.default.rx.notification(LoginSuccess_Noti).takeUntil(self.rx.deallocated).subscribe(onNext: {noti in
            self.setupAdvert()
        }).disposed(by: disposeBag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        yy_isHiddenNavBarLine = true
        if app.loginInfo.token.isEmpty{
            return
        }
        sysViewModel.queryNoReadNoticeNum()
    }
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if app.loginInfo.token.isEmpty{return}
        APIManager.shared.provider.rx.request(.gainMerchantCoupon).map(YYModel<[MerchantCouponModel]>.self).validate().subscribe(onSuccess: {data in
            if data.data?.count ?? 0 > 0{
                ObtainCouponView.show(items: data.data ?? [], vc: self)
            }
        }).disposed(by: disposeBag)
 
//        viewModel.queryShowModular()
    }
    
    
    //MARK: - 一些初始化操作
    func setup()  {
        YYSocketManager.shared().startSocket()
        // 之前没开通或没有选择定位
        self.locationViewModel.requestLocation()
        viewModel.queryUserInfo()
        viewModel.queryShowModular()
    }
    
    
    /// 设置广告
    func setupAdvert()  {
        viewModel.getAdvertising()
        DispatchQueue.main.asyncAfter(deadline: .now()+5) {
            if app.userInfo.soundSet == 0 && app.loginInfo.isLogin{
                AuthRecordView.show {
                    let vc = VoiceSettingVC()
                    self.yy_push(vc: vc)
                }
            }
        }
    }
    
    //MARK: - UI
    override func setupViews() {
        super.setupViews()
        navigationItem.titleView = view_title
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: button_user)
        navigationItem.rightBarButtonItems = [
            UIBarButtonItem.init(customView: button_scan)
            ,UIBarButtonItem.init(customView: button_message)]
        self.addChild(vtmagic)
        view.addSubview(vtmagic.magicView)
        
        collectionView.backgroundColor = UIColor.color(light: UIColor.color(hexString: "#FFFFFF"), dark: UIColor.color(hexString: "#191919"))
        view.addSubview(collectionView)
        app.window?.addSubview(leftMenu)
        leftMenu.didSelectRow.delegate(on: self) { (self, row) in
            DispatchQueue.main.async { [self] in
                switch row{
                    case 0://我的订单
                        let vc = MyOrderListVC()
                        self.yy_push(vc: vc)
                        break
                    case 1: // 优惠券
                        let vc = MineCouponsVC()
                        self.yy_push(vc: vc)
                        break
                    case 2: //企业认证
                        let vc = EnterpriseAuthVC()
                        self.yy_push(vc: vc)
                        break
                    case 3: //钱包
                        let vc = MineWalletVC()
                        self.yy_push(vc: vc)
                        break
                    case 4: //订单审核
                        let vc = OrderReviewListVC()
                        self.yy_push(vc: vc)
 
//                        self.show()
//                        APIManager.shared.provider.rx.request(.getUserUserList).map(YYModel<[UserRelationModel]>.self).validate().subscribe(onSuccess: {data in
//                            self.hide()
//                            if data.data!.count > 0{
//                                let vc = BindRelationVC()
//                                vc.relationM = data.data ?? []
//                                self.yy_push(vc: vc)
//                            }else{
//                                let vc = BindRelationAgreementVC()
//                                self.yy_push(vc: vc)
//                            }
//                        }) { error in
//                            self.hide()
//                            alert(text: error.localizedDescription)
//                        }.disposed(by: self.disposeBag)
                        break
                    case 5: //开发票
                        let vc = InvoiceViewController()
                        self.yy_push(vc: vc)
                        break
                    case 6: //意见反馈
                        let vc = MineFeedbackVC()
                        self.yy_push(vc: vc)
//                        self.show()
//                        APIManager.shared.provider.rx.request(.getMerchant).map(YYModel<MerchantInfoModel>.self).subscribe { model in
//                            self.hide()
//                            if model.data?.state == .delete || model.data?.state == .freeze{
//                                alert(text: String(format: "您的商家账号已%@,请联系平台:%@", model.data!.state.rawStr,self.customerViewModel.platform.value))
//                                return
//                            }
//
//                            if model.data?.auditStatus == .waiting{
//                                let vc = BusinessSubmitSuccessVC()
//                                self.yy_push(vc: vc)
//                            }else if model.data?.auditStatus == .agreent{
//                                let vc = MerchantVC()
//                                vc.merchantInfoModel = model.data
//                                self.yy_push(vc: vc)
//                            }else{
//                                let vc = BusinessVC()
//                                vc.merchantInfoModel = model.data
//                                self.yy_push(vc: vc)
//                            }
//                        } onError: { error in
//
//                        }.disposed(by: self.rx.disposeBag)
                        break
                    case 7: //客服
                        let vc = MineCustomerServiceVC()
                        self.yy_push(vc: vc)
//                        let vc = MineCommoentVC()
//                        self.yy_push(vc: vc)
                        break
                    case 8://设置
                        let vc = MineSetUpVC()
                        self.yy_push(vc: vc)
//                        let vc = MinePublishVC()
//                        self.yy_push(vc: vc)
                    case 9: //分享
                        let vc = MineShareVC()
                        self.yy_push(vc: vc)
//                        let vc = MineSafeVC()
//                        self.yy_push(vc: vc)
                        break
                    case 10: // 意见反馈
                        let vc = MineFeedbackVC()
                        self.yy_push(vc: vc)
                    case 11: //客服
                        let vc = MineCustomerServiceVC()
                        self.yy_push(vc: vc)
                        break
                    case 12: //设置
                        let vc = MineSetUpVC()
                        self.yy_push(vc: vc)
                        break
                    case 13: //分享
                        let vc = MineShareVC()
                        self.yy_push(vc: vc)
                        break
                    default:
                        break
                }
            }
        }
        
        leftMenu.didSelectMineInfo.delegate(on: self) { (self, _) in
            let vc = MineInfoVC()
            self.yy_push(vc: vc)
        }
        leftMenu.didPoinstMineInfo.delegate(on: self) { (self, _) in
            let vc = MyPointsVC()
            self.yy_push(vc: vc)
        }
        
    }
    
    //MARK: - Layouts
    override func defineLayouts() {
        super.defineLayouts()
        view_title.snp.makeConstraints { (make) in
            make.width.equalTo(screenW - 170)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.height.equalTo(40)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                make.top.equalToSuperview()
            }
        }
 
        vtmagic.magicView.snp.makeConstraints{make in
            if #available(iOS 11.0, *) {
                make.edges.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                make.edges.equalToSuperview()
            }
        }
        vtmagic.magicView.reloadData()
 
//        view.addSubview(button_more)
//        button_more.addTarget(self, action: #selector(itemMoreAction), for: .touchUpInside)
//        button_more.snp.makeConstraints { make in
//            make.top.equalToSuperview()
//            make.right.equalToSuperview()
//            make.width.equalTo(54)
//            make.height.equalTo(36)
//        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: - Rx
    override func bindRx() {
        super.bindRx()
        
        NotificationCenter.default.rx.notification(Notification.Name(rawValue: TokenInvalid), object: nil).subscribe(onNext: {[unowned self] (_) in
            app.userInfo.clear()
            app.loginInfo.clear()
            self.yy_popToRoot()
            self.button_message.showBadge(hidden: true,percentX: 0.75, percentY: 0.1,size: CGSize(width: 4, height: 4))
        }).disposed(by: disposeBag)
        
        sysViewModel.queryNoReadNoticeNumSubject
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self] (status) in
                switch status {
                    case .loading: break
                    case .success(let model):
                        guard let data: NoticeNumModel = model as? NoticeNumModel else{return}
                        self.button_message.showBadge(hidden: data.number > 0 ? false : true,percentX: 0.75, percentY: 0.1,size: CGSize(width: 4, height: 4))
                        break
                    case .error( _):
                        break
                }
            }).disposed(by: disposeBag)
        
        viewModel.requestSubject
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self] (status) in
                switch status {
                    case .loading: break
                    case .success(_):
                        if self.viewModel.popUpAdvert.value.count > 0{
                            self.advertising.show()
                        }
                        break
                    case .error(let error):
                        alert(text: error.localizedDescription)
                        break
                }
            }).disposed(by: disposeBag)
        
        YYMapViewManager.share.currentCity
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { (_) in
                self.view_title.text = YYLocationManager.shared.currentCity
            }).disposed(by: disposeBag)
        
        YYMapViewManager.share.callState
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { (state) in
                //                if state == .normal{
                // 判断
                //                    if self.collectionView.frame.origin.y < navH{
                //                        return
                //                    }
                //                }
                self.button_user.setImage(state == .called ? UIImage.init(named: "icon_back") : UIImage.init(named: "icon_nav_user")!, for: .normal)
                self.isUserInfo = !(state == .called)
                self.view_title.isHidden = state == .called ? true : false
                self.button_scan.isHidden = state == .called ? true : false
                self.button_message.isHidden = state == .called ? true : false
            }).disposed(by: disposeBag)
        
        NotificationCenter.default.rx.notification(Notification.Name(rawValue: YYTableViewContentOffset), object: nil).subscribe(onNext: {[unowned self] (n) in
            guard let offset = n.object as? CGPoint else{return}
            if offset.y >= -40{
                if self.collectionView.frame.origin.y == navH{
                    self.hiddenNavigationController(hidden: true)
                    UIView.animate(withDuration: 0.2) {
                        self.collectionView.transform = CGAffineTransform.init(translationX: 0, y: -40)
                    }
                }
            }else{
                if YYMapViewManager.share.callState.value == .normal{
                    self.hiddenNavigationController(hidden: false)
                }
                if self.collectionView.frame.origin.y < navH{
                    UIView.animate(withDuration: 0.2) {
                        self.collectionView.transform = CGAffineTransform.identity
                    }
                }
            }
        }).disposed(by: disposeBag)
        
        // 切换城市
        NotificationCenter.default.rx.notification(Notification.Name(rawValue: SwitchCityNotification), object: nil)
            .subscribe(onNext: {[unowned self] (_) in
                self.view_title.text = YYLocationManager.shared.currentCity
                self.viewModel.id.accept(YYLocationManager.shared.id)
                self.viewModel.queryBusinessTypeById()
                self.viewModel.queryShowModular()
                self.setupAdvert()
            }).disposed(by: disposeBag)
        
        view_title.rx.tap.subscribe(onNext: {[unowned self] (_) in
            let vc = SwitchCityVC()
            self.yy_push(vc: vc)
        }).disposed(by: disposeBag)
        
        locationViewModel.locationSubject
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self] (status) in
                switch status {
                    case .loading:
                        self.show()
                    case .success(_):
                        self.locationViewModel.validateCity()
                        self.setupAdvert()
                        self.viewModel.queryShowModular()
                        self.hide()
                    case .error(_):
                        self.hide()
                        alert(popup: .single, title: nil, text: "由于定位失败或您当前定位城市暂未开通,请选择服务城市",hiddenCloseButton: true, submitTitle: nil, cancelTitle: nil, submitClick: {[unowned self] in
                            let vc = SwitchCityVC()
                            self.yy_push(vc: vc)
                        }) {}
                }
            })
            .disposed(by: disposeBag)
        
        viewModel.queryBusinessTypeSubject
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self] (status) in
                switch status {
                    case .loading:
                        self.show()
                    case .success(_):
                        self.hide()
                        self.viewModel.queryShowModular()
                        self.collectionView.reloadData()
                        self.vtmagic.magicView.reloadData()
                    case .error(_):
                        self.hide()
                }
            }).disposed(by: disposeBag)
        
        
        locationViewModel.validateCitySubject
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: { [unowned self] (status) in
                switch status {
                    case .loading:
                        self.show()
                    case .success(_):
                        self.hide()
                        if YYLocationManager.shared.isValidated.value == true{
                            self.view_title.text = YYLocationManager.shared.currentCity
                            self.viewModel.queryBusinessType()
                        }else{
                            alert(popup: .single, title: nil, text: "由于定位失败或您当前定位城市暂未开通,请选择服务城市",hiddenCloseButton: true, submitTitle: nil, cancelTitle: nil, submitClick: {[unowned self] in
                                let vc = SwitchCityVC()
                                self.yy_push(vc: vc)
                            }) {}
                        }
                    case .error(_):
                        self.hide()
                }
            }).disposed(by: disposeBag)
 
 
        customerViewModel.requestSubject.subscribe(onNext: {status in
            switch status {
                case .success(_):break
 
                default:break
            }
        }).disposed(by: disposeBag)
        
        button_message.rx.tap.subscribe(onNext: {[unowned self] (_) in
            self.message()
        }).disposed(by: disposeBag)
        
        button_scan.rx.tap.subscribe(onNext: {[unowned self] (_) in
            self.scan()
        }).disposed(by: disposeBag)
        
        button_user.rx.tap.subscribe(onNext: {[unowned self] (_) in
            self.userInfo()
        }).disposed(by: disposeBag)
        
        // 弹窗广告
        viewModel.popUpAdvert.bind(to: self.advertising.items).disposed(by: disposeBag)
 
        viewModel.queryShowModularSubject.subscribe(onNext: { status in
            switch status{
                case .success(let model):
 
                    //74104 【更多服务】后台配置,关闭所有后,更多按钮也不应显示
                    let hidden = (model as? [ShowModularModel])?.filter({ m in
                        if m.type == 1 && m.userShow == 1{return true}
                        if m.type == 2 && m.userShow == 1{return true}
                        if m.type == 3 && m.userShow == 1{return true}
                        if m.type == 4 && m.userShow == 1{return true}
                        if m.type == 5 && m.userShow == 1{return true}
                        return false
                    }).count == 0
 
//                    self.button_more.isHidden = hidden
 
                    if let modularArray = model as? [ShowModularModel],modularArray.count > 0{
 
                        self.showModularItems = modularArray.sorted { m1, m2 in
                            return m1.nameIndex < m2.nameIndex
                        }
 
                        //74067 【特惠购卡】需根据返回的状态,是否显示 购卡模块、 我的商家中心模块
                        for item in modularArray {
                            if item.type == 6{
                                self.leftMenu.isHiddenMerchant = item.userShow == 2
                                self.leftMenu.tableView.reloadData()
                                break
                            }
                        }
                        self.vtmagic.magicView.reloadData()
                    }
                    self.vtmagic.magicView.reloadData()
                case .error(_):break
                case .loading:break
            }
        }) { error in
 
        }.disposed(by: disposeBag)
    }
    
    /// 是否隐藏导航栏
    /// - Parameter hidden: Bool
    func hiddenNavigationController(hidden: Bool)  {
        self.button_user.setImage(hidden ? UIImage.init(named: "arrow_up") : UIImage.init(named: "icon_nav_user")!, for: .normal)
        self.isUserInfo = !hidden
        self.button_scan.isHidden = hidden
        self.button_message.isHidden = hidden
        self.view_title.isHidden = hidden
    }
    
    //MARK: - Acttion
 
    @objc func itemMoreAction(){
 
        guard showModularItems.count != 0 else {
            viewModel.queryShowModular()
            alert(text: "正在加载中,请稍后再试");return
        }
 
        let moreVIew = HomeItemMoreView.show(self,items:showModularItems) {[weak self] index in
            guard let weakSelf = self else{return}
            switch index{
                case 3:
                    let vc = CarSaleListVC()
                    weakSelf.yy_push(vc: vc)
                case 5:
                   let vc = PublishSaleCarVC(nil, isEdit: false)
                    weakSelf.yy_push(vc: vc)
                case 2:
                    let vc = CarContractVC()
                    weakSelf.yy_push(vc: vc)
                case 4:
                    let vc = MinePublishHireEditVC(nil, isEdit: false)
                    weakSelf.yy_push(vc: vc)
                case 1:
                    let vc = JobViewController()
                    weakSelf.yy_push(vc: vc)
                default:break
            }
        }
 
        moreVIew.authdelegate.delegate(on: self) { (_,_) in
            let vc = MineRealNameVC()
            self.yy_push(vc: vc)
        }
    }
 
    /// 用户信息
    @objc func userInfo(){
        if self.isUserInfo{
            // 个人中心
            if isUserLogined(){
                leftMenu.show()
            }
        }else{
            if YYMapViewManager.share.callState.value == .called{
                YYMapViewManager.share.clearData()
                // 收起
                NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: YYTableViewReset)))
            }else{
                // 收起
                //                YYMapViewManager.share.callState.accept(.normal)
                NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: YYTableViewReset)))
            }
            
        }
    }
    
    /// 消息
    @objc func message(){
        if isUserLogined(){
            let vc = MessageVC()
            self.yy_push(vc: vc)
        }
    }
    
    /// 扫码
    @objc func scan(){
        if isUserLogined(){
            let vc = ScanVC()
            //            if let cuurentVc =  vtmagic.currentViewController,cuurentVc.isKind(of: TravelCityHomeVC.classForCoder()){
            //                // 跨城的扫码直接跳转
            //                vc.type = .scan
            //            }
            self.yy_push(vc: vc)
        }
    }
    
    //MARK: - Other
    /// 检测位置权限
    func detectionLocationPermissions()  {
        openLocationServiceWithBlock(false) {[unowned self] (success) in
            if success == true{
                self.locationViewModel.requestLocation()
            }else{
                alert(popup: .single, title: nil, text: "由于定位失败或您当前定位城市暂未开通,请选择服务城市",hiddenCloseButton: true, submitTitle: nil, cancelTitle: nil, submitClick: {[unowned self] in
                    let vc = SwitchCityVC()
                    self.yy_push(vc: vc)
                }) {}
            }
        }
    }
}
// MARK: - VTMagicViewDataSource
extension HomeVC: VTMagicViewDataSource {
    
    func menuTitles(for magicView: VTMagicView) -> [String] {
        return viewModel.menu.value.map{$0.name}
    }
    
    func magicView(_ magicView: VTMagicView, menuItemAt itemIndex: UInt) -> UIButton {
        let bt = magicView.dequeueReusableItem(withIdentifier: "item")
        if let button = bt{
            return button
        }else{
            let bt = UIButton()
            bt.titleLabel?.font = UIFont.init(name: Medium, size: 13)!
            bt.setTitleColor(UIColor.color(light: ThemeColor, dark: UIColor.color(hexString: "#FFFFFF")), for: .selected)
            bt.setTitleColor(UIColor.color(light: UIColor.color(hexString: "#8C9097"), dark: UIColor.color(hexString: "#8C9097")), for: .normal)
            return bt
        }
    }
    
    func magicView(_ magicView: VTMagicView, viewControllerAtPage pageIndex: UInt) -> UIViewController {
        let showCar = showModularItems.filter({$0.type == 7 && $0.userShow == 1}).count > 0
        let name = viewModel.menu.value.map{$0.name}[Int(pageIndex)]
        switch name {
            case "出租车":
                let vc = TravelVC.init(orderType: .taxi)
                vc.showCar = showCar
                return vc
            case "快车/专车":
                let vc = TravelVC(orderType: .special)
                vc.showCar = showCar
                return vc
            case "公务用车":
                let vc = TravelVC.init(orderType: .offical)
                vc.showCar = showCar
                vc.officialCharterClouse = { [weak self] (viewModel) in
                    
                    guard viewModel.trailReason.value != nil else {
                        alert(text: "请先选择出行事由");return
                    }
                    
                    
                    let officialCharterVC = OfficialCharterVC()
                    officialCharterVC.viewModel = viewModel
                    officialCharterVC.view.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: self?.view.height ?? 0)
                    self?.view.addSubview(officialCharterVC.view)
                    self?.addChild(officialCharterVC)
 
                    UIView.animate(withDuration: 0.6) {
                        officialCharterVC.view.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: self?.view.height ?? 0)
                    }
                }
                return vc
            case "机场专线","景区直通车","跨城出行":
                var vc: TravelCityHomeVC! = magicView.dequeueReusablePage(withIdentifier: String(describing: name)) as? TravelCityHomeVC
                if vc == nil {
                    vc = TravelCityHomeVC()
                    if name == "机场专线"{
                        vc.type = .plane
                    }else if name == "景区直通车"{
                        vc.type = .scenic
                    }else{
                        vc.type = .travel
                    }
                }
                vc.showCar = showCar
                return vc
            default:
                return UIViewController()
        }
    }
}
 
// MARK: - VTMagicViewDelegate
extension HomeVC: VTMagicViewDelegate{
    func magicView(_ magicView: VTMagicView, didSelectItemAt itemIndex: UInt) {
    }
    func magicView(_ magicView: VTMagicView, viewDidAppear viewController: UIViewController, atPage pageIndex: UInt) {
        //        let name = viewModel.menu.value.map{$0.name}[Int(pageIndex)]
        //        switch name {
        //        case "出租车":
        //            YYMapViewManager.share.orderType.accept(.taxi)
        //        case "快车":
        //            YYMapViewManager.share.orderType.accept(.special)
        //        default:
        //            break
        //        }
    }
}
 
// MARK: - UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
extension HomeVC: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.menu.value.map{$0.name}.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! HomeMenuCell
        cell.configure(model: viewModel.menu.value[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let name = viewModel.menu.value.map{$0.name}[indexPath.row]
        let width = name.width(UIFont.init(name: Medium, size: 13)!, height: 40)
        return CGSize(width: width + 20, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        for (value,item) in viewModel.menu.value.enumerated() {
            item.select = value == indexPath.row
        }
        self.collectionView.reloadData()
        self.vtmagic.magicView.switch(toPage: UInt(indexPath.row), animated: true)
    }
    
}
 
 
extension UIViewController
{
    
    /// 判断用户是否登录
    /// - Returns: Bool
    func isUserLogined() -> Bool {
        if app.loginInfo.token == "" {
 
            let vc = YYNavigationController.init(rootViewController: LoginVC())
            self.present(vc, animated: true, completion: nil)
            return false
            //下方是一键登录
 
            /// 没有sim卡
            if !UMCommonUtils.simSupportedIsOK(){
                let vc = YYNavigationController.init(rootViewController: LoginVC())
                self.present(vc, animated: true, completion: nil)
                return false
            }
            
            let model = UMCustomModel()
            model.changeBtnTitle = AttributedStringbuilder.build().add(string: "切换其他方式", withFont: UIFont.boldSystemFont(ofSize: 14), withColor: #colorLiteral(red: 0.2883645892, green: 0.2983885705, blue: 0.3578726053, alpha: 1)).mutableAttributedString
            model.navColor = .white
            model.navTitle = AttributedStringbuilder.build().add(string: "一键登录", withFont: UIFont.boldSystemFont(ofSize: 15), withColor: .black).mutableAttributedString
            model.logoImage = UIImage(named: "login_logo")!
            model.loginBtnBgImgs = [imageFromColor(color: #colorLiteral(red: 0.2883645892, green: 0.2983885705, blue: 0.3578726053, alpha: 1), viewSize: CGSize(width: screenW-28, height: 44)),imageFromColor(color: #colorLiteral(red: 0.2901960784, green: 0.2980392157, blue: 0.3568627451, alpha: 0.1), viewSize: CGSize(width: screenW-28, height: 44)),imageFromColor(color: #colorLiteral(red: 0.2883645892, green: 0.2983885705, blue: 0.3578726053, alpha: 1), viewSize: CGSize(width: screenW-28, height: 44))]
            model.loginBtnFrameBlock =  { (size,superSize,frame) in
                return CGRect(x: frame.origin.x, y: frame.origin.y, width: screenW-28, height: 44)
            }
            //2.调用取号接口,加速授权页的弹起
            //            UMCommonHandler.accelerateLoginPage(withTimeout: 30) { (dict) in
            //                YYAlertKit.dismiss()
            //                if  dict["resultCode"] as! String != PNSCodeSuccess {
            //                    alert(text: "授权失败")
            //                    let vc = YYNavigationController.init(rootViewController: LoginVC())
            //                    self.present(vc, animated: true, completion: nil)
            //                    return
            //                }
            //3.调用获取登录Token接口,可以立马弹起授权页
            UMCommonHandler.getLoginToken(withTimeout: 30, controller: self, model: model) { (reslutDict) in
                
                let code = reslutDict["resultCode"] as! String
                // 点击一键登录
                if code == PNSCodeSuccess{
                    // 获取token成功
                    let token = reslutDict["token"] as! String
                    print("一键登录token======\(token)")
                    self.requsetLogin(token: token)
                }else if code == PNSCodeLoginControllerClickChangeBtn{
                    // 其他登录方式
                    UMCommonHandler.cancelLoginVC(animated: true) {
                        let vc = YYNavigationController.init(rootViewController: LoginVC())
                        self.present(vc, animated: true, completion: nil)
                    }
                }
                //                }
            }
            return false
        } else {
            
            return true
        }
    }
    func requsetLogin(token:String){
        if token.isEmpty {
            let vc = YYNavigationController.init(rootViewController: LoginVC())
            self.present(vc, animated: true, completion: nil)
        }
        YYAlertKit.displayActivity()
        APIManager.shared.provider.rx
            .request(.oneClickLogin(accessToken: token))
            .map(YYModel<UserInfoModel>.self)
            .validate()
            .subscribe(onSuccess: { [unowned self] (model) in
                YYAlertKit.dismiss()
                guard let data = model.data else{return}
                app.loginInfo.token = data.token
                app.loginInfo.id = data.id
                app.userInfo.save(model: data)
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    //一键登录导致的BUG:需要重新连接Socket
                    YYSocketManager.shared().startSocket()
                }
                UMCommonHandler.cancelLoginVC(animated: true) {
                }
            }) { (error) in
                YYAlertKit.dismiss()
                alert(text: "登录失败,请选择其他登录方式")
            }
            .disposed(by: rx.disposeBag)
    }
}