import { computed, onMounted, ref, watch } from 'vue';
import type { RouteLocationNormalizedLoaded } from 'vue-router';
import { useRoute, useRouter } from 'vue-router';

import { getWarehouseProductTypeOptions } from '../admin/api';

const VALID_TYPES = [1, 2, 3, 5, 6, 7];

function resolveProductType(route: RouteLocationNormalizedLoaded): number {
  const rawParam = route.params.type;
  const fromParam = Number(Array.isArray(rawParam) ? rawParam[0] : rawParam);
  if (VALID_TYPES.includes(fromParam)) {
    return fromParam;
  }

  const match = route.path.match(/\/type\/(\d+)(?:\/|$)/);
  const fromPath = Number(match?.[1]);
  return VALID_TYPES.includes(fromPath) ? fromPath : 0;
}

async function loadTypeLabel(productType: number, typeLabel: { value: string }) {
  try {
    const options = await getWarehouseProductTypeOptions();
    const matched = options?.find((item) => item.value === productType);
    typeLabel.value = matched?.label ?? `类型${productType}`;
  } catch {
    typeLabel.value = `类型${productType}`;
  }
}

/**
 * 从路由 /.../type/:type 或静态 path /.../type/1 锁定仓库商品类型
 */
export function useWarehouseDrugTypeRoute(fallbackRedirect: string) {
  const route = useRoute();
  const router = useRouter();
  const typeLabel = ref('');

  const productType = computed(() => resolveProductType(route));

  onMounted(async () => {
    if (!productType.value) {
      await router.replace(fallbackRedirect);
      return;
    }
    await loadTypeLabel(productType.value, typeLabel);
  });

  watch(productType, async (value) => {
    if (value) {
      await loadTypeLabel(value, typeLabel);
    }
  });

  return {
    productType,
    typeLabel,
  };
}

export { VALID_TYPES };
