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

const questions = ref([])
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const person = ref({})

const id = route.query.id || ''
const title = route.query.title || ''
const questionStr = route.query.questionStr || ''
questions.value = [{
    id:id,
    title:title,
    options:JSON.parse(questionStr)
}]
// console.log('options的值是',questions.value)

// 提交回调
async function handleSubmit(payload) {
    const merged = Object.assign({}, JSON.parse(person.value.answer_list), JSON.parse(payload));
    
    // const merged = {0: 0, 1: 2, 2: 2, 3: 4, 4:0, 5: 0, 6: 0, 7: 0, 8: 1, 9: 0, 10: 1, 11: 0, 12: 1, 13: 0, 14: 0, 15: 0, 16: 6}
    // console.log('替换成功了吗',merged)
    // return
    loading.value = true

    const myToken = getToken()
    const dict = {
        first_name:person.value.first_name,
        next_name:person.value.next_name,
        sex:person.value.sex,
        zipcode:person.value.zipcode,
        answer_list:JSON.stringify(merged),
        birthday:person.value.birthday
    }
    try{
    const res = await registerAnswerApi(myToken,dict)
    loading.value = false
    if(res.code == 1){
        ElMessage.success('success')
        router.back()
    }
  }catch(err){
    loading.value = false
  }
}

async function getHomeAnswerList() {
    loading.value = true
    const myToken = getToken()
    try{
        const res = await wenJuanDetail(myToken,qid)
        loading.value = false
        if(res.code == 1){
            questions.value =  adaptQuestionsHome(res.data.data)
            // console.log('问题列表是:',questions.value)
        }
    }catch(err){
        loading.value = false
    }
}

async function personInfo() {
    const myToken = getToken()
    const res = await getPersonInfo(myToken)
    if(res.code == 1){
        person.value = res.data
    }
}

onMounted(() => {
    // getHomeAnswerList()
    personInfo()
})

</script>

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