import { defineComponent, onMounted, reactive, ref, watchEffect } from 'vue'
import { useOriginSearch } from '../uses'
import request from '/src/helpers/request'
import SettingState from '/src/pages/detail/setting-state'
import runtime, { changeSpeed } from '/src/pages/detail/runtime'
import state from '/src/pages/detail/state'
import { Toast } from 'vant'
import { userInfo } from '../App'
import { browser } from '/src/helpers/utils'
import { setSettionBackground } from '/src/pages/detail/helpers'

interface IquestionExtendsInfo {
  /** 评测难度 */
  difficulty?: 'ONE' | 'TWO' | 'THREE' | '1' | '2' | '3' | ''
  /** 开始小节 */
  start?: string | number
  /** 结束小节 */
  end?: string | number
  /** 速度 */
  speed?: number
}
const difficultyData: { [_: string]: any } = {
  ONE: 'BEGINNER',
  TWO: 'ADVANCED',
  THREE: 'PERFORMER',
  '1': 'BEGINNER',
  '2': 'ADVANCED',
  '3': 'PERFORMER',
}

export const unitTestData = reactive({
  /** 是否是选段模式 */
  isSelectMeasureMode: false,
})

export default defineComponent({
  name: 'unitTest',
  setup() {
    const questionExtendsInfo = ref<IquestionExtendsInfo>({difficulty: ''})
    /**
     * 如果是课后训练或者单元测验,获取数据
     * @param xml 获取的xml数据
     * @returns 格式化的xml数据
     */
    const getUnitData = async () => {
      const search = useOriginSearch()
      if (!search.questionId) return ''
      
      try {
        const res: any = await request.get(`/examinationQuestion/detail?examinationQuestionId=${search.questionId}`)
        questionExtendsInfo.value = JSON.parse(res?.data?.questionExtendsInfo) || {}
        questionExtendsInfo.value.start = Number(questionExtendsInfo.value.start)
        questionExtendsInfo.value.end = Number(questionExtendsInfo.value.end)
      } catch (error) {
        console.error('解析单元测验曲谱题目失败', error)
      }
      setSection()
    }
    
    const getlessonTrainingData = async () => {
      const search = useOriginSearch()
      if (!search.lessonTrainingId) return
      try {
        const res: any = await request.post(`/studentLessonTraining/trainingRecord/${search.courseScheduleId}?userId=${userInfo.id}`)
        if (Array.isArray(res?.data?.trainingDetails)){
          // bug：#8731 trainings 替换为 trainingDetails
          const train = res.data.trainingDetails.find((n: any) => n.materialId == search.materialId)
          const info = JSON.parse(train.trainingContent)
          // console.log("🚀 ~ info", info)
          questionExtendsInfo.value.start = Number(info.startSection)
          questionExtendsInfo.value.end = Number(info.endSection)
          questionExtendsInfo.value.speed = isNaN(info.speed) ? 0 : Number(info.speed)
        }
      } catch (error) {
        console.error('解析课后训练曲谱题目失败', error)
      }
      setSection()
    }

    /**设置小节 */
    const setSection = () => {
      const startNotes = state.times.filter(
        (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == questionExtendsInfo.value.start
      )
      const endNotes = state.times.filter(
        (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == questionExtendsInfo.value.end
      )
      const startNote = startNotes[0]
      // const endNote = endNotes[endNotes.length - 1]
      const endNote = endNotes[0]
      // console.log('🚀 ~ activeNote', startNote, endNote, questionExtendsInfo.value.end)
      if (startNote && endNote) {
        unitTestData.isSelectMeasureMode = true
        // 设置小节
        state.sectionStatus = true
        state.section = [startNote, endNote]
        // 设置评测难度
        if (difficultyData[questionExtendsInfo.value.difficulty!]) {
          SettingState.eva.difficulty = difficultyData[questionExtendsInfo.value.difficulty!]
        }
        //设置速度
        if (questionExtendsInfo.value.speed) {
          changeSpeed(questionExtendsInfo.value.speed)
        }
        setSettionBackground()
      }
    }
    onMounted(() => {
      const browserInfo = browser()
      //如果不是学生端直接return
      if (!browserInfo.isStudent) return
      getUnitData()
      getlessonTrainingData()
    })
    watchEffect(() => {
      // 监听是否需要刷新section小节
      if (state.isNeedRefreshSection) {
        setSection()
        state.isNeedRefreshSection = false
      }
    })    
    return () => ''
  },
})
