index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. router.back()
  245. }
  246. onMounted(async () => {
  247. await getExamDetails()
  248. // 初始化高度
  249. resizeSwipeItemHeight()
  250. window.history.pushState(null, '', document.URL)
  251. window.addEventListener('popstate', onBack, false)
  252. })
  253. return () => (
  254. <div class={styles.unitDetail}>
  255. <Cell center class={styles.unitSection} border={false}>
  256. {{
  257. title: () => <div class={styles.unitTitle}>{state.examDetail.unitExaminationName}</div>,
  258. label: () => (
  259. <div class={styles.unitCount}>
  260. <div class={styles.qNums}>
  261. <Icon class={styles.icon} name={iconQuestionNums} />
  262. 题目数量{' '}
  263. <span class={styles.num} style={{ paddingLeft: '6px' }}>
  264. {state.currentIndex + 1}
  265. </span>
  266. /{state.examDetail.questionNum}
  267. </div>
  268. <div class={styles.qNums}>
  269. <Icon class={styles.icon} name={iconCountDown} />
  270. 剩余时长:
  271. <CountDown
  272. ref={countDownRef}
  273. v-model:time={state.time}
  274. format={'mm:ss'}
  275. autoStart={false}
  276. onFinish={async () => {
  277. await onConfirmExam()
  278. state.visiableExam = true
  279. }}
  280. />
  281. </div>
  282. </div>
  283. )
  284. }}
  285. </Cell>
  286. <Swipe
  287. loop={false}
  288. showIndicators={false}
  289. ref={swipeRef}
  290. duration={300}
  291. touchable={false}
  292. height={state.swipeHeight}
  293. style={{ marginBottom: '12px' }}
  294. lazyRender
  295. onChange={(index: number) => {
  296. eventUnit.emit('unitAudioStop')
  297. state.currentIndex = index
  298. resizeSwipeItemHeight()
  299. }}
  300. >
  301. {state.questionList.map((item: any, index: number) => (
  302. // item.questionTypeCode === QuestionType.LINK && (
  303. // <SwipeItem>
  304. // <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
  305. // </SwipeItem>
  306. // )
  307. <SwipeItem>
  308. <div class="swipe-item-question">
  309. {item.questionTypeCode === QuestionType.RADIO && (
  310. <ChoiceQuestion
  311. v-model:value={item.userAnswer}
  312. index={index + 1}
  313. data={item}
  314. type="radio"
  315. />
  316. )}
  317. {item.questionTypeCode === QuestionType.CHECKBOX && (
  318. <ChoiceQuestion
  319. v-model:value={item.userAnswer}
  320. index={index + 1}
  321. data={item}
  322. type="checkbox"
  323. />
  324. )}
  325. {item.questionTypeCode === QuestionType.SORT && (
  326. <DragQuestion
  327. v-model:value={item.userAnswer}
  328. onUpdate:value={() => {
  329. resizeSwipeItemHeight(false)
  330. }}
  331. data={item}
  332. index={index + 1}
  333. />
  334. )}
  335. {item.questionTypeCode === QuestionType.LINK && (
  336. <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
  337. )}
  338. {item.questionTypeCode === QuestionType.PLAY && (
  339. <PlayQuestion
  340. v-model:value={item.userAnswer}
  341. data={item}
  342. index={index + 1}
  343. unitId={state.id as any}
  344. />
  345. )}
  346. </div>
  347. </SwipeItem>
  348. ))}
  349. </Swipe>
  350. <OSticky position="bottom" background="white">
  351. <div class={['btnGroup btnMore']}>
  352. {state.currentIndex > 0 && (
  353. <Button
  354. round
  355. block
  356. type="primary"
  357. plain
  358. onClick={() => {
  359. swipeRef.value?.prev()
  360. }}
  361. >
  362. 上一题
  363. </Button>
  364. )}
  365. <Button
  366. block
  367. round
  368. type="primary"
  369. onClick={onNextQuestion}
  370. loading={state.nextStatus}
  371. disabled={state.nextStatus}
  372. >
  373. {state.questionList.length === state.currentIndex + 1 ? '测试完成' : '下一题'}
  374. </Button>
  375. <Image
  376. src={iconButtonList}
  377. class={[styles.wapList, 'van-haptics-feedback']}
  378. onClick={() => (state.visiableAnswer = true)}
  379. />
  380. </div>
  381. </OSticky>
  382. {/* 题目集合 */}
  383. <ActionSheet v-model:show={state.visiableAnswer} title="题目列表" safeAreaInsetBottom>
  384. <AnswerList
  385. value={state.questionList}
  386. onSelect={(item: any) => {
  387. // 跳转,并且跳过动画
  388. swipeRef.value?.swipeTo(item, {
  389. immediate: true
  390. })
  391. state.visiableAnswer = false
  392. }}
  393. />
  394. </ActionSheet>
  395. <Popup
  396. v-model:show={state.visiableResult}
  397. closeOnClickOverlay={false}
  398. style={{ background: 'transparent', width: '96%' }}
  399. >
  400. <ResultFinish
  401. status={state.resultStatusType as any}
  402. result={state.resultInfo}
  403. confirmButtonText="去练习"
  404. cancelButtonText="我知道了"
  405. onClose={() => {
  406. state.visiableResult = false
  407. router.back()
  408. router.back()
  409. }}
  410. onConform={() => {
  411. state.visiableResult = false
  412. router.back()
  413. router.back()
  414. }}
  415. />
  416. </Popup>
  417. <ODialog
  418. v-model:show={state.visiableSure}
  419. title="测验完成"
  420. message="确认本次测验的题目都完成了吗?\n提交后不可修改哦"
  421. messageAlign="left"
  422. showCancelButton
  423. cancelButtonText="再等等"
  424. confirmButtonText="确认完成"
  425. onConfirm={onConfirmExam}
  426. />
  427. <ODialog
  428. v-model:show={state.visiableExam}
  429. message="考试已结束"
  430. messageAlign="center"
  431. onConfirm={async () => {
  432. onAfter()
  433. state.visiableResult = true
  434. }}
  435. />
  436. <ODialog
  437. v-model:show={state.quitStatus}
  438. title="提示"
  439. message="您是否退出本次测验?"
  440. confirmButtonText="确认完成"
  441. showCancelButton
  442. cancelButtonText="取消"
  443. onCancel={() => {
  444. window.history.pushState(null, '', document.URL)
  445. window.addEventListener('popstate', onBack, false)
  446. }}
  447. onConfirm={() => {
  448. onAfter()
  449. }}
  450. />
  451. </div>
  452. )
  453. }
  454. })