<template>
    
    <div class="mt-10 max-w-2xl mx-auto p-4  border-gray-400 ">
        <button @click="backAction" class="mt-5  border px-3 py-1 border-gray-300 rounded-xl text-[gray]">back</button>
      <!-- 顶部：进度与操作 -->
      <div class="flex items-center justify-between mb-4 mt-5">
        <div class="text-sm text-gray-500">
          Progress: {{ currentIndex + 1 }} / {{ total }}
        </div>
        <!-- <div class="flex items-center gap-2">
          <button
            class="px-3 py-1 rounded border"
            :disabled="currentIndex === 0"
            @click="goPrev"
          >Previous</button>
  
          <button
            v-if="!isLast"
            class="px-3 py-1 rounded border"
            :disabled="!answers[current.id]"
            @click="goNext"
          >Next</button>
  
          <button
            v-else
            class="px-3 py-1 rounded border bg-green-600 text-white disabled:opacity-50"
            :disabled="!isAllAnswered"
            @click="submit"
          >submit</button>
        </div> -->
      </div>
  
      <!-- 题干 -->
      <div class="mb-3 text-lg font-medium">
        {{ current.title }}
      </div>
      <div v-if="current.desc" class="mb-3 text-gray-500 text-sm">
        {{ current.desc }}
      </div>
  
      <!-- 选项（单选） -->
      <div class="space-y-2">
        <label
          v-for="(opt,index) in current.options"
          :key="'home_' + current.id"
          class="flex items-center gap-3 p-3 border rounded border-gray-300 hover:bg-gray-50 cursor-pointer"
        >
          <input
            type="radio"
            class="h-4 w-4"
            :name="'q_' + current.id"
            :value="opt.value"
            v-model="answers[current.id]"
            @change="onSelect(current.id,index)"
          />
          <span class="select-none">{{ opt.label }}</span>
        </label>
      </div>
  
      <!-- 底部：题号导航（可选） -->
      <div class="mt-6 flex flex-wrap gap-2">
        <button
          v-for="(q, idx) in questions"
          :key="q.id"
          class="w-9 h-9 rounded-full border text-sm"
          :class="{
            'bg-blue-600 text-white border-blue-600': idx === currentIndex,
            'bg-green-600 text-white border-green-600': idx !== currentIndex && answers[q.id],
          }"
          @click="jump(idx)"
          :title="answers[q.id] ? '已作答' : '未作答'"
        >
          {{ idx + 1 }}
        </button>
      </div>

      <div class="flex mt-10 items-center gap-2">
          <button
            class="px-3 py-1 rounded border"
            :disabled="currentIndex === 0"
            @click="goPrev"
          >Previous</button>
  
          <button
            v-if="!isLast"
            class="px-3 py-1 rounded border"
            :disabled="!answers[current.id]"
            @click="goNext"
          >Next</button>
  
          <button
            v-else
            class="px-3 py-1 rounded border bg-green-600 text-white disabled:opacity-50"
            :disabled="!isAllAnswered"
            @click="submit"
          >submit</button>
        </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { computed, ref, watch, onMounted } from 'vue'
  import { useRouter } from 'vue-router';
  

  const router = useRouter()

  const answerList = ref<Record<string, number>>({})  /**
   * 可复用答题卡
   * Props:
   *  - questions: 题目数组
   *      [{ id: string|number, title: string, desc?: string,
   *         options: [{ value: string|number, label: string }] }]
   *  - storageKey?: 本地保存 key，默认基于题目生成
   *  - autoAdvance?: 选中后是否自动跳下一题（默认 true）
   */
  interface Option { value: string | number; label: string }
  interface Question {
    id: string | number
    title: string
    desc?: string
    options: Option[]
  }
  
  const props = withDefaults(defineProps<{
    questions: Question[],
    storageKey?: string,
    autoAdvance?: boolean
  }>(), {
    autoAdvance: true
  })
  
  const total = computed(() => props.questions.length)
  const currentIndex = ref(0)
  const answers = ref<Record<string | number, string | number>>({})
  
  const key = computed(() =>
    props.storageKey || `quiz_${hashQuestions(props.questions)}`
  )
  
  const current = computed(() => props.questions[currentIndex.value])
  const isLast = computed(() => currentIndex.value === total.value - 1)
  const isAllAnswered = computed(() =>
    props.questions.every(q => !!answers.value[q.id])
  )
  
  // 恢复本地作答,注释掉的是恢复本地作答， 现在不要本地作答
  onMounted(() => {
    // const raw = localStorage.getItem(key.value)
    // if (raw) {
    //   try {
    //     const saved = JSON.parse(raw)
    //     if (saved?.answers) answers.value = saved.answers
    //     if (typeof saved?.index === 'number') currentIndex.value = clamp(saved.index, 0, total.value - 1)
    //   } catch {}
    // }
    // ① 先清空之前的缓存（关键）
    localStorage.removeItem(key.value)
    // ② 然后按原逻辑初始化（这时 raw 会是 null）
    const raw = localStorage.getItem(key.value)
    if (raw) {
        try {
            const saved = JSON.parse(raw)
            if (saved?.answers) answers.value = saved.answers
            console.log('现在存储的answer的值是：',answers.value)
            if (typeof saved?.index === 'number') {
            currentIndex.value = clamp(saved.index, 0, total.value - 1)
            }
        } catch {}
    } else {
        // 没有缓存时重置
        answers.value = {}
        currentIndex.value = 0
    }

  })
  
  // 同步保存
  watch([answers, currentIndex], () => {
    // console.log('answers的值是',answers.value)
    localStorage.setItem(key.value, JSON.stringify({
      answers: answers.value,
      index: currentIndex.value
    }))
  }, { deep: true })
  
  function onSelect(ID:any,Index:any) {
    answerList.value[String(ID)] = Number(Index)
    // console.log('选择的答案列表：',answerList.value)
    // 选中选项后自动跳下一题（不是最后一题）
    if (props.autoAdvance && !isLast.value) goNext()
  }
  
  function goNext() {
    // console.log('当前的数据====',current)
    setTimeout(()=>{
      currentIndex.value = clamp(currentIndex.value + 1, 0, total.value - 1)
    },300)
  }
  function goPrev() {
    currentIndex.value = clamp(currentIndex.value - 1, 0, total.value - 1)
  }
  function jump(idx: number) {
    currentIndex.value = clamp(idx, 0, total.value - 1)
  }
  function submit() {
    // 提交时抛出完整结果
    // const payload = props.questions.map(q => ({
    //   id: q.id,
    //   answer: answers.value[q.id] ?? null
    // }))
    // 你也可以在这里计算得分（如果提供正确答案）
    // console.log(JSON.stringify(answerList.value))
    emit('submit',JSON.stringify(answerList.value))
    setTimeout(()=>{
      localStorage.removeItem(key.value)
    },500)
  }
  
  const emit = defineEmits<{
    // submit: [payload: Array<{ id: Question['id'], answer: Option['value'] | null }>]
    submit: [payload: any]
  }>()
  
  function clamp(v: number, min: number, max: number) {
    return Math.min(Math.max(v, min), max)
  }
  
  // 基于题目内容生成一个简易 hash，作为默认 storageKey
  function hashQuestions(list: Question[]) {
    const str = JSON.stringify(list.map(q => ({
      id: q.id, title: q.title, options: q.options?.map(o => o.value)
    })))
    let h = 2166136261
    for (let i = 0; i < str.length; i++) {
      h ^= str.charCodeAt(i)
      h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)
    }
    return (h >>> 0).toString(16)
  }

  const backAction = () => {
    router.back()
  }
  </script>
  
  <style scoped>
  button:disabled { opacity: .5; cursor: not-allowed; }
  </style>
  