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

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

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

const router = useRouter();

const first = ref(true);

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


function handle() {
  const questionnaires = data.value;
  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 {
    load();
  }
}

async function load() {
  const _first = first.value;
  loading.value = true;
  try {
    const { reportId, questionnaires } = await questionnaireMethod(data.value);
    if (reportId) return await router.replace(`/report/${reportId}`);
    showTitle.value = _first;
    data.value = [];
    // TODO 延迟渲染
    setTimeout(() => (data.value = questionnaires), 300);
  } catch (e) {
  } finally {
    loading.value = false;
    first.value = false;
  }
}

load();
</script>
<template>
  <div>
    <div class="page-header flex py-4 px-4">
      <div class="grow shrink-0 h-full min-w-16"></div>
      <div class="grow-[3] shrink mx-2 flex flex-col justify-center overflow-hidden">
        <div class="font-bold text-3xl text-nowrap text-center tracking-wide overflow-ellipsis overflow-hidden">
          问卷
        </div>
      </div>
      <div class="grow shrink-0 h-full min-w-16"></div>
    </div>
    <div class="page-content">
      <template v-if="data.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" :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()">提交</van-button>
      </template>
      <van-toast v-else-if="first" :show="loading" type="loading" message="加载中" />
    </div>
  </div>
</template>
<style scoped lang="scss">
.required::after {
  content: '*';
  color: #f53030;
  font-size: 2rem;
}
</style>
