index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import {
  2. ActionSheet,
  3. Button,
  4. Cell,
  5. CountDown,
  6. Icon,
  7. Image,
  8. Popup,
  9. showDialog,
  10. Swipe,
  11. SwipeItem,
  12. Tag
  13. } from 'vant'
  14. import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
  15. import { useRoute, useRouter } from 'vue-router'
  16. import styles from './index.module.less'
  17. import iconQuestionNums from '../images/icon-question-nums.png'
  18. import iconCountDown from '../images/icon-count-down.png'
  19. import iconButtonList from '../images/icon-button-list.png'
  20. import OSticky from '@/components/o-sticky'
  21. import ChoiceQuestion from '../model/choice-question'
  22. import AnswerList from '../model/answer-list'
  23. import ODialog from '@/components/o-dialog'
  24. import DragQuestion from '../model/drag-question'
  25. import KeepLookQuestion from '../model/keep-look-question'
  26. import PlayQuestion from '../model/play-question'
  27. import request from '@/helpers/request'
  28. import dayjs from 'dayjs'
  29. import ResultFinish from '../model/result-finish'
  30. import { eventUnit, QuestionType } from '../unit'
  31. import { useRect } from '@vant/use'
  32. export default defineComponent({
  33. name: 'unit-detail',
  34. setup() {
  35. const route = useRoute()
  36. const router = useRouter()
  37. const countDownRef = ref()
  38. const swipeRef = ref()
  39. const state = reactive({
  40. id: route.query.id,
  41. examDetail: {} as any,
  42. visiableAnswer: false,
  43. currentIndex: 0,
  44. questionList: [],
  45. time: 0,
  46. visiableSure: false,
  47. visiableResult: false,
  48. resultInfo: {} as any,
  49. resultStatusType: 'SUCCESS', // 'SUCCESS' | 'FAIL'
  50. visiableExam: false, // 考试已结束
  51. nextStatus: false,
  52. swipeHeight: 'auto' as any,
  53. quitStatus: false
  54. })
  55. const getExamDetails = async () => {
  56. try {
  57. const { data } = await request.post(
  58. '/api-student/studentUnitExamination/startExamination',
  59. {
  60. requestType: 'form',
  61. data: {
  62. studentUnitExaminationId: state.id
  63. }
  64. }
  65. )
  66. const { questionJson, studentAnswerJson, ...res } = data
  67. const temp = questionJson || []
  68. temp.forEach((item: any) => {
  69. item.userAnswer = formatUserAnswers(item, studentAnswerJson)
  70. })
  71. state.questionList = temp
  72. state.examDetail = { ...res } || {}
  73. calcTime()
  74. } catch {
  75. //
  76. }
  77. }
  78. /**
  79. * @description 计算考试时间剩余时间
  80. */
  81. const calcTime = async () => {
  82. const examDetail = state.examDetail || {}
  83. const startTime = examDetail.startTime
  84. const nowTime = examDetail.now
  85. const timeMinutes = examDetail.timeMinutes || 0 // 测验时间
  86. // 返回秒
  87. const minu = dayjs(startTime).add(timeMinutes, 'minute').diff(dayjs(nowTime))
  88. // 时间到了考试结束
  89. if (minu <= 0) {
  90. await onConfirmExam()
  91. state.visiableExam = true
  92. } else {
  93. state.time = Math.ceil(minu / 1000) * 1000
  94. setTimeout(() => {
  95. countDownRef.value?.start()
  96. }, 10)
  97. }
  98. }
  99. /**
  100. * @description 初始化用户答案
  101. */
  102. const formatUserAnswers = (item: any, userAnswer: any) => {
  103. // 判断是否有结果
  104. if (!userAnswer) return []
  105. const answers = userAnswer || []
  106. return answers[item.id] ? answers[item.id] : []
  107. }
  108. /**
  109. * @description 重置当前的题目高度
  110. */
  111. let size = 0
  112. const resizeSwipeItemHeight = (scroll = true) => {
  113. nextTick(() => {
  114. scroll && window.scrollTo(0, 0)
  115. setTimeout(() => {
  116. // const currentItemDom: Element =
  117. // document.querySelectorAll('.swipe-item-question')[state.currentIndex]
  118. const currentItemDom: any = document
  119. .querySelectorAll('.van-swipe-item')
  120. [state.currentIndex]?.querySelector('.swipe-item-question')
  121. const allImg = currentItemDom.querySelectorAll('.answerTitleImg img')
  122. let status = true
  123. // console.log(allImg)
  124. allImg.forEach((img: any) => {
  125. console.log(img.complete)
  126. if (!img.complete) {
  127. status = false
  128. }
  129. })
  130. // 判断图片是否加载完了
  131. if (!status && size < 3) {
  132. setTimeout(() => {
  133. size += 1
  134. resizeSwipeItemHeight(scroll)
  135. }, 300)
  136. }
  137. if (status) {
  138. size = 0
  139. }
  140. const rect = useRect(currentItemDom)
  141. state.swipeHeight = rect.height
  142. }, 100)
  143. })
  144. }
  145. /**
  146. * @description 下一题 | 测试完成
  147. */
  148. const onNextQuestion = async () => {
  149. try {
  150. const questionList = state.questionList || []
  151. const userAnswerList: any = [] // 所有题目的答案
  152. // let currentResult = false // 当前题目是否已经答题
  153. questionList.forEach((question: any, index: number) => {
  154. // 格式化所有题目的答案
  155. if (question.userAnswer && question.userAnswer.length > 0) {
  156. userAnswerList.push({
  157. questionId: question.id,
  158. details: question.userAnswer
  159. })
  160. }
  161. })
  162. // 判断是否是最后一题
  163. // console.log(state.questionList.length, state.currentIndex, userAnswerList, '-----')
  164. if (state.questionList.length === state.currentIndex + 1) {
  165. state.visiableSure = true
  166. return
  167. }
  168. state.nextStatus = true
  169. await request.post('/api-student/studentUnitExamination/submitAnswer', {
  170. hideLoading: true,
  171. data: {
  172. answers: userAnswerList,
  173. studentUnitExaminationId: state.id
  174. }
  175. })
  176. swipeRef.value?.next()
  177. state.nextStatus = false
  178. } catch {
  179. //
  180. state.nextStatus = false
  181. }
  182. }
  183. /**
  184. * @description 提交最终答案
  185. */
  186. const onConfirmExam = async () => {
  187. try {
  188. const questionList = state.questionList || []
  189. const userAnswerList: any = [] // 所有题目的答案
  190. questionList.forEach((question: any) => {
  191. // 格式化所有题目的答案
  192. if (question.userAnswer && question.userAnswer.length > 0) {
  193. userAnswerList.push({
  194. questionId: question.id,
  195. details: question.userAnswer
  196. })
  197. }
  198. })
  199. const { data } = await request.post(
  200. '/api-student/studentUnitExamination/completionExamination',
  201. {
  202. data: {
  203. answers: userAnswerList,
  204. studentUnitExaminationId: state.id
  205. }
  206. }
  207. )
  208. if (data.status === 'A_PASS') {
  209. state.resultStatusType = 'SUCCESS'
  210. state.resultInfo = {
  211. tips: '恭喜你,测验通过!',
  212. score: data.score,
  213. examName: state.examDetail.unitExaminationName
  214. }
  215. } else {
  216. state.resultStatusType = 'FAIL'
  217. state.resultInfo = {
  218. tips: '本次测验不合格!',
  219. score: data.score,
  220. examName: state.examDetail.unitExaminationName
  221. }
  222. }
  223. onAfter()
  224. state.visiableResult = true
  225. } catch {
  226. //
  227. }
  228. }
  229. // 拦截
  230. const onBack = () => {
  231. // showDialog({
  232. // title: '提示',
  233. // message: '您考试还未提交,是否退出?',
  234. // theme: 'round-button',
  235. // confirmButtonColor: '#ff8057'
  236. // }).then(() => {
  237. // onAfter()
  238. // router.back()
  239. // })
  240. state.quitStatus = true
  241. }
  242. const onAfter = () => {
  243. window.removeEventListener('popstate', onBack, false)
  244. }
  245. onMounted(async () => {
  246. await getExamDetails()
  247. // 初始化高度
  248. resizeSwipeItemHeight()
  249. window.history.pushState(null, '', document.URL)
  250. window.addEventListener('popstate', onBack, false)
  251. })
  252. return () => (
  253. <div class={styles.unitDetail}>
  254. <Cell center class={styles.unitSection} border={false}>
  255. {{
  256. title: () => <div class={styles.unitTitle}>{state.examDetail.unitExaminationName}</div>,
  257. label: () => (
  258. <div class={styles.unitCount}>
  259. <div class={styles.qNums}>
  260. <Icon class={styles.icon} name={iconQuestionNums} />
  261. 题目数量{' '}
  262. <span class={styles.num} style={{ paddingLeft: '6px' }}>
  263. {state.currentIndex + 1}
  264. </span>
  265. /{state.examDetail.questionNum}
  266. </div>
  267. <div class={styles.qNums}>
  268. <Icon class={styles.icon} name={iconCountDown} />
  269. 剩余时长:
  270. <CountDown
  271. ref={countDownRef}
  272. v-model:time={state.time}
  273. format={'mm:ss'}
  274. autoStart={false}
  275. onFinish={async () => {
  276. await onConfirmExam()
  277. state.visiableExam = true
  278. }}
  279. />
  280. </div>
  281. </div>
  282. )
  283. }}
  284. </Cell>
  285. <Swipe
  286. loop={false}
  287. showIndicators={false}
  288. ref={swipeRef}
  289. duration={300}
  290. touchable={false}
  291. height={state.swipeHeight}
  292. style={{ marginBottom: '12px' }}
  293. lazyRender
  294. onChange={(index: number) => {
  295. eventUnit.emit('unitAudioStop')
  296. state.currentIndex = index
  297. resizeSwipeItemHeight()
  298. }}
  299. >
  300. {state.questionList.map((item: any, index: number) => (
  301. // item.questionTypeCode === QuestionType.LINK && (
  302. // <SwipeItem>
  303. // <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
  304. // </SwipeItem>
  305. // )
  306. <SwipeItem>
  307. <div class="swipe-item-question">
  308. {item.questionTypeCode === QuestionType.RADIO && (
  309. <ChoiceQuestion
  310. v-model:value={item.userAnswer}
  311. index={index + 1}
  312. data={item}
  313. type="radio"
  314. />
  315. )}
  316. {item.questionTypeCode === QuestionType.CHECKBOX && (
  317. <ChoiceQuestion
  318. v-model:value={item.userAnswer}
  319. index={index + 1}
  320. data={item}
  321. type="checkbox"
  322. />
  323. )}
  324. {item.questionTypeCode === QuestionType.SORT && (
  325. <DragQuestion
  326. v-model:value={item.userAnswer}
  327. onUpdate:value={() => {
  328. resizeSwipeItemHeight(false)
  329. }}
  330. data={item}
  331. index={index + 1}
  332. />
  333. )}
  334. {item.questionTypeCode === QuestionType.LINK && (
  335. <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
  336. )}
  337. {item.questionTypeCode === QuestionType.PLAY && (
  338. <PlayQuestion
  339. v-model:value={item.userAnswer}
  340. data={item}
  341. index={index + 1}
  342. unitId={state.id as any}
  343. />
  344. )}
  345. </div>
  346. </SwipeItem>
  347. ))}
  348. </Swipe>
  349. <OSticky position="bottom" background="white">
  350. <div class={['btnGroup btnMore']}>
  351. {state.currentIndex > 0 && (
  352. <Button
  353. round
  354. block
  355. type="primary"
  356. plain
  357. onClick={() => {
  358. swipeRef.value?.prev()
  359. }}
  360. >
  361. 上一题
  362. </Button>
  363. )}
  364. <Button
  365. block
  366. round
  367. type="primary"
  368. onClick={onNextQuestion}
  369. loading={state.nextStatus}
  370. disabled={state.nextStatus}
  371. >
  372. {state.questionList.length === state.currentIndex + 1 ? '测试完成' : '下一题'}
  373. </Button>
  374. <Image
  375. src={iconButtonList}
  376. class={[styles.wapList, 'van-haptics-feedback']}
  377. onClick={() => (state.visiableAnswer = true)}
  378. />
  379. </div>
  380. </OSticky>
  381. {/* 题目集合 */}
  382. <ActionSheet v-model:show={state.visiableAnswer} title="题目列表" safeAreaInsetBottom>
  383. <AnswerList
  384. value={state.questionList}
  385. onSelect={(item: any) => {
  386. // 跳转,并且跳过动画
  387. swipeRef.value?.swipeTo(item, {
  388. immediate: true
  389. })
  390. state.visiableAnswer = false
  391. }}
  392. />
  393. </ActionSheet>
  394. <Popup
  395. v-model:show={state.visiableResult}
  396. closeOnClickOverlay={false}
  397. style={{ background: 'transparent', width: '96%' }}
  398. >
  399. <ResultFinish
  400. status={state.resultStatusType as any}
  401. result={state.resultInfo}
  402. confirmButtonText="去练习"
  403. cancelButtonText="我知道了"
  404. onClose={() => {
  405. state.visiableResult = false
  406. router.back()
  407. router.back()
  408. }}
  409. onConform={() => {
  410. state.visiableResult = false
  411. router.back()
  412. router.back()
  413. }}
  414. />
  415. </Popup>
  416. <ODialog
  417. v-model:show={state.visiableSure}
  418. title="测验完成"
  419. message="确认本次测验的题目都完成了吗?\n提交后不可修改哦"
  420. messageAlign="left"
  421. showCancelButton
  422. cancelButtonText="再等等"
  423. confirmButtonText="确认完成"
  424. onConfirm={onConfirmExam}
  425. />
  426. <ODialog
  427. v-model:show={state.visiableExam}
  428. message="考试已结束"
  429. messageAlign="center"
  430. onConfirm={async () => {
  431. onAfter()
  432. state.visiableResult = true
  433. }}
  434. />
  435. <ODialog
  436. v-model:show={state.quitStatus}
  437. title="提示"
  438. message="您是否退出本次练习?"
  439. confirmButtonText="确认完成"
  440. onConfirm={() => {
  441. onAfter()
  442. router.back()
  443. }}
  444. />
  445. </div>
  446. )
  447. }
  448. })