<template>
  <Layout>
    <template #title>{{ questionnaire.title }}</template>

    <van-form @submit="onSubmit">
      <van-cell-group :title="`${index + 1}. ${item.question}`" v-for="(item, index) in questionnaire.questions"
        :key="item.id">
        <!-- 单选框 -->
        <van-field v-if="item.type === 'radio'" name="radio">
          <template #input>
            <van-radio-group v-model="item.answer">
              <van-radio v-for="(option, index) in item.options" :key="item.id + index" :name="option.id" class="mb-12">
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 复选框 -->
        <van-field v-if="item.type === 'checkbox'" name="checkboxGroup">
          <template #input>
            <van-checkbox-group v-model="item.answer" shape="square">
              <van-checkbox v-for="(option, index) in item.options" :key="item.id + index" :name="option.id"
                class="mb-12">
                {{ option.text }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <!-- 输入框 -->
        <van-field v-if="item.type === 'text'" v-model="item.answer" placeholder="请填写内容" />

        <!-- 文本域 -->
        <van-field v-if="item.type === 'textarea'" type="textarea" v-model="item.answer" placeholder="请填写内容"
          maxlength="100" show-word-limit />
      </van-cell-group>

      <div class="m-16">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </Layout>
</template>

<script setup name="home">
import { getSurveyQuestionnaireUsingGet, submitSurveyQuestionnaireAnswerUsingPost } from '@api'
import { showToast } from 'vant';



const form = ref({
  surveyId: '',
  answers: []
})

// 跳转按钮操作
const handleClick = () => {
  console.log('跳转记录')
}

const questionnaire = ref({})
const getQuestionnaire = async () => {
  const res = await getSurveyQuestionnaireUsingGet({})

  questionnaire.value = {
    surveyId: res.id,
    title: res.title,
    questions: res.questions.map((item) => ({
      ...item,
      answer: item.type === 'checkbox' ? [] : ''
    }))
  }
}

onMounted(() => getQuestionnaire())

const router = useRouter()
const onSubmit = async () => {
  // 验证表单
  if (questionnaire.value.questions.some((item) => !item.answer)) {
    showToast('请填写完整')
    return
  }

  form.value.surveyId = questionnaire.value.surveyId
  form.value.answers = questionnaire.value.questions.map((item) => ({
    questionId: item.id,
    answer: item.type === 'checkbox' ? item.answer.join(',') : item.answer
  }))
  console.log('onSubmit', form.value)

  const res = await submitSurveyQuestionnaireAnswerUsingPost({ body: form.value })

  if (res) {
    getQuestionnaire()
    form.value.surveyId = ''
    form.value.answers = []

    router.push({ name: 'result' })
  }
}
</script>

<style lang="scss" scoped></style>
