无故事王国
4 天以前 41aa6375f4086c3bbabd00c710c0734b25962d78
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//
//  HomeListenFightVC.swift
//  DolphinEnglishLearnStudent
//
//  Created by 无故事王国 on 2024/5/23.
//
 
import UIKit
import FFPage
import RxRelay
 
let NextLession_Noti = Notification.Name.init("NextLession_Noti")
let ResetLession_Noti = Notification.Name.init("ResetLession_Noti")
//let Reload_Noti = Notification.Name.init("Reload_Noti")
 
enum ListenType:Int{
    case lesson1 = 1 //自主学习-听音选图
    case lesson2 = 2 //自主学习-看图选音
    case lesson3 = 3 //自主学习-归纳排除
    case lesson4 = 4 //自主学习-有问有答
    case lesson5 = 5 //自主学习-音图相配
    case game1 = 6 //游戏类型-超级听力
    case game2 = 7 //游戏类型-超级记忆
    case story1 = 8 //故事类型-自主故事1-看图配音
    case story2 = 9 //故事类型-自主故事2-框架记忆
 
    var rawTitle:String{
        switch self {
        case .lesson1:return "自主学习1-听音选图"
        case .lesson2:return "自主学习2-看图选音"
        case .lesson3:return "自主学习3-归纳排除"
        case .lesson4:return "自主学习4-有问有答"
        case .lesson5:return "自主学习5-音图相配"
        case .game1:return "游戏类型1-超级听力"
        case .game2:return "游戏类型2-超级记忆"
        case .story1:return "自主故事1-看图配音"
        case .story2:return "自主故事2-框架记忆"
        }
    }
}
 
enum ListenFightLine{
    case before
    case next
    case none
}
 
 
//中途退出所需要
class ExitLearnModel{
    var topicsIds = Set<Int>()
}
 
class HomeListenFightViewModel{
 
    /// 当前页数
    var currentPage = BehaviorRelay<Int?>(value: nil)
    var maxPage = BehaviorRelay<Int>(value: 5)
    var listenType = BehaviorRelay<ListenType>(value:.lesson1)
    var times:Int = 0
    var quarter = BehaviorRelay<Int?>(value: 0)
    var week = BehaviorRelay<Int?>(value: 0)
    var day = BehaviorRelay<Int?>(value: 0)
 
    //游戏专属,游戏等级
    var gameLevel = BehaviorRelay<Int>(value:0)
 
    //回答错误数量
    var correctNum:Int = 0{
        didSet{
            print("回答正确:\(correctNum)")
        }
    }
 
    /// 回答错误数量
    var errorNum:Int = 0{
        didSet{
            print("回答错误:\(correctNum)")
        }
    }
 
    //所有回答的 两游戏在用
    var answerItems = Dictionary<Int,Any>() //{page:0,data:String,currectAt:0}
    var answerCount = BehaviorRelay<Int>(value: 1)
 
    var answerItems_1 = Dictionary<String,Array<Int>>()
 
    //回答正确的题
    func insertCorrectAnswer(teamId:String?,answerId:Int){
        guard teamId != nil else {return}
        if answerItems_1[teamId!] == nil{
            answerItems_1[teamId!] = Array<Int>()
        }
 
        answerItems_1[teamId!]!.append(answerId)
    }
}
 
class HomeListenFightVC: BaseVC {
    private var viewModel = HomeListenFightViewModel()
    var studyScheduleModel:StudyScheduleModel? //学习进度(上级传递)
    var listenFightLine:ListenFightLine = .none
    var data:Any?
 
    var maxPage = 0 //最大页记录
    var teamScheduleModel:TeamScheduleModel? //上次中途退出,答题记录
    var pages = [[ListenSubCardModel]]() //分页显示
 
    private var notiObject:Dictionary<String,Any>?
 
