<script setup lang="js">
import QuizSheet from '@/view/components/QuizSheet.vue'
import { onMounted,ref } from 'vue'
import {registerAnwerDetailApi,getPersonInfo,registerAnswerApi} from '@/http/register.js'
import {getToken,setLogin} from '@/utils/local.js'
import {adaptQuestions} from '@/utils/util.js'
import { useRoute,useRouter } from 'vue-router'

const questions = ref([])
const personInfo = ref({})
const route = useRoute()
const router = useRouter()

const loading = ref(false)

const zipCode   = route.query.zipCode || ''
const birthDate = route.query.birthDate  || ''
const sex       = route.query.sex  || ''
const firstName = route.query.firstName  || ''
const lastName  = route.query.lastName  || ''

// 提交回调
async function handleSubmit(payload) {
  console.log('提交结果：', payload)
  // 比如发送到后端：
  // await request.post('/api/submit', payload)
  const myToken = getToken()
  const dict = {
    first_name:firstName,
    next_name:lastName,
    zipcode:zipCode,
    sex:sex,
    birthday:birthDate,
    answer_list:payload
  }
  try{
    loading.value = true
    const res = await registerAnswerApi(myToken,dict)
    loading.value = false
    if(res.code == 1){
      setLogin('anwerAndLogin')
      // router.replace('/home')
      router.replace('/home')
    }
  }catch(err){
    loading.value = false
  }

}

async function getAnswerList() {
  try{
    loading.value = true
    const myToken = getToken()
    const res = await registerAnwerDetailApi(myToken)
    loading.value = false
    if(res.code == 1){
        questions.value =  adaptQuestions(res.data.list)
        // console.log('问题列表是:',questions.value)
    }
  }catch(err){
    loading.value = false
  }
}
async function getPerson() {
    const myToken = getToken()
    const res = await getPersonInfo(myToken)
    if(res.code == 1){
        personInfo.value = res.data
    }
}

onMounted(() => {
    getAnswerList()
    // getPerson()
})

</script>

<template>
  <div v-loading="loading" v-if="loading" style="height: 100vh;" class="w-full flex justify-center items-center"></div>
  <QuizSheet
  v-else
    v-if="questions.length > 0"
    :questions="questions"
    storageKey="quiz_demo_v1"     
    @submit="handleSubmit"
  />
</template>
