<script setup lang="ts">
import { useRequest } from 'alova/client';
import { getDataMethod } from '@/api/pda.api.ts';
import { useStepStore } from '@/stores';

import { useStep } from '@/core/hook/useStep.ts';

const stepStore = useStepStore();
const { dataset, id, mode, title } = storeToRefs(stepStore);
const loaded = computed(() => !!id.value);

const keyword = ref('');
const { menu, tabTitle, next, prev } = useStep(mode, id, title);

watchEffect(() => {
  keyword.value = id.value;
  nextTick(() => {
    if (!id.value) stepStore.$reset();
  });
});

const { loading, send: search } = useRequest(getDataMethod, { immediate: false })
  .onSuccess(({ data }) => {
    dataset.value = data;
    next(dataset.value.no);
  })
  .onError(() => {
    keyword.value = '';
  });

function onSearch(value?: string) {
  if (value) {
    keyword.value = value?.trim();
  } else {
    value = keyword.value;
  }
  if (value?.trim()) {
    search(value.trim(), mode.value);
  } else {
    showNotify({ message: '请使用设备按钮进行扫码', type: 'warning' });
  }
}

defineExpose({
  search: onSearch,
  back: prev,
});
</script>

<template>
  <div class="page page__home flex flex-col size-full">
    <van-toast :show="loading" type="loading" forbid-click message="查询中..." />

    <header class="flex-none">
      <van-nav-bar :title="menu?.title" left-text="返回" left-arrow @click-left="prev()" />
      <van-search v-model="keyword" input-align="center" placeholder="请使用设备按钮进行扫码" @search="onSearch()" :readonly="loaded" :show-action="loaded" @cancel="prev()" />
    </header>
    <slot :title="tabTitle" :component="menu?.component"></slot>
  </div>
</template>

<style scoped lang="scss"></style>
