<script lang="ts" setup>
/**
 * 超级仓库 Admin：选品字段，搜索尚未加入总仓（yii_drugstore_drug）的药品
 */
import { computed, ref, watch } from 'vue';

import { Button } from 'ant-design-vue';

import {
  WarehouseAvailableDrugSearch,
  type WarehouseDrugItem,
} from '#/components/warehouse-drug-search';

const PRODUCT_TYPE_LABEL: Record<number, string> = {
  1: '中药',
  2: '西药',
  3: '保健食品',
  4: '中成药',
  5: '产品服务包',
  6: '非药品',
  7: '医疗器械',
};

const props = withDefaults(
  defineProps<{
    /** vben-form：药品 ID */
    value?: number;
    /** 列表筛选类型（ProductTypeEnum） */
    productType?: number;
  }>(),
  {
    productType: 1,
  },
);

const emit = defineEmits<{
  'update:value': [value: number | undefined];
}>();

const selectedLabel = ref('');

const placeholder = computed(() => {
  const name = PRODUCT_TYPE_LABEL[props.productType] ?? '药品';
  return `输入${name}名称或拼音搜索（显示图片、供应商、规格）`;
});

watch(
  () => props.value,
  (v) => {
    if (v == null || v === undefined) {
      selectedLabel.value = '';
    }
  },
  { immediate: true },
);

function onSelect(drug: WarehouseDrugItem) {
  selectedLabel.value = drug.drug_name || '';
  emit('update:value', drug.id);
}

function clearSelection() {
  selectedLabel.value = '';
  emit('update:value', undefined);
}
</script>

<template>
  <div class="w-full space-y-2">
    <WarehouseAvailableDrugSearch
      :product-type="productType"
      :placeholder="placeholder"
      @select="onSelect"
    />
    <div
      v-if="value != null"
      class="flex items-center gap-2 text-sm text-muted-foreground"
    >
      <span>已选：{{ selectedLabel || `ID ${value}` }}</span>
      <Button type="link" size="small" class="!p-0" @click="clearSelection">
        清除
      </Button>
    </div>
  </div>
</template>
