无故事王国
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//
//  HomeListenFight_lesson_3_VC.swift
//  DolphinEnglishLearnStudent
//
//  Created by 无故事王国 on 2024/5/27.
//
 
import UIKit
import Lantern
 
class HomeListenFight_lesson_3_VC: BaseVC {
 
    private var viewModel = FightAnswerViewModel()
 
    private lazy var collectionView:UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let w = (JQ_ScreenW - 97 - 54 - 36) / 3.0
        flowLayout.itemSize = CGSize(width: w, height: w * 0.947)
        flowLayout.minimumInteritemSpacing = 18
        flowLayout.scrollDirection = .vertical
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.register(UINib(nibName: "ListenFight_lesson_3_CCell", bundle: nil), forCellWithReuseIdentifier: "_ListenFight_lesson_3_CCell")
        collection.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        collection.isScrollEnabled = false
        return collection
    }()
 
    private lazy var stackView:UIStackView = {
        let sta = UIStackView()
        sta.spacing = 5
        sta.distribution = .equalSpacing
        sta.axis = .horizontal
        return sta
    }()
 
    private var listenNewModel:ListenNewModel!
    private var page:Int!
    private var answterCount:Int = 0 //回答计数,用于确定角标
    var rootViewModel:HomeListenFightViewModel!
    var teamScheduleModel:TeamScheduleModel?
    private var voicePlayer = VoicePlayer.share()
    private var playIndex = Set<IndexPath>() //顺序播放
 
    private var isPlayingIndex:IndexPath? //正在播放中
    private var islisten:Bool = false
    private var handleClouse:(()->Void)?
 
    required init(page:Int,listenNewModel:ListenNewModel){
        super.init(nibName: nil, bundle: nil)
        self.page = page
        self.listenNewModel = listenNewModel
    }
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    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 viewDidLoad() {
        super.viewDidLoad()
        navigationItem.titleView = UIView()
        playIndex.insert(IndexPath(row: 0, section: 0))
        listenNewModel.subjectList[page][0].isQuestion = 1
        listenNewModel.subjectList[page][1].isQuestion = 1
        listenNewModel.subjectList[page][3].isQuestion = 1
 
 
        rootViewModel.currentPage.subscribe(onNext: {[unowned self] cpage in
            if cpage == self.page{
                DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                    self.restore()
                    self.isPlayingIndex = IndexPath(row: 0, section: 0)
                    self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][0].correct)
                }
            }
        }).disposed(by: disposeBag)
 
 
        //回传记录,始终保持答题进度
        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)
                    }
                }
            }
        }
    }
 
    func restore(){
        listenNewModel.subjectList.forEach { list in
            list.forEach { sub in
                sub.isAnster = false
            }
        }
        isPlayingIndex = nil
        playIndex.removeAll()
        playIndex.insert(IndexPath(row: 0, section: 0))
        answterCount = 0
        for subView in view.subviews{
            if subView is Lesson_3_AnswerView{
                subView.removeFromSuperview()
            }
        }
        setUI()
        collectionView.reloadData()
 
    }
 
    override func setUI() {
        super.setUI()
        if !view.subviews.contains(collectionView){
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.showsVerticalScrollIndicator = false
            collectionView.contentInset = UIEdgeInsets(top: 33, left: 0, bottom: 0, right: 0)
            collectionView.backgroundColor = .clear
            view.addSubview(collectionView)
        }
 
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(0)
            make.left.equalTo(97)
            make.right.equalTo(-54)
            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
 
        let w = (collectionView.size.width - flowLayout.minimumLineSpacing) / 3.1
        let h = (collectionView.size.height - flowLayout.minimumInteritemSpacing) / 2 - 40
        if flowLayout.itemSize.width != w || flowLayout.itemSize.height != h{
            flowLayout.itemSize = CGSize(width: w, height: h)
            collectionView.reloadData()
        }
    }
 
    private func setAnswerStackView(force:Bool = false){
 
 
        for v in stackView.arrangedSubviews{
            v.removeFromSuperview()
        }
 
        var tempImageArray = [String]()
        tempImageArray.append(listenNewModel.subjectList[page][2].img)
        tempImageArray.append(listenNewModel.subjectList[page][4].img)
        tempImageArray.append(listenNewModel.subjectList[page][5].img)
 
        view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-82)
            make.centerY.equalToSuperview().offset(10)
            make.height.equalTo(52)
        }
 
        var tempAnswerViews = [Lesson_3_AnswerView]()
        for i in 0...2{
            let answerView = Lesson_3_AnswerView.jq_loadNibView()
            answerView.alpha = 0
            answerView.btn_choose.addTarget(self, action: #selector(chooseAnswerAction), for: .touchUpInside)
            answerView.btn_fullscreen.addTarget(self, action: #selector(fullscreenAction), for: .touchUpInside)
            answerView.img_cover.contentMode = .scaleToFill
            answerView.btn_choose.tag = 10+i
            answerView.btn_fullscreen.tag = 20+i
            answerView.imageUrl = tempImageArray[i]
            answerView.img_cover.sd_setImage(with: URL(string: tempImageArray[i]))
            answerView.snp.makeConstraints { make in
                make.width.equalTo(85)
                make.height.equalTo(52)
            }
 
            //            UIView.animate(withDuration: 0.05 + Double(i)) {
            answerView.alpha = 1
            //            }
            tempAnswerViews.append(answerView)
        }
        tempAnswerViews.shuffle()
        stackView.addArrangedSubviews(tempAnswerViews)
    }
 
    func handleClouseAction(clouse:@escaping ()->Void){
        self.handleClouse = clouse
    }
 
    @objc private func chooseAnswerAction(btn:UIButton){
 
        var subV:Lesson_3_AnswerView?
 
        for (_,v) in (stackView.arrangedSubviews as! [Lesson_3_AnswerView]).enumerated(){
            if v.btn_choose.tag == btn.tag{
                subV = v;break
            }
        }
 
        var answerType:Fight_lessonType = .none
 
        var valueIndex:Int! //图片的角标
        if answterCount == 0{
            valueIndex = 2
        }else if answterCount == 1{
            valueIndex = 4
        }else if answterCount == 2{
            valueIndex = 5
        }
 
        if subV?.imageUrl == listenNewModel.subjectList[page][valueIndex].img{
            answterCount += 1
            listenNewModel.subjectList[page][valueIndex].isAnster = true
            answerType = .success
            subV?.alpha = 0
            voicePlayer.playSuccessVoice()
 
 
            switch answterCount{
            case 1:isPlayingIndex = IndexPath(row: 2, section: 0)
            case 2:isPlayingIndex = IndexPath(row: 1, section: 1)
            case 3:isPlayingIndex = IndexPath(row: 2, section: 1)
            default:break
            }
            let index = self.isPlayingIndex!.section * 3 + self.isPlayingIndex!.row
 
            let model = listenNewModel.list[index]
            model.status = 2
            Services.answerQuestion(id: model.id, status: 2).subscribe(onNext: {_ in
                self.handleClouse?()
            }).disposed(by: self.disposeBag)
 
        }else{
            answerType = .fail
            voicePlayer.playFailVoice()
 
            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)
        }
 
        switch answerType {
        case .success:
            rootViewModel.correctNum += 1
            viewModel.answerType.accept(.success)
            let copyViewFrame = subV?.convert(subV!.bounds, to: self.view)
            let copyView = subV?.copyView()
            copyView?.frame = copyViewFrame!
            copyView?.img_cover.contentMode = .scaleToFill
            copyView?.img_cover.image = subV?.img_cover.image
            self.view.addSubview(copyView!)
            copyView?.layoutIfNeeded()
 
            if let cell = collectionView.cellForItem(at: isPlayingIndex!) as? ListenFight_lesson_3_CCell{
                var newFrame = cell.img_cover.convert(cell.img_cover.bounds, to: self.view)
                newFrame.origin.x += 0
                newFrame.origin.y += 0
 
                let successImage = UIImageView(image: UIImage(named: "icon_success"))
                successImage.bounds = CGRect(x: 0, y: 0, width: 75, height: 75)
                successImage.center = newFrame.center
                successImage.transform = .init(scaleX: 0.1, y: 0.1)
                successImage.alpha = 0
                successImage.layoutIfNeeded()
                self.view.addSubview(successImage)
                UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4) {
                    successImage.transform = .init(scaleX: 1.0, y: 1.0)
                    successImage.alpha = 1
                }
 
                UIView.animate(withDuration: 0.5, delay: 3) {
                    successImage.transform = .init(scaleX: 0.1, y: 0.1)
                    successImage.alpha = 0
                }completion: { _ in
                    successImage.removeFromSuperview()
                }
 
                UIView.animate(withDuration: 0.4) {
                    copyView?.frame = newFrame
                } completion: { _ in
                    let cell = self.collectionView.cellForItem(at: IndexPath(row: 0, section: 1)) as! ListenFight_lesson_3_CCell
 
                    self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][valueIndex].correct)
                    cell.isPlaying(isplaying: true)
 
                    let teamId = self.listenNewModel.data?.id.components(separatedBy: ",")[self.page]
                    let answerId = self.listenNewModel.subjectList[self.page][valueIndex].id
                    self.rootViewModel.insertCorrectAnswer(teamId: teamId, answerId: answerId)
 
                    for v in self.stackView.arrangedSubviews{
                        v.removeFromSuperview()
                    }
 
                    let v = self.rootViewModel.answerCount.value + 1
                    self.rootViewModel.answerCount.accept(v)
                }
            }
 
        case .fail:
            rootViewModel.errorNum += 1
            viewModel.answerType.accept(.fail)
            UIView.animate(withDuration: 0.4) {
                subV?.img_state.alpha = 1
                subV?.btn_fullscreen.alpha = 0
            }completion: { _ in
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.islisten  = false
                    for v in self.stackView.arrangedSubviews{
                        v.removeFromSuperview()
                    }
                }
            }
        default:break
        }
    }
 
    @objc private func fullscreenAction(btn:UIButton){
 
        var answerView:Lesson_3_AnswerView!
        for (_,v) in (stackView.arrangedSubviews as! [Lesson_3_AnswerView]).enumerated(){
            if v.btn_fullscreen.tag == btn.tag{
                answerView = v;break
            }
        }
 
 
        let lantern = Lantern()
        lantern.numberOfItems = { () in
            return 1
        }
 
        lantern.cellClassAtIndex = { _ in
            LanternImageCell.self
        }
 
 
        lantern.transitionAnimator = LanternZoomAnimator(previousView: { index -> UIView? in
            return answerView.img_cover
        })
 
 
        // UIPageIndicator样式的页码指示器
        lantern.pageIndicator = LanternDefaultPageIndicator()
 
        lantern.pageIndex = 0
 
        lantern.reloadCellAtIndex = { context in
            let lanternCell = context.cell as? LanternImageCell
            lanternCell?.imageView.image = answerView.img_cover.image
        }
        //不要使用push
        lantern.show()
    }
}
 
