闫增涛
2024-03-18 b929e9d487632580cc28ac7b8bf9494f25ca8ca3
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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
import { getPublicImage } from '../../../../assets/js/middleGround/tool'
const app = getApp()
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    barHeight: "",
    navBarHeight: "",
    loading: false,
    answerTitle: "",  // 导航栏标题
    countdownInterval: null,   // 计时器
    isCountdownRunning: true, // 是否倒计时
    countdownTime: 0,  // 倒计时时间
    bookId: "",
    productLinkPath: "",
    rootCmsItemId: "",
    idPathList: [],  // 题目列表
    answerType: "",  // 答题模式
    submitStatus: false,  // 提交状态
    currentIndex: 0, // 当前显示的题号
    collectList: [],   //  收藏题目列表 
    errorList: [],  // 错题列表
    subjectiveTotal: 0,  // 客观题总数
    subjectiveNum: 0, // 客观题得分
    subjectiveGrade: 0, // 客观题总分
    correctNum: 0,  // 正确题目数量
    total: 0,   // 题目总数
    cardList: [],  // 提交项,
    questionDataList: [],  // 显示题目列表
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const systInfo = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect(); // 胶囊信息
    const navBarHeight = (menu.top - systInfo.statusBarHeight) * 2 + menu.height; // 导航栏高度
    this.setData({
      barHeight: systInfo.statusBarHeight,
      navBarHeight: navBarHeight,
      answerTitle: options.answerTitle,
      bookId: options.bookId,
      productLinkPath: options.productLinkPath ? options.productLinkPath : '',
      rootCmsItemId: options.rootCmsItemId,
      idPathList: options.idPathList ? JSON.parse(options.idPathList) : [],
      answerType: options.answerType
    });
    this.init()
    console.log('传参', options);
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
 
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
 
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
 
  },
 
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.countdownInterval !== null) {
      clearInterval(this.data.countdownInterval)
    }
  },
 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
 
  },
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
 
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  // 返回
  goBack() {
    wx.navigateBack();
  },
 
  // 获取保存的倒计时时间
  getSavedTime() {
    const savedTime = wx.getStorageSync('countdownTime')
    return savedTime ? parseInt(savedTime) : null
  },
  // 保存倒计时时间到本地存储
  saveTime() {
    wx.setStorageSync('countdownTime', this.data.countdownTime.toString())
  },
  clearTime() {
    this.setData({
      countdownTime: 2 * 60 * 60 * 1000
    })
  },
  // 暂停或继续倒计时
  toggleCountdown() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval)
      this.setData({
        countdownInterval: null,
        isCountdownRunning: false
      })
    } else {
      this.startCountdown()
      this.setData({
        isCountdownRunning: true
      })
    }
  },
  // 开始倒计时
  startCountdown() {
    // 如果计时器已经存在,先清除之前的计时器
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval)
      this.setData({
        countdownInterval: null
      })
    }
    this.setData({
      countdownInterval: setInterval(() => {
        this.setData({
          countdownTime: this.data.countdownTime - 1000
        })
        if (this.data.countdownTime <= 0) {
          clearInterval(this.data.countdownInterval)
          this.setData({
            countdownTime: 0,
            isCountdownRunning: false
          })
        }
        this.saveTime()
      }, 1000)
    })
  },
  // 切换题目
  changeSwiper(e) {
    this.setData({
      currentIndex: e.detail.index
    })
    let index = e.detail.index - 1 >= 0 ? e.detail.index - 1 : 0
    let flag = this.isHaveAnswer(this.data.questionDataList[index].userAnswer)
    if (flag) this.handleQuestion(e.detail.index)
 
  },
  // 点击答题卡跳转题目
  goQuestion(e) {
    console.log(e);
    const id = e.detail.id
    this.data.questionDataList.forEach((item, index) => {
      if (item.id == id) {
        this.setData({
          currentIndex: index
        })
      }
    })
  },
  // 单选 多选 触发
  onChangeRadio(e) {
    const radioData = e.detail.value.currentTarget.dataset.value
    const id = e.detail.value.currentTarget.dataset.id
    const radioChecked = e.detail.value.detail.value
    const questionList = this.data.questionDataList
    questionList.forEach(item => {
      if (item.id == id) {
        item.userAnswer = radioChecked
      }
    })
    this.setData({
      questionDataList: questionList
    })
    console.log(this.data.questionDataList);
  },
  // 输入框触发
  onChangeInput(e) {
    const inputData = e.detail.value.detail.value
    const id = e.detail.value.currentTarget.dataset.id
    const index = e.detail.value.currentTarget.dataset.index
    const questionList = this.data.questionDataList
    questionList.forEach(item => {
      if (item.id == id) {
        item.userAnswer[index] = inputData
      }
    })
    this.setData({
      questionDataList: questionList
    })
    console.log(this.data.questionDataList);
  },
  // 数组转为字符串方法
  arrayToString(data) {
    // 检查是否为数组
    if (Array.isArray(data)) {
      // 使用 join 方法将数组转换为字符串,默认使用逗号分隔
      return data.join(',').replace(/<[^>]*>/g, '')
    } else {
      // 如果不是数组,直接返回原始值
      return data.replace(/<[^>]*>/g, '')
    }
  },
  // 判断是否有用户答案
  isHaveAnswer(data) {
    if (typeof data == 'string') {
      data = data
        .replace(/<[^>]*>/g, '')
        .replace(/&nbsp;/g, '')
        .trim()
      if (data.length) {
        return true
      } else {
        return false
      }
    } else {
      const answer = data.find((item) => item.length > 0)
      if (answer) {
        return true
      } else {
        return false
      }
    }
  },
  // 提交逻辑
  submitPaper() {
    this.setData({
      submitStatus: true
    })
    if (this.data.answerType == 'option') {
      this.toggleCountdown()
      const child = this.selectComponent('#question-options')
      if (this.data.answerType == 'option' || this.data.answerType == 'errorQuestion') {
        // 先遍历所有题目,将未批改的题目批改
        const qustionList = this.data.questionDataList
        for (let index = 0; index < qustionList.length; index++) {
          const item = qustionList[index];
          if (!item.isComplete) this.handleQuestion(index + 1)
        }
      }
      if (this.data.answerType == 'option') {
        this.recordAnswerData()
        child.openTestReportDialog()
      }
    } else if (this.data.answerType == 'collectQuestion' || this.data.answerType == 'errorQuestion') {
      this.goBack()
    }
 
  },
  // 初始化函数
  async init() {
    this.setData({
      loading: true,
      subjectiveTotal: 0,
      subjectiveNum: 0,
      subjectiveGrade: 0
    })
    if (this.data.answerType == 'option') {
      if (this.data)
        this.startCountdown()
      this.setData({
        countdownTime: 2 * 60 * 60 * 1000
      })
      // 测试答题
      await this.getCollectIdList() // 获取收藏id列表
      await this.getErrorList()   // 获取错题id列表
    } else if (this.data.answerType == 'collectQuestion') {
      // 我的收藏
      await this.getcollectId() // 获取收藏题目
    } else if (this.data.answerType == 'errorQuestion') {
      // 我的错题
      // loadings.value = true
      await this.getErrorIdList()
      await this.getCollectIdList() // 获取收藏id列表
    }
  },
  async restart() {
    const countDownRef = this.selectComponent('#countDownRef')
    this.setData({
      loading: true,
      total: 0,
      subjectiveGrade: 0,
      subjectiveTotal: 0,
      subjectiveNum: 0,
      currentIndex: 0,
      submitStatus: false
    })
    if (this.data.answerType == 'option') {
      this.setData({
        countdownTime: 2 * 60 * 60 * 1000
      })
      this.delAnswerInfo(() => {
        this.getQuestionList()
        this.clearTime()
      })
      if (!this.data.submitStatus) {
        this.startCountdown()
      }
    } else if (this.data.answerType == 'mock') {
      // 组卷模式
      // 清空答题记录
      await app.MG.identity.setUserKey({
        setKeyRequests: [
          {
            domain: 'mockAnswerData',
            key: route.query.uuid,
            value: JSON.stringify({
              time: countDownRef.value.countdownTime,
              answerData: []
            })
          }
        ]
      })
      this.init()
    } else {
      this.init()
      this.clearTime()
      if (submitStatus.value) {
        this.startCountdown()
      }
    }
  },
  // 获取收藏题目列表id
  getCollectIdList() {
    app.MG.identity
      .getUserKey({
        domain: 'collectData',
        keys: [this.data.rootCmsItemId]
      })
      .then((res) => {
        try {
          this.setData({
            collectList: JSON.parse(res[0].value)
          })
        } catch (error) {
        }
        if (this.data.answerType == 'option') {
          // 先获取用户答题记录
          this.getAnswerInfo(async (res) => {
            if (res.length) {
              // 有记录,不能答题,状态设为已提交
              this.setData({
                submitStatus: true
              })
              let value = JSON.parse(res[0].value)
              // 有答题记录,得分赋值
              if (value) {
                this.setData({
                  submitStatus: true
                })
                value.dataList.forEach((item) => {
                  if (item.name == '客观题得分' && item.path == this.data.productLinkPath)
                    this.setData({
                      subjectiveNum: item.score
                    })
                })
              }
              this.setData({
                currentIndex: value.currentIndex
              })
              // 携带答题记录 获取题目
              await this.getQuestionList(value.dataList)
            } else {
              await this.getQuestionList() // 获取题库题目
            }
          })
        }
      })
  },
  // 获取错题id列表
  getErrorList() {
    app.MG.identity
      .getUserKey({
        domain: 'errorData',
        keys: [this.data.rootCmsItemId]
      })
      .then((res) => {
        try {
          this.setData({
            errorList: JSON.parse(res[0].value)
          })
        } catch (error) {
 
        }
      })
  },
  // 获取题库题目
  getQuestionList(oldData) {
    // 清空正确题数记录
    this.setData({
      cardList: [],
      correctNum: 0,
    })
    let flag = 0
    this.data.idPathList.forEach((pathitem) => {
      const pathList = this.data.cardList
      pathList.push({
        path: pathitem.productLinkPath,
        catalogName: pathitem.name,
        infoList: []
      })
      this.setData({
        cardList: pathList
      })
      // 获取题目
      let query = {
        path: '*',
        queryType: '*',
        productId: this.data.bookId,
        cmsPath: pathitem.productLinkPath,
        itemFields: {
          // SysType: 'CmsFolder',
          Embedded_QuestionBank_Stem: [],
          Embedded_QuestionBank_AnalysisCon: [],
          Embedded_QuestionBank_Answer: [],
          Embedded_QuestionBank_Option: [],
          Embedded_QuestionBank_QuestionType: [],
          Embedded_QuestionBank_StemStyle: [],
          Embedded_QuestionBank_OptionStyle: [],
          Embedded_QuestionBank_KnowledgePoint: [],
          Embedded_QuestionBank_Difficulty: []
        },
        pading: {
          start: 0,
          size: 999
        }
      }
      app.MG.store.getProductDetail(query).then((res) => {
        this.setData({
          total: res.datas.cmsDatas[0].datas.length
        })
        // total.value += res.datas.cmsDatas[0].datas.length
        let oldList
        if (oldData) {
          // 提交过,存在答题记录
          oldList = oldData.find((item) => item.path == pathitem.productLinkPath).infoList
          this.setData({
            submitStatus: true
          })
        }
        res.datas.cmsDatas[0].datas.forEach((item, index) => {
          let oldObj = ''
          if (oldList) oldObj = oldList.find((oldItem) => oldItem.id == item.id)
          let questionObj = {
            // num: index, // 题号
            id: item.id,
            type: pathitem.name,
            stem:
              item.Embedded_QuestionBank_QuestionType == 'completion'
                ? JSON.parse(item.Embedded_QuestionBank_Stem)
                  .stemTxt.replaceAll('<vacancy>', ',input,')
                  .split(',')
                : JSON.parse(item.Embedded_QuestionBank_Stem), // 题干
            answer: item.Embedded_QuestionBank_Answer, // 答案
            option: item.Embedded_QuestionBank_Option
              ? JSON.parse(item.Embedded_QuestionBank_Option)
              : '', // 选择题选项
            analysisCon: item.Embedded_QuestionBank_AnalysisCon, // 解析
            questionType: item.Embedded_QuestionBank_QuestionType, // 题型
            optionStyle: item.Embedded_QuestionBank_OptionStyle, // 选项显示类型
            stemStyle: item.Embedded_QuestionBank_StemStyle, // 题干显示类型
            difficulty: item.Embedded_QuestionBank_Difficulty
              ? 4 - item.Embedded_QuestionBank_Difficulty
              : 0, // 难度等级
            userAnswer: oldObj
              ? oldObj.userAnswer
              : item.Embedded_QuestionBank_QuestionType == 'completion' ||
                item.Embedded_QuestionBank_QuestionType == 'multipleChoice'
                ? []
                : '',
            isRight: oldObj ? oldObj.isRight : null,
            isComplete: oldObj ? oldObj.isComplete : false,
            isCollect: this.data.collectList.indexOf(item.id) > -1 ? true : false,
            isUnfold: '' // 控制解析的折叠面板是否展开
          }
          // 多选和填空答案肯为数组,要转换JSON格式
          if (
            questionObj.questionType == 'completion' ||
            questionObj.questionType == 'multipleChoice'
          ) {
            try {
              questionObj.answer = JSON.parse(questionObj.answer)
            } catch (error) {
              questionObj.answer = item.Embedded_QuestionBank_Answer
            }
          }
          // questionObj.userAnswer = this.arrayToString(questionObj.userAnswer)
          // questionObj.isHaveAnswer = this.isHaveAnswer(questionObj.userAnswer)
          // 填空题改造
          if (questionObj.questionType == 'completion') {
            let index = 0
            for (let i = 0; i < questionObj.stem.length; i++) {
              const item = questionObj.stem[i]
              if (item == 'input') {
                questionObj.stem[i] = {
                  num: index,
                  data: 'input'
                }
                if (!oldObj) questionObj.userAnswer[index] = ''
                index++
              }
            }
          }
          // 获取图片
          if (questionObj.stemStyle == 'Image' || questionObj.stemStyle == 'TxtAndImage') {
            questionObj.stem.stemImage = getPublicImage(questionObj.stem.stemImage, 150)
          }
          if (questionObj.optionStyle == 'Image' || questionObj.optionStyle == 'TxtAndImage') {
            questionObj.option.forEach(optionItem => {
              if (optionItem.img) optionItem.img = getPublicImage(optionItem.img, 150)
            })
          }
          // if (questionObj.optionStyle == 'RichText') {
          //   questionObj.option.forEach(optionItem => {
          //     optionItem.txt.replace(/<img>/g, "<img class='imgClass'>")
          //   })
          // }
          // 旧数据里 题目已经作答,修改已答题目数量
          // if (oldObj && oldObj.userAnswer.length > 0) countDownRef.value.changeAlready()
          // 旧数据里 题目正确 记录正确数量
          if (questionObj.isRight) {
            this.setData({
              correctNum: this.data.correctNum + 1
            })
          }
          if (pathitem.name == '判断题' || pathitem.name == '填空题' || pathitem.name == '多选题' || pathitem.name == '单选题' || pathitem.name == '听力题') {
            if (oldObj) {
              this.setData({
                subjectiveTotal: this.data.subjectiveTotal + 1
              })
            }
 
          }
          // cardList赋值
          let cardIndex = this.data.cardList.findIndex((item) => item.path == pathitem.productLinkPath)
          let infoList = this.data.cardList[cardIndex].infoList
          infoList.push(questionObj)
          this.setData({
            [`cardList[${cardIndex}].infoList`]: infoList
          })
          //   this.data.cardList[this.data.cardList.findIndex((item) => item.path == pathitem.productLinkPath)]
          //     .infoList
          // infoList.push(questionObj)
          flag++;
          let questionList = []
          const cardUpdatedList = this.data.cardList
          // if (flag == this.data.idPathList.length) {
          cardUpdatedList.forEach(aitem => {
            aitem.infoList.forEach((bitem, bindex) => {
              questionList.push(bitem)
              bitem.number = bindex + 1
              bitem.grade = 2
            })
          })
          this.setData({
            questionDataList: questionList,
            cardList: cardUpdatedList
          })
        })
      })
    })
    this.setData({
      loading: false,
    })
  },
  // 批改题目 (练习,我的错题,我的收藏)
  handleQuestion(num) {
    const questionList = this.data.questionDataList
    const index = num - 1 >= 0 ? num - 1 : 0
    if (questionList[index].isComplete) {
      // 题目已完成,跳过
      return true
    }
    questionList[index].isComplete = true
    const item = questionList[index]
    // 批改题目
    if (item.questionType == 'multipleChoice') {
      // 多选题
      // subjectiveGrade.value += item.score
      if (item.answer.length == item.userAnswer.length) {
        const sortedArr1 = item.answer.slice().sort()
        const sortedArr2 = item.userAnswer.slice().sort()
        questionList[index].isRight = sortedArr1.every(
          (value, valueIndex) => value === sortedArr2[valueIndex]
        )
      } else {
        questionList[index].isRight = false
      }
    } else if (item.questionType == 'singleChoice' || item.questionType == 'judge') {
      // 单选 判断
      // subjectiveGrade.value += item.score
      questionList[index].isRight = item.answer == item.userAnswer
    } else if (item.questionType == 'shortAnswer') {
      // 简答 翻译
      questionList[index].isRight = null
    } else if (item.questionType == 'completion') {
      // 填空
      // subjectiveGrade.value += item.score
      if (typeof item.answer == 'string') {
        questionList[index].isRight = item.answer == item.userAnswer[0]
      } else {
        if (item.answer.length != item.userAnswer.length) {
          questionList[index].isRight = false
        } else {
          questionList[index].isRight = item.answer.every(
            (value, valueIndex) => value === item.userAnswer[valueIndex]
          )
        }
      }
    }
    if (item.questionType != 'shortAnswer') {
      this.setData({
        subjectiveTotal: this.data.subjectiveTotal + 1,
        subjectiveGrade: this.data.subjectiveGrade + item.grade
      })
    }
    if (questionList[index].isRight && item.questionType != 'shortAnswer') {
      // 客观题回答正确
      this.setData({
        subjectiveNum: this.data.subjectiveNum + item.grade,
        correctNum: this.data.correctNum + 1
      })
    }
    if (!questionList[index].isRight && item.questionType != 'shortAnswer') {
      // 客观题回答错误 记录错题
      if (this.data.errorList.findIndex((errorItem) => errorItem == item.id) == -1) {
        this.data.errorList.push(item.id)
      }
    } else {
      if (this.data.answerType == 'errorQuestion' || this.data.answerType == 'option') {
        // 从错题集中移除
        let errorIndex = this.data.errorList.findIndex((erroritem) => erroritem == item.id)
        if (errorIndex > -1) {
          this.data.errorList.splice(errorIndex, 1)
        }
      }
    }
    if (this.data.answerType != 'collectQuestion') {
      // 记录错题
      app.MG.identity
        .setUserKey({
          setKeyRequests: [
            {
              domain: 'errorData',
              key: this.data.rootCmsItemId,
              value: JSON.stringify(this.data.errorList)
            }
          ]
        })
        .then((res) => {
          console.log(res)
        })
    }
    this.setData({
      questionDataList: questionList
    })
    const cardUpdatedList = this.data.cardList
    cardUpdatedList.forEach((item) => {
      item.infoList.forEach((citem) => {
        if (citem.id == questionList[index].id) {
          citem = questionList[index];
        }
      });
    });
    this.setData({
      cardList: cardUpdatedList
    })
    // console.log(this.data.questionDataList, this.data.cardList);
  },
  // 题目收藏按钮,收藏和取消同一接口,取消数组减去该项id
  setCollect() {
    const citem = this.data.questionDataList[this.data.currentIndex]
    const questionList = this.data.questionDataList
    for (let index = 0; index < questionList.length; index++) {
      const item = questionList[index];
      if (item.id == citem.id) {
        item.isCollect = !item.isCollect
      }
    }
    this.setData({
      questionDataList: questionList
    })
    if (this.data.collectList.length == 0) {
      this.setData({
        collectList: [citem.id]
      })
    } else {
      const collectItme = this.data.collectList.filter((item) => item == citem.id)
      if (collectItme.length) {
        const arr = this.data.collectList.filter((item) => item != citem.id)
        this.setData({
          collectList: arr
        })
      } else {
        const collectArr = this.data.collectList
        collectArr.push(citem.id)
        this.setData({
          collectList: collectArr
        })
      }
    }
    app.MG.identity
      .setUserKey({
        setKeyRequests: [
          {
            domain: 'collectData',
            key: this.data.rootCmsItemId,
            value: JSON.stringify(this.data.collectList)
          }
        ]
      })
      .then((res) => { })
  },
  // 处理答题数据
  recordAnswerData() {
    this.data.cardList.push(
      {
        name: '客观题得分',
        score: this.data.subjectiveNum,
        path: this.data.productLinkPath,
        // infoList: [],
        // catalogName: ''
      }
    )
    let setInfoData = {
      currentIndex: this.data.currentIndex,
      dataList: JSON.parse(JSON.stringify(this.data.cardList))
    }
    for (let i = 0; i < setInfoData.dataList.length; i++) {
      const item = setInfoData.dataList[i]
      if (!item.name && !item.name == '客观题得分') {
        for (let j = 0; j < item.infoList.length; j++) {
          let obj = {
            id: item.infoList[j].id,
            userAnswer: item.infoList[j].userAnswer,
            isComplete: item.infoList[j].isComplete,
            isRight: item.infoList[j].isRight,
            isCollect: item.infoList[j].isCollect
          }
          item.infoList[j] = obj
        }
      }
    }
 
    this.setAnswerInfo(setInfoData)
  },
  // 提交答题数据
  setAnswerInfo(data) {
    app.MG.identity
      .setUserKey({
        setKeyRequests: [
          {
            domain: 'answerData',
            key: this.data.productLinkPath,
            value: JSON.stringify(data)
          }
        ]
      })
      .then((res) => { })
  },
  // 获取答题数据
  getAnswerInfo(callback) {
    app.MG.identity
      .getUserKey({
        domain: 'answerData',
        keys: [this.data.productLinkPath]
      })
      .then((res) => {
        if (callback) callback(res)
      })
  },
  // 删除答题数据
  delAnswerInfo(callback) {
    app.MG.identity
      .delUserKey({
        domain: 'answerData',
        keys: [this.data.productLinkPath]
      })
      .then((res) => {
        if (callback) callback()
      })
  },
  // 我的收藏模式下获取收藏题目id
  async getcollectId() {
    app.MG.identity
      .getUserKey({
        domain: 'collectData',
        keys: [this.data.rootCmsItemId]
      })
      .then(async (res) => {
        try {
          this.setData({
            collectList: JSON.parse(res[0].value)
          })
          // total.value = collectList.value.length
        } catch (error) {
        }
        if (this.data.collectList && this.data.collectList.length) {
          await this.getCollectDataList()
        } else {
          this.setData({
            loading: false
          })
          wx.showModal({
            title: '提示',
            content: '收藏夹暂无数据',//editable如果为true,这就是输入框的内容
            editable: false,//是否显示输入框
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                this.setData({
                  submitStatus: true
                })
                this.goBack()
              }
 
            }
          })
        }
        // console.log('收藏', collectList.value)
      })
  },
  // 获取收藏夹
  async getCollectDataList() {
    let questionArr = []
    this.setData({
      cardList: [
        {
          catalogName: '收藏夹',
          infoList: []
        }
      ]
    })
    let query = {
      path: '*',
      cmsPath: this.data.rootCmsItemId,
      cmsType: '*',
      productId: this.data.bookId,
      queryType: '*',
      itemIds: this.data.collectList.map((item) => item + ''),
      itemFields: {
        Embedded_QuestionBank_Stem: [],
        Embedded_QuestionBank_AnalysisCon: [],
        Embedded_QuestionBank_Answer: [],
        Embedded_QuestionBank_Option: [],
        Embedded_QuestionBank_QuestionType: [],
        Embedded_QuestionBank_StemStyle: [],
        Embedded_QuestionBank_OptionStyle: [],
        Embedded_QuestionBank_KnowledgePoint: [],
        Embedded_QuestionBank_Difficulty: []
      }
    }
    app.MG.store.getProductDetail(query).then((res) => {
      let questionArr = []
      res.datas.cmsDatas[0].datas.forEach((item, index) => {
        const questionObj = {
          number: index + 1, // 题号
          id: item.id,
          stem:
            item.Embedded_QuestionBank_QuestionType == 'completion'
              ? JSON.parse(item.Embedded_QuestionBank_Stem)
                .stemTxt.replaceAll('<vacancy>', ',input,')
                .split(',')
              : JSON.parse(item.Embedded_QuestionBank_Stem), // 题干
          answer: item.Embedded_QuestionBank_Answer, // 答案
          option: item.Embedded_QuestionBank_Option
            ? JSON.parse(item.Embedded_QuestionBank_Option)
            : '', // 选择题选项
          analysisCon: item.Embedded_QuestionBank_AnalysisCon, // 解析
          questionType: item.Embedded_QuestionBank_QuestionType, // 题型
          optionStyle: item.Embedded_QuestionBank_OptionStyle, // 选项显示类型
          stemStyle: item.Embedded_QuestionBank_StemStyle, // 题干显示类型
          difficulty: item.Embedded_QuestionBank_Difficulty
            ? 4 - item.Embedded_QuestionBank_Difficulty
            : 0, // 难度等级
          userAnswer:
            item.Embedded_QuestionBank_QuestionType == 'completion' ||
              item.Embedded_QuestionBank_QuestionType == 'multipleChoice'
              ? []
              : '',
          isSubmit: false, // 查看解析
          isRight: null, // 是否正确
          isComplete: false,
          isCollect: true
        }
        // 多选和填空答案肯为数组,要转换JSON格式
        if (
          questionObj.questionType == 'completion' ||
          questionObj.questionType == 'multipleChoice'
        ) {
          try {
            questionObj.answer = JSON.parse(questionObj.answer)
          } catch (error) {
            //
          }
        }
        // 填空题改造
        if (questionObj.questionType == 'completion') {
          let index = 0
          for (let i = 0; i < questionObj.stem.length; i++) {
            const item = questionObj.stem[i]
            if (item == 'input') {
              questionObj.stem[i] = {
                num: index,
                data: 'input'
              }
              questionObj.userAnswer[index] = ''
              index++
            }
          }
        }
        // 获取图片
        if (questionObj.stemStyle == 'Image' || questionObj.stemStyle == 'TxtAndImage') {
          questionObj.stem.stemImage = getPublicImage(questionObj.stem.stemImage, 150)
        }
        if (questionObj.optionStyle == 'Image' || questionObj.optionStyle == 'TxtAndImage') {
          questionObj.option.forEach(optionItem => {
            if (optionItem.img) optionItem.img = getPublicImage(optionItem.img, 150)
          })
        }
        // if (item.Embedded_QuestionBank_QuestionType == 'judge') {
        //   topicList.value.judge.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'singleChoice') {
        //   topicList.value.radio.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'multipleChoice') {
        //   topicList.value.check.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'completion') {
        //   topicList.value.gap.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'shortAnswer') {
        //   topicList.value.short.data.push(questionObj)
        // }
        questionArr.push(questionObj)
        // cardList.value[0].infoList.push(questionObj)
      })
      // loadings.value = false
      this.setData({
        questionDataList: questionArr,
        ['cardList[0].infoList']: questionArr,
        loading: false,
      })
    })
  },
  // 我的错题模式下获取错题id列表
  async getErrorIdList() {
    await app.MG.identity
      .getUserKey({
        domain: 'errorData',
        keys: [this.data.rootCmsItemId]
      })
      .then((res) => {
        try {
          this.setData({
            errorList: JSON.parse(res[0].value)
          })
        } catch (error) {
        }
        if (this.data.errorList && this.data.errorList.length) {
          this.getErrorDataList()
        } else {
          this.setData({
            loading: true
          })
          wx.showModal({
            title: '提示',
            content: '错题集暂无数据',//editable如果为true,这就是输入框的内容
            editable: false,//是否显示输入框
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                this.setData({
                  submitStatus: true
                })
                this.goBack()
              }
            }
          })
        }
      })
  },
  // 获取错题集
  async getErrorDataList() {
    this.setData({
      cardList: [
        {
          catalogName: '错题集',
          infoList: []
        }
      ]
    })
    let query = {
      path: '*',
      cmsPath: this.data.rootCmsItemId,
      cmsType: '*',
      productId: this.data.bookId,
      queryType: '*',
      itemIds: this.data.errorList.map((item) => item + ''),
      itemFields: {
        Embedded_QuestionBank_Stem: [],
        Embedded_QuestionBank_AnalysisCon: [],
        Embedded_QuestionBank_Answer: [],
        Embedded_QuestionBank_Option: [],
        Embedded_QuestionBank_QuestionType: [],
        Embedded_QuestionBank_StemStyle: [],
        Embedded_QuestionBank_OptionStyle: [],
        Embedded_QuestionBank_KnowledgePoint: [],
        Embedded_QuestionBank_Difficulty: []
      }
    }
    await app.MG.store.getProductDetail(query).then((res) => {
      let questionArr = []
      res.datas.cmsDatas[0].datas.forEach((item, index) => {
        const questionObj = {
          number: index + 1, // 题号
          id: item.id,
          stem:
            item.Embedded_QuestionBank_QuestionType == 'completion'
              ? JSON.parse(item.Embedded_QuestionBank_Stem)
                .stemTxt.replaceAll('<vacancy>', ',input,')
                .split(',')
              : JSON.parse(item.Embedded_QuestionBank_Stem), // 题干
          answer: item.Embedded_QuestionBank_Answer, // 答案
          option: item.Embedded_QuestionBank_Option
            ? JSON.parse(item.Embedded_QuestionBank_Option)
            : '', // 选择题选项
          analysisCon: item.Embedded_QuestionBank_AnalysisCon, // 解析
          questionType: item.Embedded_QuestionBank_QuestionType, // 题型
          optionStyle: item.Embedded_QuestionBank_OptionStyle, // 选项显示类型
          stemStyle: item.Embedded_QuestionBank_StemStyle, // 题干显示类型
          difficulty: item.Embedded_QuestionBank_Difficulty
            ? 4 - item.Embedded_QuestionBank_Difficulty
            : 0, // 难度等级
          userAnswer:
            item.Embedded_QuestionBank_QuestionType == 'completion' ||
              item.Embedded_QuestionBank_QuestionType == 'multipleChoice'
              ? []
              : '',
          isSubmit: false, // 查看解析
          isRight: null, // 是否正确
          isComplete: false,
          isCollect: this.data.collectList.some((collectItem) => collectItem == item.id)
        }
        // 多选和填空答案肯为数组,要转换JSON格式
        if (
          questionObj.questionType == 'completion' ||
          questionObj.questionType == 'multipleChoice'
        ) {
          try {
            questionObj.answer = JSON.parse(questionObj.answer)
          } catch (error) {
            //
          }
        }
        // 填空题改造
        if (questionObj.questionType == 'completion') {
          let index = 0
          for (let i = 0; i < questionObj.stem.length; i++) {
            const item = questionObj.stem[i]
            if (item == 'input') {
              questionObj.stem[i] = {
                num: index,
                data: 'input'
              }
              questionObj.userAnswer[index] = ''
              index++
            }
          }
        }
        // 获取图片
        if (questionObj.stemStyle == 'Image' || questionObj.stemStyle == 'TxtAndImage') {
          questionObj.stem.stemImage = getPublicImage(questionObj.stem.stemImage, 150)
        }
        if (questionObj.optionStyle == 'Image' || questionObj.optionStyle == 'TxtAndImage') {
          questionObj.option.forEach(optionItem => {
            if (optionItem.img) optionItem.img = getPublicImage(optionItem.img, 150)
          })
        }
        // if (item.Embedded_QuestionBank_QuestionType == 'judge') {
        //   topicList.value.judge.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'singleChoice') {
        //   topicList.value.radio.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'multipleChoice') {
        //   topicList.value.check.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'completion') {
        //   topicList.value.gap.data.push(questionObj)
        // } else if (item.Embedded_QuestionBank_QuestionType == 'shortAnswer') {
        //   topicList.value.short.data.push(questionObj)
        // }
        questionArr.push(questionObj)
      })
      this.setData({
        questionDataList: questionArr,
        ['cardList[0].infoList']: questionArr,
        loading: false
      })
    })
    // loadings.value = false
    // console.log('错题集', topicList.value)
  }
})