import { ActionSheet, Button, Cell, Icon, Image, Swipe, SwipeItem } from 'vant'
import { defineComponent, onMounted, reactive, ref, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import iconQuestionNums from '../images/icon-question-nums.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 DragQuestion from '../model/drag-question'
import KeepLookQuestion from '../model/keep-look-question'
import PlayQuestion from '../model/play-question'
import request from '@/helpers/request'
import { QuestionType } from '../unit'
import { useRect } from '@vant/use'
import { state as baseState } from '@/state'

export default defineComponent({
  name: 'unit-detail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const swipeRef = ref()
    const state = reactive({
      id: route.query.id,
      examDetail: {} as any,
      visiableAnswer: false,
      currentIndex: 0,
      questionList: [],
      time: 0,
      resultInfo: {} as any,
      answerResult: [] as any,
      nextStatus: false,
      swipeHeight: 'auto' as any
    })

    // 学生端查看详情
    const getExamDetails = async () => {
      try {
        const { data } = await request.post('/api-student/studentUnitExamination/detail', {
          requestType: 'form',
          data: {
            studentUnitExaminationId: state.id
          }
        })
        const { questionJson, studentAnswerJson, answerResult, ...res } = data
        const temp = questionJson || []
        temp.forEach((item: any) => {
          item.userAnswer = formatUserAnswers(item, studentAnswerJson)
          item.showAnalysis = true
          item.analysis = {
            message: item.answerAnalysis,
            topic: true, // 是否显示结果
            userResult: formatUserResult(item.id) // 用户答题对错
          }
        })
        // 问题列表
        state.questionList = temp
        // 正确答案
        state.answerResult = answerResult ? JSON.parse(answerResult) : []

        // 详情
        state.examDetail = { ...res } || {}
      } catch {
        //
      }
    }

    const getExamTeaherDetails = async () => {
      try {
        const { data } = await request.post('/api-teacher/classGroupUnitExamination/report', {
          requestType: 'form',
          data: {
            classGroupUnitExaminationId: state.id,
            level: route.query.level
          }
        })
        console.log(data)
        // const { questionJson, studentAnswerJson, answerResult, ...res } = data
        state.examDetail = {
          unitExaminationName: data.unitExaminationName,
          questionNum: data.questionNum || 0
        }
        // 问题列表
        const temp = data.examinationQuestionAdds || []
        temp.forEach((item: any) => {
          item.userAnswer = formatTeacherAnswer(item.answers)
          item.showAnalysis = true
          item.showRate = true
          item.analysis = {
            message: item.answerAnalysis,
            topic: false // 是否显示结果
          }
        })
        // 问题列表
        state.questionList = temp
        // 正确答案
      } catch {
        //
      }
    }
    /**
     * @description 初始化正确答案
     */
    const formatTeacherAnswer = (answers: any) => {
      console.log(answers)
      const result: any = []
      answers.forEach((answer: any) => {
        // rightAnswerFlag 说明是正确的
        if (answer.rightAnswerFlag) {
          const rightOption = answers.find(
            (item: any) => item.questionExtra === answer.questionExtra
          )

          result.push({
            answer: answer.questionAnswer,
            answerId: answer.examinationQuestionAnswerId,
            answerExtra: rightOption ? rightOption.questionExtra : null
          })
        }
      })
      return result || []
    }

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

    /**
     * @description 检查用户是否答对
     * @returns Boolean
     */
    const formatUserResult = (id: string) => {
      let result = false
      state.answerResult.forEach((item: any) => {
        if (item.questionId === id) {
          result = item.rightFlag
        }
      })
      return result
    }

    /**
     * @description 重置当前的题目高度
     */
    const resizeSwipeItemHeight = () => {
      nextTick(() => {
        window.scrollTo(0, 0)
        setTimeout(() => {
          const currentItemDom: Element =
            document.querySelectorAll('.swipe-item-question')[state.currentIndex]
          const rect = useRect(currentItemDom)
          state.swipeHeight = rect.height
        }, 100)
      })
    }

    /**
     * @description 下一题 | 测试完成
     */
    const onNextQuestion = async () => {
      try {
        state.nextStatus = true
        if (state.questionList.length === state.currentIndex + 1) {
          router.back()
        }
        swipeRef.value?.next()
        state.nextStatus = false
      } catch {
        //
        state.nextStatus = false
      }
    }

    onMounted(async () => {
      if (baseState.platformType === 'TEACHER') {
        await getExamTeaherDetails()
      } else {
        await getExamDetails()
      }

      // 初始化高度
      resizeSwipeItemHeight()
    })

    return () => (
      <div class={styles.unitDetail}>
        <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 || 0}
                </div>
              </div>
            )
          }}
        </Cell>

        <Swipe
          loop={false}
          showIndicators={false}
          ref={swipeRef}
          duration={300}
          touchable={false}
          lazyRender
          style={{ paddingBottom: '12px' }}
          height={state.swipeHeight}
          onChange={(index: number) => {
            state.currentIndex = index
            resizeSwipeItemHeight()
          }}
        >
          {state.questionList.map(
            (item: any, index: number) =>
              item.questionTypeCode === QuestionType.CHECKBOX && (
                <SwipeItem>
                  <ChoiceQuestion
                    v-model:value={item.userAnswer}
                    index={index + 1}
                    data={item}
                    readOnly
                    type="checkbox"
                    showRate={item.showRate}
                    showAnalysis={item.showAnalysis}
                    analysis={item.analysis}
                  />
                </SwipeItem>
              )
            // <SwipeItem>
            //   <div class="swipe-item-question">
            //     {item.questionTypeCode === QuestionType.RADIO && (
            //       <ChoiceQuestion
            //         v-model:value={item.userAnswer}
            //         index={index + 1}
            //         data={item}
            //         readOnly
            //         type="radio"
            //         showRate={item.showRate}
            //         showAnalysis={item.showAnalysis}
            //         analysis={item.analysis}
            //       />
            //     )}
            //     {item.questionTypeCode === QuestionType.CHECKBOX && (
            //       <ChoiceQuestion
            //         v-model:value={item.userAnswer}
            //         index={index + 1}
            //         data={item}
            //         readOnly
            //         type="checkbox"
            //         showRate={item.showRate}
            //         showAnalysis={item.showAnalysis}
            //         analysis={item.analysis}
            //       />
            //     )}
            //     {item.questionTypeCode === QuestionType.SORT && (
            //       <DragQuestion
            //         readOnly
            //         v-model:value={item.userAnswer}
            //         data={item}
            //         index={index + 1}
            //         showRate={item.showRate}
            //         showAnalysis={item.showAnalysis}
            //         analysis={item.analysis}
            //       />
            //     )}
            //     {item.questionTypeCode === QuestionType.LINK && (
            //       <KeepLookQuestion
            //         readOnly
            //         v-model:value={item.userAnswer}
            //         data={item}
            //         index={index + 1}
            //         showRate={item.showRate}
            //         showAnalysis={item.showAnalysis}
            //         analysis={item.analysis}
            //       />
            //     )}
            //     {item.questionTypeCode === QuestionType.PLAY && (
            //       <PlayQuestion
            //         readOnly
            //         v-model:value={item.userAnswer}
            //         data={item}
            //         index={index + 1}
            //         unitId={state.id as any}
            //         showRate={item.showRate}
            //         showAnalysis={item.showAnalysis}
            //         analysis={item.analysis}
            //       />
            //     )}
            //   </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}
            answerResult={state.answerResult}
            index={state.currentIndex}
            lookType={baseState.platformType === 'STUDENT' ? 'RESULT' : 'CLICK'}
            statusList={
              baseState.platformType === 'STUDENT'
                ? [
                    {
                      text: '答对',
                      color: '#71B0FF'
                    },
                    {
                      text: '答错',
                      color: '#FF8486'
                    }
                  ]
                : []
            }
            onSelect={(item: any) => {
              // 跳转，并且跳过动画
              swipeRef.value?.swipeTo(item, {
                immediate: true
              })
              state.visiableAnswer = false
            }}
          />
        </ActionSheet>
      </div>
    )
  }
})