extension HomeListenFight_lesson_3_VC:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 
    }
}
 
extension HomeListenFight_lesson_3_VC:UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0{
            return CGSize.zero
        }
        return CGSizeMake(JQ_ScreenW, 65)
    }
}
 
extension HomeListenFight_lesson_3_VC:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "_ListenFight_lesson_3_CCell", for: indexPath) as! ListenFight_lesson_3_CCell
        cell.indexPath = indexPath
        cell.canClick(playIndex.contains(indexPath))
        cell.palyVoiceAt {[weak self] index in
            guard let weakSelf = self else { return }
 
            weakSelf.isPlayingIndex = index
            weakSelf.viewModel.selectIndex.accept(index)
 
            weakSelf.voicePlayer.playerEnd()
 
            if indexPath.section == 1{
                weakSelf.voicePlayer.playerAt(url:  weakSelf.listenNewModel.subjectList[weakSelf.page][indexPath.row + 3].correct)
            }else{
                weakSelf.voicePlayer.playerAt(url:  weakSelf.listenNewModel.subjectList[weakSelf.page][indexPath.row].correct)
            }
 
 
            if index == IndexPath(row: 2, section: 0) || index == IndexPath(row: 1, section: 1) || index == IndexPath(row: 2, section: 1){
 
                var model:Listen1SubModel?
                if indexPath.section == 0{
                    model = weakSelf.listenNewModel.subjectList[weakSelf.page][indexPath.row]
                }
 
                if indexPath.section == 1{
                    model = weakSelf.listenNewModel.subjectList[weakSelf.page][indexPath.row + 3]
                }
 
                if model?.isAnster == false{
                    //点击答案,就显示
                    weakSelf.setAnswerStackView()
                }
            }
 
            collectionView.reloadItems(at: [index])
        }
 
        if indexPath.section == 0{
            let model = listenNewModel.subjectList[page][indexPath.row]
            if indexPath.row != 2{
                cell.img_cover.sd_setImage(with: URL(string: model.img))
            }else{
                cell.img_cover.image = nil
            }
            cell.setModel(model,isplaying: isPlayingIndex == indexPath)
        }
 
        if indexPath.section == 1{
            let model = listenNewModel.subjectList[page][indexPath.row + 3]
            if indexPath.row == 0{
                cell.img_cover.sd_setImage(with: URL(string: model.img))
            }else{
                cell.img_cover.image = nil
            }
            cell.setModel(model,isplaying: isPlayingIndex == indexPath)
        }
        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 3
    }
 
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
}
 
