import {
  ActionSheet,
  Button,
  Cell,
  CountDown,
  Icon,
  Image,
  Popup,
  showDialog,
  Swipe,
  SwipeItem,
  Tag
} from 'vant'
import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import iconQuestionNums from '../images/icon-question-nums.png'
import iconCountDown from '../images/icon-count-down.png'
import iconButtonList from '../images/icon-button-list.png'
import OSticky from '@/components/o-sticky'
import ChoiceQuestion from '../model/choice-question'
import AnswerList from '../model/answer-list'
import ODialog from '@/components/o-dialog'
import DragQuestion from '../model/drag-question'
import KeepLookQuestion from '../model/keep-look-question'
import PlayQuestion from '../model/play-question'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import ResultFinish from '../model/result-finish'
import { eventUnit, QuestionType } from '../unit'
import { useRect } from '@vant/use'
import { useInterval } from '@vueuse/core'
import OHeader from '@/components/o-header'

export default defineComponent({
  name: 'unit-detail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const countDownRef = ref()
    const swipeRef = ref()
    const state = reactive({
      id: route.query.id,
      examDetail: {} as any,
      visiableAnswer: false,
      currentIndex: 0,
      questionList: [],
      time: 0,
      visiableSure: false,
      visiableResult: false,
      resultInfo: {} as any,
      resultStatusType: 'SUCCESS', // 'SUCCESS' | 'FAIL'
      visiableExam: false, // 考试已结束
      nextStatus: false,
      swipeHeight: 'auto' as any,
      quitStatus: false
    })

    // 计时
    // const { counter, resume, pause } = useInterval(1000, { controls: true })

    // watch(
    //   () => counter.value,
    //   async () => {
    //     console.log(counter.value, state.time / 1000, dayjs().format('HH:mm:ss'))
    //     // 秒
    //     if (counter.value >= state.time / 1000) {
    //       pause()
    //       eventUnit.emit('unitAudioStop')
    //       await onConfirmExam()
    //       state.visiableExam = true
    //     }
    //   }
    // )

    const getExamDetails = async () => {
      try {
        const { data } = await request.post(
          '/api-student/studentUnitExamination/startExamination',
          {
            requestType: 'form',
            data: {
              studentUnitExaminationId: state.id
            }
          }
        )
        const { questionJson, studentAnswerJson, ...res } = data
        const temp = questionJson || []
        temp.forEach((item: any) => {
          item.userAnswer = formatUserAnswers(item, studentAnswerJson)
        })
        state.questionList = temp

        state.examDetail = { ...res } || {}

        calcTime()
      } catch {
        //
      }
    }

    /**
     * @description 计算考试时间剩余时间
     */
    const calcTime = async () => {
      const examDetail = state.examDetail || {}
      const startTime = examDetail.startTime
      const nowTime = examDetail.now
      const timeMinutes = examDetail.timeMinutes || 0 // 测验时间
      // 返回秒
      const minu = dayjs(startTime).add(timeMinutes, 'minute').diff(dayjs(nowTime))
      // 时间到了考试结束
      if (minu <= 0) {
        eventUnit.emit('unitAudioStop')
        await afterQuestion()
        state.visiableExam = true
      } else {
        // pause()
        state.time = Math.ceil(minu / 1000) * 1000
        setTimeout(() => {
          countDownRef.value?.start()
          // resume()
        }, 10)
      }
    }

    /**
     * @description 初始化用户答案
     */
    const formatUserAnswers = (item: any, userAnswer: any) => {
      // 判断是否有结果
      if (!userAnswer) return []
      const answers = userAnswer || []
      return answers[item.id] ? answers[item.id] : []
    }

    /**
     * @description 重置当前的题目高度
     */
    let size = 0
    const resizeSwipeItemHeight = (scroll = true) => {
      nextTick(() => {
        scroll && window.scrollTo(0, 0)
        setTimeout(() => {
          // const currentItemDom: Element =
          //   document.querySelectorAll('.swipe-item-question')[state.currentIndex]
          const currentItemDom: any = document
            .querySelectorAll('.van-swipe-item')
            [state.currentIndex]?.querySelector('.swipe-item-question')

          const allImg = currentItemDom.querySelectorAll('.answerTitleImg img')
          let status = true
          // console.log(allImg)
          allImg.forEach((img: any) => {
            console.log(img.complete)
            if (!img.complete) {
              status = false
            }
          })
          // 判断图片是否加载完了
          if (!status && size < 3) {
            setTimeout(() => {
              size += 1
              resizeSwipeItemHeight(scroll)
            }, 300)
          }
          if (status) {
            size = 0
          }

          const rect = useRect(currentItemDom)
          state.swipeHeight = rect.height
        }, 100)
      })
    }

    /**
     * @description 下一题 | 测试完成
     */
    const onNextQuestion = async () => {
      try {
        const questionList = state.questionList || []
        const userAnswerList: any = [] // 所有题目的答案
        // let currentResult = false // 当前题目是否已经答题
        questionList.forEach((question: any, index: number) => {
          // 格式化所有题目的答案
          if (question.userAnswer && question.userAnswer.length > 0) {
            userAnswerList.push({
              questionId: question.id,
              details: question.userAnswer
            })
          }
        })

        // 判断是否是最后一题
        // console.log(state.questionList.length, state.currentIndex, userAnswerList, '-----')
        if (state.questionList.length === state.currentIndex + 1) {
          eventUnit.emit('unitAudioStop')
          state.visiableSure = true
          return
        }

        state.nextStatus = true
        await request.post('/api-student/studentUnitExamination/submitAnswer', {
          hideLoading: true,
          data: {
            answers: userAnswerList,
            studentUnitExaminationId: state.id
          }
        })
        swipeRef.value?.next()

        state.nextStatus = false
      } catch {
        //
        state.nextStatus = false
      }
    }

    /**
     * @description 提交最终答案
     */
    const onConfirmExam = async () => {
      try {
        await afterQuestion()
        onAfter()
        // if (status) {
        state.visiableResult = true
        // }
      } catch {
        //
      }
    }

    const afterQuestion = async () => {
      try {
        const questionList = state.questionList || []
        const userAnswerList: any = [] // 所有题目的答案
        questionList.forEach((question: any) => {
          // 格式化所有题目的答案
          if (question.userAnswer && question.userAnswer.length > 0) {
            userAnswerList.push({
              questionId: question.id,
              details: question.userAnswer
            })
          }
        })
        const { data } = await request.post(
          '/api-student/studentUnitExamination/completionExamination',
          {
            hideLoading: false,
            data: {
              answers: userAnswerList,
              studentUnitExaminationId: state.id
            }
          }
        )
        if (data.status === 'A_PASS') {
          state.resultStatusType = 'SUCCESS'
          state.resultInfo = {
            tips: '恭喜你，测验通过！',
            score: data.score,
            examName: state.examDetail.unitExaminationName
          }
        } else {
          state.resultStatusType = 'FAIL'
          state.resultInfo = {
            tips: '本次测验不合格！',
            score: data.score,
            examName: state.examDetail.unitExaminationName
          }
        }
      } catch {
        //
      }
    }

    // 拦截
    const onBack = () => {
      // showDialog({
      //   title: '提示',
      //   message: '您考试还未提交，是否退出？',
      //   theme: 'round-button',
      //   confirmButtonColor: '#ff8057'
      // }).then(() => {
      //   onAfter()
      //   router.back()
      // })
      state.quitStatus = true
      eventUnit.emit('unitAudioStop')
    }

    const onAfter = () => {
      window.removeEventListener('popstate', onBack, false)
      router.back()
    }

    onMounted(async () => {
      await getExamDetails()

      // 初始化高度
      resizeSwipeItemHeight()

      window.history.pushState(null, '', document.URL)
      window.addEventListener('popstate', onBack, false)
    })

    onUnmounted(() => {
      eventUnit.emit('unitAudioStop')
    })

    return () => (
      <div class={styles.unitDetail}>
        <OHeader />
        <Cell center class={styles.unitSection} border={false}>
          {{
            title: () => <div class={styles.unitTitle}>{state.examDetail.unitExaminationName}</div>,
            label: () => (
              <div class={styles.unitCount}>
                <div class={styles.qNums}>
                  <Icon class={styles.icon} name={iconQuestionNums} />
                  题目数量{' '}
                  <span class={styles.num} style={{ paddingLeft: '6px' }}>
                    {state.currentIndex + 1}
                  </span>
                  /{state.examDetail.questionNum}
                </div>
                <div class={styles.qNums}>
                  <Icon class={styles.icon} name={iconCountDown} />
                  剩余时长：
                  <CountDown
                    ref={countDownRef}
                    v-model:time={state.time}
                    format={'mm:ss'}
                    autoStart={false}
                    onFinish={async () => {
                      eventUnit.emit('unitAudioStop')
                      await afterQuestion()
                      state.visiableExam = true
                    }}
                  />
                </div>
              </div>
            )
          }}
        </Cell>

        <Swipe
          loop={false}
          showIndicators={false}
          ref={swipeRef}
          duration={300}
          touchable={false}
          height={state.swipeHeight}
          style={{ marginBottom: '12px' }}
          lazyRender
          onChange={(index: number) => {
            eventUnit.emit('unitAudioStop')
            state.currentIndex = index
            resizeSwipeItemHeight()
          }}
        >
          {state.questionList.map((item: any, index: number) => (
            // item.questionTypeCode === QuestionType.LINK && (
            //   <SwipeItem>
            //     <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
            //   </SwipeItem>
            // )
            <SwipeItem>
              <div class="swipe-item-question">
                {item.questionTypeCode === QuestionType.RADIO && (
                  <ChoiceQuestion
                    v-model:value={item.userAnswer}
                    index={index + 1}
                    data={item}
                    type="radio"
                  />
                )}
                {item.questionTypeCode === QuestionType.CHECKBOX && (
                  <ChoiceQuestion
                    v-model:value={item.userAnswer}
                    index={index + 1}
                    data={item}
                    type="checkbox"
                  />
                )}
                {item.questionTypeCode === QuestionType.SORT && (
                  <DragQuestion
                    v-model:value={item.userAnswer}
                    onUpdate:value={() => {
                      resizeSwipeItemHeight(false)
                    }}
                    data={item}
                    index={index + 1}
                  />
                )}
                {item.questionTypeCode === QuestionType.LINK && (
                  <KeepLookQuestion v-model:value={item.userAnswer} data={item} index={index + 1} />
                )}
                {item.questionTypeCode === QuestionType.PLAY && (
                  <PlayQuestion
                    v-model:value={item.userAnswer}
                    data={item}
                    index={index + 1}
                    unitId={state.id as any}
                  />
                )}
              </div>
            </SwipeItem>
          ))}
        </Swipe>

        <OSticky position="bottom" background="white">
          <div class={['btnGroup btnMore']}>
            {state.currentIndex > 0 && (
              <Button
                round
                block
                type="primary"
                plain
                onClick={() => {
                  swipeRef.value?.prev()
                }}
              >
                上一题
              </Button>
            )}
            <Button
              block
              round
              type="primary"
              onClick={onNextQuestion}
              loading={state.nextStatus}
              disabled={state.nextStatus}
            >
              {state.questionList.length === state.currentIndex + 1 ? '测试完成' : '下一题'}
            </Button>
            <Image
              src={iconButtonList}
              class={[styles.wapList, 'van-haptics-feedback']}
              onClick={() => (state.visiableAnswer = true)}
            />
          </div>
        </OSticky>

        {/* 题目集合 */}
        <ActionSheet v-model:show={state.visiableAnswer} title="题目列表" safeAreaInsetBottom>
          <AnswerList
            value={state.questionList}
            onSelect={(item: any) => {
              // 跳转，并且跳过动画
              swipeRef.value?.swipeTo(item, {
                immediate: true
              })
              state.visiableAnswer = false
            }}
          />
        </ActionSheet>

        <Popup
          v-model:show={state.visiableResult}
          closeOnClickOverlay={false}
          style={{ background: 'transparent', width: '96%' }}
        >
          <ResultFinish
            status={state.resultStatusType as any}
            result={state.resultInfo}
            confirmButtonText="去练习"
            cancelButtonText="我知道了"
            onClose={() => {
              state.visiableResult = false
              router.back()
              router.back()
            }}
            onConform={() => {
              state.visiableResult = false
              router.back()
              router.back()
            }}
          />
        </Popup>

        <ODialog
          v-model:show={state.visiableSure}
          title="测验完成"
          message="确认本次测验的题目都完成了吗？\n提交后不可修改哦"
          messageAlign="left"
          showCancelButton
          cancelButtonText="再等等"
          confirmButtonText="确认完成"
          onConfirm={onConfirmExam}
        />

        <ODialog
          v-model:show={state.visiableExam}
          message="考试已结束"
          messageAlign="center"
          onConfirm={async () => {
            onAfter()
            state.visiableResult = true
          }}
        />

        <ODialog
          v-model:show={state.quitStatus}
          title="提示"
          message="您是否退出本次测验？"
          confirmButtonText="确认退出"
          showCancelButton
          cancelButtonText="取消"
          onCancel={() => {
            window.history.pushState(null, '', document.URL)
            window.addEventListener('popstate', onBack, false)
          }}
          onConfirm={() => {
            onAfter()
          }}
        />
      </div>
    )
  }
})
