<script lang="ts" setup>
/**
 * 在线复诊开方：按药品分步卡片选配送仓库
 * 默认选中 options[0]（与后端 auto 一致：quote ASC 最低价）
 * 样式使用主题 token，适配亮/暗色
 */
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button, Image, message } from 'ant-design-vue';

const emit = defineEmits<{
  (e: 'confirm', map: Record<number, number>): void;
}>();

type WarehouseOption = {
  warehouse_id: number;
  warehouse_name: string;
  quote: string;
  available_stock: number;
  /** 接口可能在 option 上带药品展示字段，供 row 回退 */
  drug_name?: string;
  image?: string;
  specification?: string;
};

type DrugRow = {
  drug_id: number;
  drug_name: string;
  image?: string;
  specification?: string;
  options: WarehouseOption[];
  warehouse_id?: number;
};

/**
 * 从 row 或 options[0] 取药品展示字段（接口规格在 option 上）
 */
function resolveDrugMeta(row: DrugRow) {
  const first = row.options?.[0];
  return {
    drug_name: row.drug_name || first?.drug_name || '',
    image: row.image || first?.image || '',
    specification: row.specification || first?.specification || '',
  };
}

const drugRows = ref<DrugRow[]>([]);
/** 当前步骤下标（0-based） */
const stepIndex = ref(0);

const totalSteps = computed(() => drugRows.value.length);
const currentRow = computed(() => drugRows.value[stepIndex.value] || null);
/** 当前步药品展示：名/图/规格，含 option 回退 */
const currentDrugMeta = computed(() =>
  currentRow.value
    ? resolveDrugMeta(currentRow.value)
    : { drug_name: '', image: '', specification: '' },
);
const isFirstStep = computed(() => stepIndex.value <= 0);
const isLastStep = computed(
  () => stepIndex.value >= Math.max(totalSteps.value - 1, 0),
);
const canGoNext = computed(() => !!currentRow.value?.warehouse_id);

/** 点击卡片选中当前步骤药品的配送仓 */
function selectWarehouse(warehouseId: number) {
  const row = currentRow.value;
  if (!row) return;
  row.warehouse_id = warehouseId;
}

function goPrev() {
  if (!isFirstStep.value) {
    stepIndex.value -= 1;
  }
}

function goNext() {
  if (!canGoNext.value) {
    message.error('请先选择配送仓库');
    return;
  }
  if (!isLastStep.value) {
    stepIndex.value += 1;
  }
}

/** 汇总 warehouse_map 并确认 */
function confirmAll() {
  if (!canGoNext.value) {
    message.error('请先选择配送仓库');
    return;
  }
  const map: Record<number, number> = {};
  for (const row of drugRows.value) {
    if (!row.warehouse_id) {
      message.error(`请为【${row.drug_name}】选择配送仓库`);
      return;
    }
    map[row.drug_id] = row.warehouse_id;
  }
  emit('confirm', map);
  modalApi.close();
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  footer: false,
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<{ rows: DrugRow[] }>();
      // 默认选中每药 options[0]（最低 quote）；规格/图/名可从 option 回退
      drugRows.value = (data?.rows || []).map((row) => {
        const meta = resolveDrugMeta(row);
        return {
          ...row,
          warehouse_id: row.options?.[0]?.warehouse_id,
          drug_name: meta.drug_name || `药品#${row.drug_id}`,
          image: meta.image,
          specification: meta.specification,
        };
      });
      stepIndex.value = 0;
    }
  },
});
</script>

<template>
  <Modal title="选择配送仓库" class="w-[640px]">
    <div v-if="currentRow" class="space-y-4 py-2">
      <div class="text-muted-foreground text-sm">
        第 {{ stepIndex + 1 }} / {{ totalSteps }} 个药品
      </div>
      <!-- 当前药品信息：图 / 名 / 规格 -->
      <div
        class="border-border bg-muted/30 flex items-start gap-3 rounded-lg border p-3"
      >
        <Image
          v-if="currentDrugMeta.image"
          :src="currentDrugMeta.image"
          :width="64"
          :height="64"
          class="shrink-0 rounded object-cover"
        />
        <div
          v-else
          class="bg-accent text-muted-foreground flex h-16 w-16 shrink-0 items-center justify-center rounded text-xs"
        >
          暂无图
        </div>
        <div class="min-w-0 flex-1">
          <div
            class="text-foreground truncate text-base font-medium"
            :title="currentDrugMeta.drug_name"
          >
            {{ currentDrugMeta.drug_name }}
          </div>
          <div class="text-muted-foreground mt-1 text-sm">
            规格：{{ currentDrugMeta.specification || '--' }}
          </div>
        </div>
      </div>
      <!-- 仓卡片 -->
      <div class="flex flex-wrap gap-2">
        <button
          v-for="opt in currentRow.options"
          :key="opt.warehouse_id"
          type="button"
          class="min-w-[140px] rounded-lg border px-3 py-2 text-left transition-colors"
          :class="
            currentRow.warehouse_id === opt.warehouse_id
              ? 'border-primary bg-primary/10 ring-primary ring-1'
              : 'border-border hover:border-primary/50'
          "
          @click="selectWarehouse(opt.warehouse_id)"
        >
          <div class="text-foreground text-sm font-medium">
            {{ opt.warehouse_name }}
          </div>
          <div class="text-muted-foreground mt-1 text-xs">
            供货价 {{ opt.quote }} · 库存 {{ opt.available_stock }}
          </div>
        </button>
      </div>
    </div>
    <div v-else class="text-muted-foreground py-6">当前药品无需选择配送仓库</div>
    <!-- 自定义底栏：上一步 / 下一步 / 确认 -->
    <div class="border-border mt-4 flex justify-end gap-2 border-t pt-3">
      <Button v-if="!isFirstStep" @click="goPrev">上一步</Button>
      <Button
        v-if="!isLastStep"
        type="primary"
        :disabled="!canGoNext"
        @click="goNext"
      >
        下一步
      </Button>
      <Button v-else type="primary" :disabled="!canGoNext" @click="confirmAll">
        确认
      </Button>
    </div>
  </Modal>
</template>