    private lazy var label_pageNum:UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 14, weight: .medium)
        label.textColor = .black.withAlphaComponent(0.81)
        label.textAlignment = .center
        label.numberOfLines = 2
        label.text = "已完成:0/0\n正确率:--%"
        return label
    }()
 
    private lazy var btn_forward:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("上一题", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(Config.ThemeColor, for: .normal)
        btn.jq_borderColor = Config.ThemeColor
        btn.backgroundColor = .white
        btn.jq_borderWidth = 1
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var collection_card:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 2
        layout.minimumLineSpacing = 2
        layout.itemSize = CGSize(width: 24, height: 24)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        return collectionView
    }()
 
    private lazy var btn_beAgain:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("重新开始", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(Config.ThemeColor, for: .normal)
        btn.jq_borderColor = Config.ThemeColor
        btn.backgroundColor = .white
        btn.jq_borderWidth = 1
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var btn_continue:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("继续答题", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(Config.ThemeColor, for: .normal)
        btn.jq_borderColor = Config.ThemeColor
        btn.backgroundColor = .white
        btn.jq_borderWidth = 1
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var btn_forward_mini:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("上一小题", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(Config.ThemeColor, for: .normal)
        btn.jq_borderColor = Config.ThemeColor
        btn.backgroundColor = .white
        btn.isHidden = true
        btn.jq_borderWidth = 1
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var btn_next:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("下一题", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(Config.ThemeColor, for: .normal)
        btn.jq_borderColor = Config.ThemeColor
        btn.backgroundColor = .white
        btn.jq_borderWidth = 1
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var btn_exit:UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("退出", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = Config.ThemeColor
        btn.jq_cornerRadius = 4
        return btn
    }()
 
    private lazy var pageVC:FFPageViewController = {
        let vc = FFPageViewController()
        vc.scrollview.isScrollEnabled = false
        return vc
    }()
 
    private var timer:Timer!
 
 
    init(listenType:ListenType,quarter:Int? = nil,week:Int? = nil,day:Int? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.viewModel.listenType.accept(listenType)
        self.viewModel.week.accept(week)
        self.viewModel.day.accept(day)
        self.viewModel.quarter.accept(quarter)
 
        if listenType == .game1 || listenType == .game2{
            self.viewModel.maxPage.accept(1)
        }
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        sceneDelegate?.suspendTimer()
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
 
        yy_popBlock = {[weak self] in
            self?.quitAction(isPop: true)
        }
 
        btn_exit.addTarget(self, action: #selector(quitAction), for: .touchUpInside)
        btn_forward.addTarget(self, action: #selector(beforeAction), for: .touchUpInside)
        btn_forward_mini.addTarget(self, action: #selector(beforeAction_mini), for: .touchUpInside)
        btn_next.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
        btn_beAgain.addTarget(self, action: #selector(beAgaionAction), for: .touchUpInside)
 
        setPages()
//        pageVC.reloadData()
 
        timer = Timer(fire: .distantPast, interval: 1.0, repeats: true, block: {[weak self] _ in
            self?.viewModel.times += 1
        })
 
        timer.fire()
        RunLoop.current.add(timer, forMode: .common)
        setPages()
 
        if let teamSchedule = teamScheduleModel{
            viewModel.correctNum = viewModel.correctNum + teamSchedule.correctNumber
            viewModel.errorNum = teamSchedule.answerNumber - teamSchedule.correctNumber
            maxPage    = teamSchedule.schedule
 
            switch viewModel.listenType.value{
            case .lesson1:
 
                if let m  = data as? ListenNewModel{
                    self.pages = Array<ListenSubCardModel>.splitArray(m.list, subArraySize: 4)
                    let c = m.subjectList.count
                    let totalW = 24 * c + 2 * (c - 1)
                    collection_card.snp.updateConstraints { make in
                        make.width.equalTo(totalW)
                    }
                }
 
            case .lesson4:
                if let m  = data as? ListenNewModel{
                    self.pages = Array<ListenSubCardModel>.splitArray(m.list, subArraySize: 4)
                    let totalW = 24 * m.subjectList.count + 2 * (m.subjectList.count - 1)
                    collection_card.snp.updateConstraints { make in
                        make.width.equalTo(totalW)
                    }
                }
 
            case .lesson2,.lesson3,.lesson5:
                if let m  = data as? ListenNewModel{
                    self.pages = Array<ListenSubCardModel>.splitArray(m.list, subArraySize: 1)
                    let totalW = 24 * m.list.count + 2 * (m.list.count - 1)
                    collection_card.snp.updateConstraints { make in
                        make.width.equalTo(totalW)
                    }
                }
            default:break
            }
 
            switch viewModel.listenType.value {
            case .lesson1:
                collection_card.reloadData()
                let nextPage = floor(Double(maxPage) / 5.0)
                pageVC.scroll(toPage: Int(nextPage), animation: false)
                viewModel.currentPage.accept(Int(nextPage))
                viewModel.answerCount.accept(maxPage)
                setPages()
 
            case .lesson2:
                collection_card.reloadData()
                let maxCount = (data as! ListenNewModel).subjectList.count
                let page = min((maxPage - 1),maxCount)
                if pageVC.currentPage != page{
                    viewModel.currentPage.accept(page)
                    pageVC.scroll(toPage: page, animation: false)
                    setPages()
                }
 
            case .lesson4:
                collection_card.reloadData()
                let maxCount = (data as! ListenNewModel).subjectList.count
                let page = min((maxPage - 1),maxCount)
                if pageVC.currentPage != page{
                    viewModel.currentPage.accept(page)
                    pageVC.scroll(toPage: page, animation: false)
                    setPages()
                }
 
 
            case .lesson3,.lesson5:
                collection_card.reloadData()
                let maxCount = (data as! ListenNewModel).subjectList.count
                let page = min((maxPage - 1),maxCount)
                if pageVC.currentPage != page{
                    viewModel.currentPage.accept(page)
                    pageVC.scroll(toPage: page, animation: false)
                    setPages()
                }
 
 
            default:break
            }
        }
    }
 
    override func setUI() {
        super.setUI()
 
        switch viewModel.listenType.value{
        case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:
            collection_card.delegate = self
            collection_card.dataSource = self
            collection_card.register(CardItemCCell.self, forCellWithReuseIdentifier: "_CardItemCCell")
        default:break
        }
 
        craeteFootFuncView()
 
        pageVC.delegate = self
        view.addSubview(pageVC.view)
        pageVC.view.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            if self.viewModel.listenType.value == .lesson3 || self.viewModel.listenType.value == .lesson4{
                make.bottom.equalTo(self.label_pageNum.snp.top).offset(-52)
            }else{
                make.bottom.equalTo(self.label_pageNum.snp.top).offset(-52)
            }
        }
    }
 
 
    private func showGameLevel(canLevel:Int){
        ChooseLevelView.show(canLevel: canLevel) {[weak self] level in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.gameLevel.accept(level)
            Services.gameHearing(difficulty: level, quarter: weakSelf.viewModel.quarter.value!, week: weakSelf.viewModel.week.value!).subscribe(onNext: {result in
                GameBeginTipView.show {
                    if let data = result.data{
                        weakSelf.data = data
                        (weakSelf.data as! Listen1Model).data?.playNow = true
                        weakSelf.pageVC.reloadData()
                    }
                }
            },onError: {[weak self] _ in
                self?.navigationController?.popViewController(animated: true)
            }).disposed(by: weakSelf.disposeBag)
        } cancelClouse: { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
 
    private func craeteFootFuncView(){
 
        view.addSubview(collection_card)
 
        btn_forward.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.equalTo(124)
        }
 
        btn_beAgain.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.equalTo(124)
        }
 
        btn_continue.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.equalTo(124)
        }
 
 
        btn_exit.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.equalTo(124)
        }
 
 
        let stackView = UIStackView(arrangedSubviews: [btn_beAgain,label_pageNum,btn_exit])
        if viewModel.listenType.value == .story2{
            btn_next.snp.makeConstraints { make in
                make.height.equalTo(40)
                make.width.equalTo(124)
            }
            stackView.insertArrangedSubview(btn_next, at: 2)
        }
 
        stackView.spacing = 22
        view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-5)
            make.centerX.equalToSuperview()
            make.height.equalTo(40)
        }
 
        switch viewModel.listenType.value{
        case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:
            collection_card.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.width.equalTo(10)
                make.bottom.equalTo(stackView.snp.top).offset(-10)
                make.height.equalTo(24)
            }
        default:break
        }
    }
 
    override func setRx() {
        NotificationCenter.default.rx.notification(NextLession_Noti).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] noti in
            guard let weakSelf = self else { return }
            let nextPage = (weakSelf.viewModel.currentPage.value ?? 0) + 1
            var asComplete:Bool = false
            switch weakSelf.viewModel.listenType.value {
            case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:asComplete = nextPage >= (weakSelf.data as! ListenNewModel).subjectList.count
            case .game1,.game2:asComplete = true
            case .story1,.story2: asComplete = nextPage >= (weakSelf.data as! Listen1Model).storyList.count
            }
 
            if asComplete{
                switch weakSelf.viewModel.listenType.value {
                case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:
                    weakSelf.studyComplete()
                case .game1,.game2:
                    weakSelf.notiObject = noti.object as? Dictionary<String,Any>
                    weakSelf.timer.invalidate()
 
                    if let isComplete = weakSelf.notiObject?["complete"] as? Bool{
                        if isComplete{
                            weakSelf.btn_exit.setTitle("提交", for: .normal)
                        }else{
                            weakSelf.gamesComplete(gameId: weakSelf.notiObject!["gameId"] as! Int,integral: weakSelf.notiObject!["gameIntegral"] as! Int)
                        }
                    }
                case .story1,.story2:
                    if let dict = noti.object as? Dictionary<String,Any>{
                        let type = weakSelf.viewModel.listenType.value == .story1 ? 1:2
                        let accracy = floor(Double(weakSelf.viewModel.correctNum) / Double(weakSelf.viewModel.correctNum + weakSelf.viewModel.errorNum) * 100).int
                        weakSelf.storyComplete(storyId: dict["storyId"] as! Int, accuracy: accracy, studyTime: weakSelf.viewModel.times, type: type, integral: dict["storyIntegral"] as! Int)
                    }
                }
                return
            }
 
            if weakSelf.viewModel.listenType.value == .story2{
                weakSelf.btn_next.isHidden = (nextPage + 1) == weakSelf.viewModel.maxPage.value
                if weakSelf.btn_next.isHidden{
                    weakSelf.btn_exit.setTitle("完成", for: .normal)
                }
            }
 
            weakSelf.listenFightLine = .next
            weakSelf.pageVC.scroll(toPage: nextPage, animation: true)
            weakSelf.viewModel.currentPage.accept(nextPage)
        }).disposed(by: disposeBag)
 
        viewModel.currentPage.subscribe(onNext: {[weak self]currentPage in
            guard let weakSelf = self else { return }
            guard let currentPage else {return}
            weakSelf.btn_forward.isHidden = currentPage <= 0
            weakSelf.setPages()
        }).disposed(by: disposeBag)
 
        viewModel.answerCount.subscribe(onNext: {[weak self] count in
            self?.setPages()
        }).disposed(by: disposeBag)
    }
 
    private func setPages(){
        guard let currentPage = viewModel.currentPage.value else {return}
        switch viewModel.listenType.value{
        case .lesson1:
            let m = data as! ListenNewModel
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.flatMap({$0}).count / 4)"
            let correctNum = m.list.filter({$0.status == 2}).count //正确
            //                if correctNum > 0 {
            let ratio = Double(correctNum) / Double(m.list.count) * 100.0
            let ratioStr = ratio.jq_formatFloat
 
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.flatMap({$0}).count / 4)\n正确率:\(ratioStr)%"
            //                }
 
            maxPage = viewModel.answerCount.value
            btn_forward.isHidden = viewModel.answerCount.value == 1
        case .lesson3:
            let m = data as! ListenNewModel
