无故事王国
5 天以前 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
//
//  HomeListenFight_lesson_4_VC.swift
//  DolphinEnglishLearnStudent
//
//  Created by 无故事王国 on 2024/5/28.
//
 
import UIKit
import JQTools
 
class HomeListenFight_lesson_4_VC: BaseVC {
    
    private var viewModel = FightAnswerViewModel()
    private var listenNewModel:ListenNewModel!
    private var page:Int!
    var rootViewModel:HomeListenFightViewModel!
    var teamScheduleModel:TeamScheduleModel?
    
    private var answerIndex:IndexPath? //答案的Index
    private var playingIndex:IndexPath?
    private var answerIndexs = Set<IndexPath>() //回答过的Index集合
    private var filterItems = [[Listen1SubModel]]() //此类型特殊,需要数据清理
    private var handleClouse:(()->Void)?
    
    private lazy var stackView:UIStackView = {
        let sta = UIStackView()
        sta.spacing = 41
        sta.distribution = .equalSpacing
        sta.axis = .vertical
        return sta
    }()
    
    private lazy var collectionView:UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let w = (JQ_ScreenW - 164 * 2 - 62) / 2.0
        flowLayout.minimumLineSpacing = 20
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.itemSize = CGSize(width: w, height: w * 0.702)
        flowLayout.scrollDirection = .vertical
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.contentInset = UIEdgeInsets(top: 33, left: 0, bottom: 0, right: 0)
        collection.register(UINib(nibName: "ListenFight_lesson_4_CCell", bundle: nil), forCellWithReuseIdentifier: "_ListenFight_lesson_4_CCell")
        collection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        collection.isScrollEnabled = false
        return collection
    }()
    
    private var voicePlayer = VoicePlayer.share()
    
    required init(page:Int,listenNewModel:ListenNewModel){
        super.init(nibName: nil, bundle: nil)
        self.page = page
        self.listenNewModel = listenNewModel
        let temp1 = Array(listenNewModel.subjectList[page][0...1])
        let temp2 = Array(listenNewModel.subjectList[page][2...3])
        
        filterItems.append(temp1)
        filterItems.append(temp2)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func restore(){
        answerIndexs.removeAll()
        answerIndex = nil
        for subView in view.subviews{
            if subView is Lesson_4_AnswerView{
                subView.removeFromSuperview()
            }
        }
        
        setUI()
        collectionView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        playingIndex = IndexPath(row: 0, section: 0)
        //回传记录,始终保持答题进度
        if let team = teamScheduleModel{
            for teamId in team.teamIds{
                for v in listenNewModel.subjectList[page]{
                    if team.topicIds.contains(v.id){
                        rootViewModel.insertCorrectAnswer(teamId: "\(teamId)", answerId: v.id)
                    }
                }
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            var index:IndexPath!
            if self.filterItems[0][0].isQuestion == 1{
                index = IndexPath(row: 0, section: 0)
            }else{
                index = IndexPath(row: 1, section: 0)
            }
            
            let m = self.filterItems[index.section][index.row]
            self.viewModel.selectIndex.accept(index)
            UIView.animate(withDuration: 0.5) {
                self.collectionView.snp.remakeConstraints { make in
                    make.left.equalTo(76)
                    make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(0)
                    make.width.equalTo(JQ_ScreenW - 164 * 2)
                    make.bottom.equalToSuperview()
                }
                self.view.layoutIfNeeded()
            }completion: { _ in
                self.setAnswerStackView()
                self.voicePlayer.playerAt(url: m.correct)
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        voicePlayer.delegate = self
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        voicePlayer.delegate = nil
        VoicePlayer.share().playerInterrupt()
    }
    
    
    override func setUI() {
        super.setUI()
        
        if !view.subviews.contains(collectionView){
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.showsVerticalScrollIndicator = false
            collectionView.backgroundColor = .clear
            view.addSubview(collectionView)
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(0)
            make.left.equalTo(164)
            make.width.equalTo(JQ_ScreenW - 164 * 2)
            make.bottom.equalToSuperview()
        }
    }
    
    override func setRx() {
        NotificationCenter.default.rx.notification(ResetLession_Noti).take(until: self.rx.deallocated).subscribe(onNext: {[weak self]_ in
            self?.restore()
            self?.viewDidLoad()
        }).disposed(by: disposeBag)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.minimumLineSpacing = 20
        flowLayout.minimumInteritemSpacing = 20
        
        let w = (collectionView.size.width - flowLayout.minimumLineSpacing) / 2
        let h = (collectionView.size.height - flowLayout.minimumInteritemSpacing) / 2.1
        
        if flowLayout.itemSize.width != w || flowLayout.itemSize.height != h{
            flowLayout.itemSize = CGSize(width: w, height: h - 20)
            collectionView.reloadData()
        }
    }
    
    private func setAnswerStackView(){
        
        guard let selectIndex = viewModel.selectIndex.value else{
            alertError(msg: "请先听题");return
        }
        
        for v in stackView.subviews{
            v.removeFromSuperview()
        }
        
        if !view.subviews.contains(stackView){
            view.addSubview(stackView)
            stackView.snp.makeConstraints { make in
                make.right.equalToSuperview().offset(-14)
                make.centerY.equalToSuperview()
            }
        }
        
        let answerModel = filterItems[selectIndex.section].filter({$0.isQuestion == 0}).first!
        let answerId = answerModel.id
        
        var tempVoiceArray = [String]()
        for v in filterItems[selectIndex.section]{
            if v.id == answerId{
                tempVoiceArray.append(v.correct)
                tempVoiceArray.append(v.error.components(separatedBy: ",").first ?? "")
                tempVoiceArray.append(v.error.components(separatedBy: ",").last ?? "")
            }
        }
        
        tempVoiceArray.shuffle()
        
        
        for i in 0...2{
            let answerView = Lesson_4_AnswerView.jq_loadNibView()
            answerView.btn_choose.tag = 10 + i
            answerView.tag = 20 + i
            answerView.voiceUrl = tempVoiceArray[i]
            answerView.btn_isAnswer.setImage(viewModel.selectIndex.value?.row == 1 ? UIImage(named: "icon_question"):UIImage(named: "icon_answer"), for: .normal)
            answerView.btn_choose.addTarget(self, action: #selector(answerAction), for: .touchUpInside)
            answerView.alpha = 0
            answerView.snp.makeConstraints { make in
                make.width.equalTo(221)
                make.height.equalTo(52)
            }
            answerView.btn_choose.isEnabled = false
            answerView.playAt { index in
                answerView.btn_choose.isEnabled = true
            }
            
            //            UIView.animate(withDuration: 0.05 + Double(i)) {
            answerView.alpha = 1
            //            }
            
            stackView.insertArrangedSubview(answerView, at: 0)
        }
    }
    
    func handleClouseAction(clouse:@escaping ()->Void){
        self.handleClouse = clouse
    }
    
    @objc func answerAction(btn:UIButton){
        
        var islistenDone:Int = 0
        for v in stackView.arrangedSubviews as! [Lesson_4_AnswerView]{
            if v.btn_choose.isEnabled == true{
                islistenDone += 1
            }
        }
        
        if islistenDone != 3{
            alertError(msg: "请先听完");return
        }
        
        guard let selectIndex = viewModel.selectIndex.value else{
            alertError(msg: "请先听题");return
        }
        
        var tempSubV:Lesson_4_AnswerView?
        
        for subV in stackView.arrangedSubviews{
            if let s = subV as? Lesson_4_AnswerView{
                s.btn_choose.isSelected = btn.tag == s.btn_choose.tag
                if s.btn_choose.isSelected{tempSubV = s}
            }
        }
        
        var answerModel:Listen1SubModel?
        for (index,v) in filterItems[selectIndex.section].enumerated(){
            let m = filterItems[selectIndex.section].filter({$0.isQuestion == 0}).first
            if v.id == m?.id{
                answerModel = v
                answerIndex = IndexPath(row: index, section: viewModel.selectIndex.value!.section)
            }
        }
        
        var answerType:Fight_lessonType = .none
        if tempSubV?.voiceUrl == answerModel?.correct{
            answerType = .success
            voicePlayer.playSuccessVoice()
            
            
            let model = listenNewModel.list[self.page]
            model.status = 2
            Services.answerQuestion(id: model.id, status: 2).subscribe(onNext: {_ in
                self.handleClouse?()
            }).disposed(by: self.disposeBag)
            
            
            var teamId:String = ""
            var answerId:Int = 0
            if self.viewModel.selectIndex.value?.section == 1{
                teamId = self.listenNewModel.data?.id.components(separatedBy: ",")[self.page + 1] ?? ""
                answerId = answerModel!.id
            }else{
                teamId = self.listenNewModel.data?.id.components(separatedBy: ",")[self.page] ?? ""
                answerId = answerModel!.id
            }
            
            self.rootViewModel.insertCorrectAnswer(teamId: teamId, answerId: answerId)
            
            DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                self.voicePlayer.playerAt(url: tempSubV!.voiceUrl)
            }
            
            //防止重复答题造成计数错误的问题
            if !answerIndexs.contains(answerIndex!){
                rootViewModel.correctNum += 1
                let v = rootViewModel.answerCount.value + 1
                rootViewModel.answerCount.accept(v)
            }
            
            //正确才记录回答
            answerIndexs.insert(answerIndex!)
            
        }else{
            answerType = .fail
            voicePlayer.playFailVoice()
            rootViewModel.errorNum += 1
            
            let model = listenNewModel.list[self.page]
            model.status = 3
            Services.answerQuestion(id: model.id, status: 3).subscribe(onNext: {_ in
                self.handleClouse?()
            }).disposed(by: self.disposeBag)
        }
        voicePlayer.playerEnd()
        
        switch answerType {
        case .success:
            DispatchQueue.main.asyncAfter(deadline: .now()+0.4) {
                if let copyView = tempSubV?.copyView(){
                    tempSubV?.alpha = 0
                    let newRect = tempSubV!.view_handle.convert(tempSubV!.bounds, to: self.view)
                    copyView.frame = CGRect(origin: newRect.origin, size: CGSize(width: 159, height: 40))
                    copyView.view_state.isHidden = true
                    copyView.isCopy = true
                    copyView.isPlaying()
                    copyView.btn_isAnswer.setImage(self.viewModel.selectIndex.value?.row == 1 ? UIImage(named: "icon_question"):UIImage(named: "icon_answer"), for: .normal)
                    copyView.img_play.alpha = 1
                    copyView.voiceUrl = tempSubV!.voiceUrl
                    self.view.addSubview(copyView)
                    self.view.layoutIfNeeded()
                    
                    //获取Cell的顶部试图
                    if let cell = self.collectionView.cellForItem(at: self.answerIndex!) as? ListenFight_lesson_4_CCell{
                        var newRect1 = cell.convert(cell.bounds, to: self.collectionView)
                        newRect1.origin.x += 76
                        newRect1.origin.y += 33
                        
                        self.collectionView.reloadData()
                        UIView.animate(withDuration: 0.4) {
                            copyView.frame = CGRect(origin: newRect1.origin, size: CGSize(width: newRect1.width, height: 40))
                        } completion: { _ in
                           let nextIndex = IndexPath(row: 0, section: 1)
                            if self.viewModel.selectIndex.value != nextIndex{
                                self.viewModel.selectIndex.accept(nextIndex)
                                let m = self.filterItems[nextIndex.section][nextIndex.row]
                                self.voicePlayer.playerAt(url: m.correct)
                                self.collectionView.reloadData()
 
                                for v in self.stackView.subviews{
                                    v.removeFromSuperview()
                                }
 
                                self.setAnswerStackView()
                                self.stackView.layoutIfNeeded()
                            }
                        }
                    }
                }
            }
            
        case .fail:
            self.view.isUserInteractionEnabled = false
            UIView.animate(withDuration: 0.4) {
                tempSubV?.img_state.alpha = 1
            }completion: { _ in
                
                UIView.animate(withDuration: 0.4, delay: 2.0) {
                    tempSubV?.img_state.alpha = 0
                }
                
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.setAnswerStackView()
                    self.view.isUserInteractionEnabled = true
                }
            }
        case .none:
            break
        }
    }
}
 
extension HomeListenFight_lesson_4_VC:UICollectionViewDelegate{
    
}
 
extension HomeListenFight_lesson_4_VC:UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSizeMake(JQ_ScreenW, 20)
    }
}
 
