<script setup lang="ts">
import { Notify }                  from '@/platform';
import { questionnaireMethod }     from '@/request/api';
import type { QuestionnaireProps } from '@/request/model';
import { useRequest }              from 'alova/client';

import TierSelectField from './TierSelect.field.vue';


defineOptions({
  name: 'QuestionnairePage',
});

const router = useRouter();

const showTitle = ref(true);
const { data, loading, send } = useRequest((data) => questionnaireMethod(data), {
  initialData: { reportId: null, questionnaires: [] },
}).onSuccess(({ data }) => {
  if ( data.reportId ) router.replace(`/report/${ data.reportId }`);
});


function handle(questionnaires: QuestionnaireProps[]) {
  console.log(questionnaires);
  const tips: string[] = [];
  for ( const { label, required, name, options } of questionnaires ) {
    if ( !required ) continue;
    switch ( name ) {
      case 'select':
        if ( !options.some(op => op.checked) ) tips.push(label);
        break;
    }
  }
  if ( tips.length ) {
    Notify.warning(`问卷请补充完整\n\n${ tips.join('\n') }`);
  } else {
    send(questionnaires).then(() => showTitle.value = false);
  }
}
</script>
<template>
  <div>
    <template v-if="data.questionnaires.length">
      <div v-if="showTitle" class="my-8 text-2xl text-primary text-center">
        <div>为了更全面地评估您的健康状况</div>
        <div>还需要您回答6-9个问题，耗时2-3分钟</div>
      </div>
      <div class="m-6" v-for="item in data.questionnaires" :key="item.id">
        <div class="text-2xl" :class="{required:item.required}">{{ item.label }}</div>
        <TierSelectField
          v-if="item.name === 'select'"
          v-model:options="item.options" :multiple="item.multiple" :disabled="loading"
        />
      </div>
      <van-button class="decorate" block :loading
                  @click="handle(data.questionnaires)"
      >提交
      </van-button>
    </template>
    <van-toast v-else :show="loading" type="loading" message="加载中" />
  </div>
</template>
<style scoped lang="scss">
.required::after {
  content: "*";
  color: #f53030;
  font-size: 2rem;
}
</style>
