import type { StartDirectiveValue } from '@/composables/start/start.directive';

import { showLoadingToast } from 'vant';
import { Notify } from '@/platform';
import { registerVisitorMethod } from '@/request/api';
import { useFlowStore, useVisitor } from '@/stores';

const showLoading = () => {
  const instance = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  return () => instance.close();
}

export function useStart(ui?: boolean) {
  const Visitor = useVisitor();
  const Flow = useFlowStore();
  const { flow } = storeToRefs(Flow);

  const extra: StartDirectiveValue = {
    threshold: 1000 * 5,
    fn() {},
  };

  const register = async () => {
    loading.value = true;
    const close = ui ? showLoading() : void 0;
    try {
      Visitor.patientId = await registerVisitorMethod().send(true);
      return Visitor.patientId;
    } catch (error: any) {
      Notify.error(error.message);
    } finally {
      loading.value = false;
      close?.()
    }
  };

  const loading = ref(false);
  async function handle() {
    if (loading.value) return;
    Visitor.$reset();
    if (flow.value.next === '/register' || (await register())) await Flow.router.push();
  }

  return { extra, loading, handle };
}