//            label_pageNum.text = "已完成:\(viewModel.currentPage.value + 1)/\(m.subjectList.count / 6)"
            btn_forward.isHidden = currentPage == 0
            let page = currentPage + 1
            maxPage = page
 
            let correctNum = m.list.filter({$0.status == 2}).count //正确
            let ratio = Double(correctNum) / Double(m.list.count) * 100.0
            let ratioStr = ratio.jq_formatFloat
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.count)\n正确率:\(ratioStr)%"
 
        case .lesson2:
            let m = data as! ListenNewModel
//            label_pageNum.text = "已完成:\(viewModel.currentPage.value + 1)/\(m.subjectList.count)"
            btn_forward.isHidden = viewModel.currentPage.value == 0
            let page = currentPage + 1
            maxPage = page
 
            let correctNum = m.list.filter({$0.status == 2}).count //正确
            let ratio = Double(correctNum) / Double(m.list.count) * 100.0
            let ratioStr = ratio.jq_formatFloat
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.count)\n正确率:\(ratioStr)%"
 
        case .lesson5:
            let m = data as! ListenNewModel
//            label_pageNum.text = "已完成:\(viewModel.currentPage.value + 1)/\(m.subjectList.count)"
            btn_forward.isHidden = viewModel.currentPage.value == 0
            let page = currentPage + 1
            maxPage = page
 
            let correctNum = m.list.filter({$0.status == 2}).count //正确
            let ratio = Double(correctNum) / Double(m.list.count) * 100.0
            let ratioStr = ratio.jq_formatFloat
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.count)\n正确率:\(ratioStr)%"
 
        case .lesson4:
            let m = data as! ListenNewModel
            //两题为一组:需要/2
            label_pageNum.text = "已完成:\(currentPage + 1)/\(m.subjectList.count)"
            let page = currentPage + 1
            //                                                                maxPage = max(page,maxPage)
            maxPage = page
 
            let correctNum = m.list.filter({$0.status == 2}).count //正确
            let ratio = Double(correctNum) / Double(m.list.count) * 100.0
            let ratioStr = ratio.jq_formatFloat
            label_pageNum.text = "已完成:\(viewModel.answerCount.value)/\(m.subjectList.count)\n正确率:\(ratioStr)%"
        case .game1,.game2:
            btn_forward.isHidden = true
            label_pageNum.isHidden = true
 
            if viewModel.listenType.value == .game1{
                showGameLevel(canLevel: studyScheduleModel?.gameDifficulty ?? 0)
            }
        case .story1:
            if viewModel.listenType.value == .story2{
                btn_next.isHidden = (currentPage + 1) == viewModel.maxPage.value
                if btn_next.isHidden{
                    btn_exit.setTitle("完成", for: .normal)
                }
            }
            fallthrough
        case .story2:
            let count = (data as! Listen1Model).storyList.count
            viewModel.maxPage.accept(count)
            label_pageNum.text = "已完成:\(currentPage + 1)/\(count)"
        }
    }
 
 
    /// 学习类完成
    /// - Parameter ignorePush: 是否忽略跳转(未完成答题 :true)
    private func studyComplete(){
        let ids:String = viewModel.answerItems_1.keys.sorted().joined(separator: ",")
 
        //正确率
        let accracy = floor(Double(viewModel.correctNum) / Double(viewModel.correctNum + viewModel.errorNum) * 100).int
 
        Services.completeLearing(type: viewModel.listenType.value.rawValue, studyTime: viewModel.times, studyIds: ids, quarter: viewModel.quarter.value!, week: viewModel.week.value!, day: viewModel.day.value!, accracy: accracy).subscribe(onNext: {data in
            NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
            NotificationCenter.default.post(name: StudyCompleteCoinUpdate_Noti, object: data.data ?? 0)
        }).disposed(by: disposeBag)
 
        timer.invalidate()
 
        let vc = HomeStudyCompleteVC(viewModel: viewModel,studyScheduleModel: studyScheduleModel!)
        vc.title = viewModel.listenType.value.rawTitle
        vc.viewModel = viewModel
        push(vc: vc)
    }
 
    //游戏类完成
    private func gamesComplete(gameId:Int,integral:Int){
 
        var name = ""
        var accuracy:Int = 0
        var totalNum:Double = 0
 
        if viewModel.listenType.value == .game1{
            name = "超级听力"
            totalNum =  Double(viewModel.correctNum + viewModel.errorNum)
            if totalNum > 0{
                accuracy = floor(Double(viewModel.correctNum) / totalNum * 100).int
            }
        }else{
            name = "超级记忆"
            let v = viewModel.answerItems.first?.value as! Listen1Model
            //11887:完成答题页,总题目、错误题目 数量计算逻辑错误(只要是没有答对的题目就算错误题目,不管是否答,相当于错误题目就是总题目减去正确题目)
            totalNum = Double(v.photoList.count)
            if totalNum > 0 && viewModel.correctNum > 0 && viewModel.errorNum > 0{
                accuracy = floor(Double(viewModel.correctNum) / Double(totalNum) * 100).int
            }
            viewModel.errorNum = Int(totalNum) - viewModel.correctNum
        }
 
        Services.completeGames(gameId: gameId, gameName: name, difficulty: viewModel.gameLevel.value, accuracy: accuracy, useTime: viewModel.times).subscribe(onNext: {data in
            NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
            NotificationCenter.default.post(name: StudyCompleteCoinUpdate_Noti, object: data.data ?? 0)
        }).disposed(by: disposeBag)
 
        timer.invalidate()
 
        let vc = HomeStudyCompleteVC(totalNum:totalNum.int,viewModel: viewModel,studyScheduleModel: studyScheduleModel!)
        vc.title = viewModel.listenType.value.rawTitle
        vc.viewModel = viewModel
        push(vc: vc)
    }
 
    private func storyComplete(storyId:Int,accuracy:Int,studyTime:Int,type:Int,integral:Int){
        timer.invalidate()
        Services.completeStory(storyId: storyId, accuracy: accuracy, studyTime: studyTime, type: type).subscribe(onNext: {data in
            NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
            NotificationCenter.default.post(name: StudyCompleteCoinUpdate_Noti, object: data.data ?? 0)
        }).disposed(by: disposeBag)
 
        let vc = HomeStudyCompleteVC(viewModel: viewModel,studyScheduleModel: studyScheduleModel!)
        vc.title = viewModel.listenType.value.rawTitle
        vc.viewModel = viewModel
        push(vc: vc)
    }
 
    deinit{
        timer.invalidate()
    }
 
    @objc func quitAction(isPop:Bool = false){
        if btn_exit.titleLabel?.text == "完成"{
            if viewModel.listenType.value == .story2{
 
                if isPop{
                    CommonAlertView.show(content: "未完成全部答题,确认退出吗?") {[weak self] () in
                        guard let weakSelf = self else { return }
                        for vc in weakSelf.navigationController?.viewControllers ?? []{
                            if vc.isKind(of: HomeListenVC.self){
                                weakSelf.navigationController?.popToViewController(vc, animated: true)
                                NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
                                break
                            }
                        }
                    }
                    return
                }
 
                guard (pageVC.currentController as! HomeListenStory_2_VC).isPlayEnd else {
                    alert(msg: "请听完");return
                }
 
                let v = data as! Listen1Model
                let accuracy = 100
                storyComplete(storyId: v.data!.id, accuracy: accuracy, studyTime: viewModel.times, type: viewModel.listenType.value == .story1 ? 1:2, integral: v.data!.integral)
            }
        }else if btn_exit.titleLabel?.text == "提交"{
 
            if isPop{
                CommonAlertView.show(content: "未完成全部答题,确认退出吗?") {[weak self] () in
                    guard let weakSelf = self else { return }
                    for vc in weakSelf.navigationController?.viewControllers ?? []{
                        if vc.isKind(of: HomeListenVC.self){
                            weakSelf.navigationController?.popToViewController(vc, animated: true)
                            NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
                            break
                        }
                    }
                }
                return
            }
 
            if viewModel.listenType.value == .game1 || viewModel.listenType.value == .game2{
                if let dict = notiObject{
                    gamesComplete(gameId: dict["gameId"] as! Int,integral: dict["gameIntegral"] as! Int)
                }
            }
        } else{
            CommonAlertView.show(content: "未完成全部答题,确认退出吗?") {[weak self] () in
                guard let weakSelf = self else { return }
 
                let temIds = [String]()
                let topicIds = [String]()
 
 
                switch weakSelf.viewModel.listenType.value{
                case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:
                    let totalNum = weakSelf.viewModel.correctNum + weakSelf.viewModel.errorNum
                    Services.exitLearning(type:weakSelf.viewModel.listenType.value.rawValue,quarter: weakSelf.viewModel.quarter.value!,week: weakSelf.viewModel.week.value!, day: weakSelf.viewModel.day.value!, teamIds: temIds, topicIds: topicIds,answerNumber: totalNum,correctNumber:weakSelf.viewModel.correctNum,studyTime:weakSelf.viewModel.times,schedule: weakSelf.maxPage).subscribe(onNext: { data in
 
                        NotificationCenter.default.post(name: MeUserInfoUpdate_Noti, object: nil)
 
                    }).disposed(by: weakSelf.disposeBag)
                case .game1,.game2,.story1,.story2:
                    Services.exitGameOrStory(studyTime: weakSelf.viewModel.times).subscribe(onNext: { _ in
 
                    }).disposed(by: weakSelf.disposeBag)
                }
                for vc in weakSelf.navigationController?.viewControllers ?? []{
                    if vc.isKind(of: HomeListenVC.self){
                        weakSelf.navigationController?.popToViewController(vc, animated: true)
                        NotificationCenter.default.post(name: Refresh_ListenSchedule_Noti, object: nil)
                        break
                    }
                }
            }
        }
    }
 
    @objc func beAgaionAction(){
        CommonAlertView.show(content: "是否重新开始答题?确认后将清空当前答题进度") {[unowned self] in
            let day = self.viewModel.day.value ?? 0
            let week = self.viewModel.week.value ?? 0
            let type = self.viewModel.listenType.value.rawValue
            Services.restart(day: day, type: type, week: week).subscribe(onNext: {[unowned self]_ in
                self.pageVC.scroll(toPage: 0, animation: true)
                if let m = (self.data as? ListenNewModel){
                    for v in m.list{
                        v.status = 1
                    }
                    self.restore()
                    self.setPages()
                    self.collection_card.reloadData()
                    NotificationCenter.default.post(name: ResetLession_Noti, object: nil)
                }
            }).disposed(by: disposeBag)
        }
    }
 
    @objc func nextAction(){
        listenFightLine = .next
        if viewModel.listenType.value == .story2{
 
            guard (pageVC.currentController as! HomeListenStory_2_VC).isPlayEnd else {
                alert(msg: "请听完");return
            }
 
            let v = data as! Listen1Model
            var dict = Dictionary<String,Any>()
            dict["storyId"] = v.data?.id ?? 0
            dict["storyIntegral"] = v.data?.lookIntegral ?? 0
            NotificationCenter.default.post(name: NextLession_Noti, object: data)
        }
    }
 
    @objc func beforeAction_mini(){
        if viewModel.listenType.value == .lesson1{
            if let vc = pageVC.currentController as? HomeListenFight_lesson_1_VC{
                print("---->进入")
                vc.tobefore()
            }
        }
    }
 
    @objc func beforeAction(){
        guard let currentPage = viewModel.currentPage.value else {return}
 
        listenFightLine = .before
        let beforePage = max(0, currentPage - 1)
        switch viewModel.listenType.value {
        case .lesson1:
            if !(pageVC.currentController as! HomeListenFight_lesson_1_VC).isListen{
                alert(msg: "请听完");return
            }
 
            let temp = viewModel.answerCount.value - 1
            viewModel.answerCount.accept(max(1,temp))
        case .lesson2:
            let temp = (beforePage * 4) + 1
            viewModel.answerCount.accept(max(1,temp))
        default:break
        }
 
 
        pageVC.scroll(toPage: beforePage, animation: true)
        viewModel.currentPage.accept(beforePage)
 
 
        if viewModel.listenType.value == .story2{
            guard (pageVC.currentController as! HomeListenStory_2_VC).isPlayEnd else {
                alert(msg: "请听完");return
            }
        }
 
        if viewModel.listenType.value == .lesson1{
            let currentVC = pageVC.currentController as! HomeListenFight_lesson_1_VC
            currentVC.tobefore();return
        }
 
        if viewModel.listenType.value == .lesson3{
            (pageVC.currentController as! HomeListenFight_lesson_3_VC).restore()
        }
 
        if viewModel.listenType.value == .story2{
            btn_next.isHidden = false
        }
 
        btn_exit.setTitle("退出", for: .normal)
    }
 
    private func restore(){
        if let vc = pageVC.currentController as? HomeListenFight_lesson_1_VC{
            vc.restore()
        }
        if let vc = pageVC.currentController as? HomeListenFight_lesson_2_VC{
            vc.restore()
        }
        if let vc = pageVC.currentController as? HomeListenFight_lesson_3_VC{
            vc.restore()
        }
        if let vc = pageVC.currentController as? HomeListenFight_lesson_4_VC{
            vc.restore()
        }
        if let vc = pageVC.currentController as? HomeListenFight_lesson_5_VC{
            vc.restore()
        }
 
        if let vc = pageVC.currentController as? HomeListenStory_1_VC{
            vc.restore()
        }
        if let vc = pageVC.currentController as? HomeListenStory_2_VC{
            vc.restore()
        }
    }
}
 
