<script setup lang="ts">
import { Notify } from '@/platform';
import { tryOnBeforeMount, tryOnUnmounted, useCountdown } from '@vueuse/core';

import { useRequest } from 'alova/client';
import { putPulseMethod } from '@/request/api/pulse.api';
import type { Flow, FlowRoute } from '@/request/model';
import { getRoutePath, useRouteNext } from '@/computable/useRouteNext';

import { useVisitor } from '@/stores';

import NavHomeSelect from '@/assets/images/nav-home.select.png?url';

const router = useRouter();
const Visitor = useVisitor();

const finished = ref(false);
const supported = ref(true);
const actionText = computed(() => supported.value ? `获取健康调理方案` : `下一步`);
/* 倒计时完成动作 */
const done = shallowRef<Flow>();
/* 下一动作可选 */
const next = shallowRef<Flow>();

const { handle, loading } = useRouteNext({
  onSuccess(flow) { return pulse(flow); },
  onError(error) { Notify.warning(error.message); },
});

const { remaining, start, stop } = useCountdown(5, {
  onComplete() { replace(done.value!); },
  immediate: false,
});
const countdown = computed(() => remaining.value.toString().padStart(2, '0'));

tryOnBeforeMount(() => handle());
tryOnUnmounted(() => stop());

async function pulse(flow: FlowRoute) {
  stop();
  const showReport = flow.next.route === '/pulse/result';
  try {
    const patientId = Visitor.patientId;
    const result = await Bridge.pulse(patientId!!);
    await submit(patientId, result);
    if (showReport) await replace(flow.next);
    else {
      finished.value = true;
      done.value = flow.next.optional ? { title: '返回首页', route: '/screen' } : flow.next;
      next.value = flow.next.optional ? flow.next : void 0;
      start(10);
    }
  } catch (e) {
    let message;
    let countdown;

    if (e instanceof ReferenceError) {
      supported.value = false;
      message = `当前环境不支持脉诊设备，请联系管理员！`;
      countdown = 5;
    } else {
      message = `请再次测量脉诊！`;
      countdown = 10;
    }
    done.value = flow.value.optional && !showReport ? flow.next : { title: '返回首页', route: '/screen' };
    start(countdown);
    Notify.warning(message);
  }
}

const { data: report, loading: submitting, send: submit, } = useRequest((id, result) => putPulseMethod(id, result), { immediate: false }).onSuccess(({ data }) => {
  Visitor.updatePulseReport(data);
});

const replace = (flow: Flow) => router.push({ path: getRoutePath(flow), replace: true });
</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">
          {{ finished ? '完成脉诊采集' : '脉诊采集' }}
        </div>
      </div>
      <div class="grow shrink-0 h-full min-w-16 flex items-center justify-end overflow-hidden">
        <router-link :to="{ path: '/screen' }" replace>
          <img class="size-8 object-scale-down" :src="NavHomeSelect" alt="返回首页" />
        </router-link>
      </div>
    </div>
    <div class="page-content flex flex-col">
      <header></header>
      <main class="flex flex-col justify-evenly">
        <template v-if="finished && report">
          <img class="size-40 mx-auto" src="@/assets/images/tips.png" alt="" />
          <div>
            <div class="text-3xl text-center">恭喜您！</div>
            <div class="text-3xl text-center my-8">完成脉诊采集</div>
          </div>
          <AnalysisPulseComponent title="" v-bind="report" disabled>
            <template #exception>
              <div><!--空占位符--></div>
            </template>
          </AnalysisPulseComponent>
        </template>
      </main>
      <footer class="flex flex-col justify-center items-center">
        <template v-if="!loading">
          <van-button v-if="next" class="decorate !text-xl" @click="replace(next)">
            {{ next.title ?? actionText }}
          </van-button>
          <van-button v-if="done" class="decorate !text-xl !text-primary-400" @click="replace(done)">
            {{ done.title ?? actionText }}
            <template v-if="remaining">({{ countdown }}s)</template>
          </van-button>
        </template>
        <div v-if="supported && !finished" class="van-button decorate" @click="!loading && handle()">
          <div class="van-button__content">
            <van-loading v-if="loading || submitting" />
            <span v-else class="van-button__text">连接脉诊</span>
          </div>
        </div>
      </footer>
    </div>
  </div>
</template>
<style scoped lang="scss">
header {
  flex: 1 1 10%;
}

footer {
  flex: 1 1 30%;
}

main {
  position: relative;
  flex: 1 1 50%;
}

.decorate {
  margin: 24px 0;
}
</style>