extension HomeListenFight_lesson_3_VC:VoicePlayerDelegate{
 
    func playComplete() {
        view.isUserInteractionEnabled = true
        islisten  = true
 
        //1
        if isPlayingIndex?.section == 0 && isPlayingIndex?.row == 0{
            isPlayingIndex?.row += 1
            let index = isPlayingIndex!.row
            self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][index].correct)
            playIndex.insert(isPlayingIndex!)
            collectionView.reloadData()
            return
        }
 
        //2
        if isPlayingIndex?.section == 0 && isPlayingIndex?.row == 1{
            isPlayingIndex?.row += 1
            let index = isPlayingIndex!.row
            self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][index].correct)
            playIndex.insert(isPlayingIndex!)
            collectionView.reloadData()
            self.setAnswerStackView()
            return
        }
 
        //3
        if isPlayingIndex?.section == 0 && isPlayingIndex?.row == 2{
            let index = isPlayingIndex!.row
            if self.listenNewModel.subjectList[self.page][index].isAnster{
                isPlayingIndex?.row = 0
                isPlayingIndex?.section += 1
                let index = isPlayingIndex!.section * 3 + isPlayingIndex!.row
                self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][index].correct)
                playIndex.insert(isPlayingIndex!)
                collectionView.reloadData()
            }
 
            return
        }
 
 
        if isPlayingIndex?.section == 1 && isPlayingIndex?.row == 0{
            let index = isPlayingIndex!.section * 3 + isPlayingIndex!.row
            self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][index].correct)
            isPlayingIndex?.row += 1
            playIndex.insert(isPlayingIndex!)
            collectionView.reloadData()
            return
        }
 
        if isPlayingIndex?.section == 1 && isPlayingIndex?.row == 1{
            let index = isPlayingIndex!.section * 3 + isPlayingIndex!.row
            if self.listenNewModel.subjectList[self.page][index].isAnster{
                isPlayingIndex?.row += 1
                let index = isPlayingIndex!.section * 3 + isPlayingIndex!.row
                self.voicePlayer.playerAt(url: self.listenNewModel.subjectList[self.page][index].correct)
                playIndex.insert(isPlayingIndex!)
                collectionView.reloadData()
                return
            }
            self.setAnswerStackView()
        }
 
        if isPlayingIndex?.section == 1 && isPlayingIndex?.row == 2{
            let index = isPlayingIndex!.section * 3 + isPlayingIndex!.row
            if self.listenNewModel.subjectList[self.page][index].isAnster{
                //答完了
                NotificationCenter.default.post(name: NextLession_Noti, object: nil)
                return
            }
            self.setAnswerStackView()
        }
    }
 
    func playing() {
        islisten = false
        view.isUserInteractionEnabled = false
    }
}