extension HomeListenFightVC:FFPageViewControllerDelegate{
    func totalPagesOfpageViewController(_ pageViewConteoller: FFPageViewController) -> UInt {
 
        switch viewModel.listenType.value {
        case .lesson1,.lesson2,.lesson3,.lesson4,.lesson5:return UInt((data as! ListenNewModel).subjectList.count)
        case .story1,.story2:
            return UInt((data as! Listen1Model).storyList.count)
        default:break
        }
 
 
        //超级听力,只有一页
        if viewModel.listenType.value == .game1 || viewModel.listenType.value == .game2{
            return 1
        }
        return UInt(viewModel.maxPage.value)
    }
 
    func pageViewController(_ pageViewController: FFPageViewController, currentPageChanged currentPage: Int) {
 
        viewModel.currentPage.accept(currentPage)
        if listenFightLine == .before{
            restore()
        }
    }
 
    func pageViewController(_ pageViewConteoller: FFPageViewController, controllerForPage page: Int) -> UIViewController {
        if viewModel.listenType.value == .lesson1{
            let vc = HomeListenFight_lesson_1_VC(page: page,listenNewModel:data as! ListenNewModel)
            vc.teamScheduleModel = teamScheduleModel
            vc.rootViewModel = viewModel
            vc.handleClouseAction {[unowned self] in
                self.setPages()
                self.collection_card.reloadData()
            }
            return vc
        }
 
        if viewModel.listenType.value == .lesson2{
            let vc = HomeListenFight_lesson_2_VC(page: page,listenNewModel:data as! ListenNewModel)
            vc.teamScheduleModel = teamScheduleModel
            vc.rootViewModel = viewModel
            vc.handleClouseAction {[unowned self] in
                self.setPages()
                self.collection_card.reloadData()
            }
            return vc
        }
 
        if viewModel.listenType.value == .lesson3{
            let vc = HomeListenFight_lesson_3_VC(page: page, listenNewModel: data as! ListenNewModel)
            vc.teamScheduleModel = teamScheduleModel
            vc.rootViewModel = viewModel
            vc.handleClouseAction {[unowned self] in
                self.setPages()
                self.collection_card.reloadData()
            }
            return vc
        }
 
        if viewModel.listenType.value == .lesson4{
            let vc = HomeListenFight_lesson_4_VC(page: page, listenNewModel: data as! ListenNewModel)
            vc.teamScheduleModel = teamScheduleModel
            vc.rootViewModel = viewModel
            vc.handleClouseAction {[unowned self] in
                self.setPages()
                self.collection_card.reloadData()
            }
            return vc
        }
 
        if viewModel.listenType.value == .lesson5{
            let vc = HomeListenFight_lesson_5_VC(page: page, listenNewModel: data as! ListenNewModel)
            vc.teamScheduleModel = teamScheduleModel
            vc.rootViewModel = viewModel
            vc.handleClouseAction {[unowned self] in
                self.setPages()
                self.collection_card.reloadData()
            }
            return vc
        }
 
        if viewModel.listenType.value == .game1{
            if data == nil{return UIViewController()}
            let vc = HomeListenGame_1_VC(listen1Model: data as! Listen1Model)
            vc.rootViewModel = viewModel
            return vc
        }
 
        if viewModel.listenType.value == .game2{
            let vc = HomeListenGame_2_VC(listen1Model: data as! Listen1Model)
            vc.rootViewModel = viewModel
            return vc
        }
 
        if viewModel.listenType.value == .story1{
            let vc = HomeListenStory_1_VC(page: page, listen1Model: data as! Listen1Model)
            vc.rootViewModel = viewModel
            return vc
        }
 
        if viewModel.listenType.value == .story2{
            let vc = HomeListenStory_2_VC(page: page, listen1Model: data as! Listen1Model)
            vc.rootViewModel = viewModel
            return vc
        }
 
        let vc = UIViewController()
        return vc
    }
}
 