extension HomeListenFight_lesson_4_VC:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_ListenFight_lesson_4_CCell", for: indexPath) as! ListenFight_lesson_4_CCell
        cell.backgroundColor = .white
        cell.contentView.backgroundColor = .white
        cell.indexPath = indexPath
 
        if playingIndex == indexPath{
            cell.playing()
        }else{
            cell.playEnd()
        }
 
        cell.playAtIndex {[weak self] index in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.selectIndex.accept(index)
            UIView.animate(withDuration: 0.5) {
                weakSelf.collectionView.snp.remakeConstraints { make in
                    make.left.equalTo(76)
                    make.top.equalTo(weakSelf.view.safeAreaLayoutGuide.snp.top).offset(0)
                    make.width.equalTo(JQ_ScreenW - 164 * 2)
                    make.bottom.equalToSuperview()
                }
                weakSelf.view.layoutIfNeeded()
            }completion: { _ in
                weakSelf.setAnswerStackView()
            }
        }
        let m = filterItems[indexPath.section][indexPath.row]
        if indexPath == answerIndex{
            UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4,options: .layoutSubviews) {
                cell.img_state.alpha = 1
                cell.img_state.transform = .init(scaleX: 1.0, y: 1.0)
            }
            UIView.animate(withDuration: 0.4, delay: 3.0) {
                cell.img_state.alpha = 0
                cell.img_state.transform = .init(scaleX: 0.1, y: 0.1)
            }
        }else{
            cell.img_state.alpha = 0
            cell.img_state.transform = .init(scaleX: 0.1, y: 0.1)
        }
        
        if indexPath.row == 1{
            cell.btn_handle.setImage(UIImage(named: "icon_answer"), for: .normal)
            cell.view_handle.isHidden = true
        }else{
            cell.btn_handle.setImage(UIImage(named: "icon_question"), for: .normal)
            cell.view_handle.isHidden = true
        }
        
        //问题
        if filterItems[indexPath.section][indexPath.row].isQuestion == 0{
            cell.view_handle.isHidden = true
        }else{
            cell.view_handle.isHidden = false
        }
        cell.setModel(m)
        
        
        if answerIndexs.count == 0 && indexPath.section == 1{
            cell.view_handle.backgroundColor = UIColor(hexString: "#D4D2CD")
            cell.view_handle.isEnabled = false
        }else{
            cell.view_handle.backgroundColor = .white
            cell.view_handle.isEnabled = true
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
        return reusableView
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return filterItems[section].count
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return filterItems.count
    }
}
 
extension HomeListenFight_lesson_4_VC:VoicePlayerDelegate{
    func playComplete() {
        playingIndex = nil
        self.view.isUserInteractionEnabled = true
        
        for subV in view.subviews {
            if let s = subV as? Lesson_4_AnswerView{
                s.playEnd()
                s.img_play.isHidden = false
                s.img_play.alpha = 1
            }
        }
        
        
        let temp = stackView.subviews as! [Lesson_4_AnswerView]
        for subV in temp.reversed() {
            if subV.isplayend == false{
                voicePlayer.playerAt(url: subV.voiceUrl ?? "")
                subV.isPlaying()
                subV.btn_choose.isEnabled = true
                break
            }else{
                subV.playEnd()
            }
        }
        
        if let indexPath = viewModel.selectIndex.value ,let cell = collectionView.cellForItem(at: indexPath) as? ListenFight_lesson_4_CCell{
            cell.playEnd()
        }
        
        //回答完成,下一答题
        if answerIndexs.count == 2{
            voicePlayer.playerEnd()
            NotificationCenter.default.post(name: NextLession_Noti, object: nil)
            return
        }
    }
    
    func playing() {
        self.view.isUserInteractionEnabled = false
    }
}