<script setup lang="ts">
import NavHomeSelect from '@/assets/images/nav-home.select.png?url';

import type RegisterForm from '@/components/RegisterForm.vue';
import type { RegisterModel } from '@/request/model';

import { useRouteQuery } from '@vueuse/router';
import { useRequest } from 'alova/client';
import { getApplicationMethod, registerAccountMethod } from '@/request/api';

import { useFlowStore, useVisitor } from '@/stores';


useRequest(getApplicationMethod, { initialData: { image: {} } });

const flow = useFlowStore();
const visitor = useVisitor();
const { loading: submitting, send: submit } = useRequest(registerAccountMethod, { immediate: false });

const formRef = ref<InstanceType<typeof RegisterForm> | null>(null);
async function onSubmitFromForm(payload: { model: RegisterModel; modelLabel: Partial<RegisterModel> }) {
  const patientId = await submit(payload.model);
  visitor.updatePatient(payload.modelLabel, patientId);
  flow.router.push();
}

const scan = useRouteQuery<string>('scan');

function applyScanToForm() {
  const key = scan.value;
  if (!key) return;
  try {
    const { model } = JSON.parse(sessionStorage.getItem(`scan_${key}`) ?? '');
    nextTick(() => formRef.value?.setValues(model));
  } catch (_e: any) {}
}

watch(scan, applyScanToForm, { immediate: true, flush: 'post' });

watch(formRef, (inst) => {
  if (inst && scan.value) applyScanToForm();
}, { flush: 'post' });

onBeforeUnmount(() => {
  for (let i = 0; i < sessionStorage.length; i++) {
    const key = sessionStorage.key(i);
    if (key?.startsWith('scan_')) sessionStorage.removeItem(key);
  }
});
</script>
<template>
  <div>
    <div class="page-header flex py-4 px-4 overflow-hidden">
      <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="flex justify-center font-bold text-3xl text-nowrap text-center tracking-wide overflow-ellipsis overflow-hidden">
          建档 <van-loading v-if="formRef?.searching" style="margin-left: 4px; color: #38ff6e"></van-loading>
        </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 p-6 overflow-auto">
      <RegisterForm ref="formRef" :search-forbidden-field="!extra_hack" @submit="onSubmitFromForm" />
      <div class="m-4">
        <div class="m-auto size-16 cursor-pointer">
          <van-loading v-if="submitting || formRef?.loading" type="spinner" size="64" color="#38ff6e" />
          <img v-else class="size-full" src="@/assets/images/next-step.svg" alt="提交" @click="formRef?.submit()" />
        </div>
      </div>
    </div>
  </div>
</template>