extension HomeListenFightVC:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard pageVC.currentPage != indexPath.row else {return}
        if let m = data as? ListenNewModel{
            if viewModel.listenType.value == .lesson1{
                guard pages[indexPath.row].filter({$0.status == 2}).count == 4 else {return}
            }else{
                guard m.list[indexPath.row].status != 1 else{return}
            }
 
            pageVC.scroll(toPage: indexPath.row, animation: true)
        }
    }
}
 
extension HomeListenFightVC:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if data is ListenNewModel{
            if viewModel.listenType.value == .lesson1{
                return (data as! ListenNewModel).subjectList.count
            }
 
            if viewModel.listenType.value == .lesson2{
                return (data as! ListenNewModel).subjectList.count
            }
 
            return pages.count
        }
        return 0
    }
 
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_CardItemCCell", for: indexPath) as! CardItemCCell
        if data is ListenNewModel{
            let model = pages[indexPath.row]
            cell.titleL.text = "\(indexPath.row + 1)"
 
            if viewModel.listenType.value == .lesson1{
                if model.filter({$0.status == 2}).count == 4{
                    cell.titleL.textColor = UIColor(hexString: "#52C41A")
                    cell.titleL.jq_borderColor = UIColor(hexString: "#52C41A")
                }else if model.filter({$0.status == 3}).count >= 1 {
                    cell.titleL.textColor = UIColor(hexString: "#FF4D4F")
                    cell.titleL.jq_borderColor = UIColor(hexString: "#52C41A")
                }else{
                    cell.titleL.textColor = .black.withAlphaComponent(0.25)
                    cell.titleL.jq_borderColor = .black.withAlphaComponent(0.25)
                }
            }else{
                //状态1灰色未答题 2绿色正确 3红色错误
                switch model.first!.status{
                case 1:
                    cell.titleL.textColor = .black.withAlphaComponent(0.25)
                    cell.titleL.jq_borderColor = .black.withAlphaComponent(0.25)
                case 2:
                    cell.titleL.textColor = UIColor(hexString: "#52C41A")
                    cell.titleL.jq_borderColor = UIColor(hexString: "#52C41A")
                case 3:
                    cell.titleL.textColor = UIColor(hexString: "#FF4D4F")
                    cell.titleL.jq_borderColor = UIColor(hexString: "#52C41A")
                default:break
                }
            }
        }
        return cell
    }
}
 
class CardItemCCell:UICollectionViewCell{
 
    var titleL:UILabel!
 
    override init(frame: CGRect) {
        super.init(frame: frame)
 
        titleL = UILabel()
        titleL.text = "1"
        titleL.backgroundColor = .white
        titleL.jq_borderColor = .black.withAlphaComponent(0.15)
        titleL.jq_borderWidth = 0.5
        titleL.font = .systemFont(ofSize: 13,weight: .semibold)
        titleL.textAlignment = .center
        contentView.addSubview(titleL)
        titleL.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}