<script lang="ts" setup>
/**
 * 某药品的配送仓绑定列表弹窗（卡片展示）
 * 展示报价/推广费/平台费/库存；新增/编辑打开仓药绑定表单（药品预填）
 * 打开时尽量补齐总仓售价，供费用封顶与平台费默认 5%
 */
import { computed, nextTick, ref } from 'vue';

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

import { Button, Empty, message, Pagination, Spin, Tag } from 'ant-design-vue';

import { getWarehouseDrugManagementList } from '#/views/business/warehouse-drug-management/admin/api';

import { deleteDeliveryWarehouseDrug, getDeliveryWarehouseDrugList } from '../api';
import { resolveCentralPrice } from '../utils/resolve-central-price';
import FormModal from './modal.vue';

const drugId = ref(0);
const drugName = ref('');
const drugMeta = ref<Record<string, any>>({});
/** 总仓售价，用于绑仓表单默认平台费与封顶 */
const centralPrice = ref<number | null>(null);
const productGridApi = ref();
const loading = ref(false);
const items = ref<Record<string, any>[]>([]);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
/** 打开后是否立刻弹出新增表单 */
const pendingAutoCreate = ref(false);

const [FormModalComp, formModalApi] = useVbenModal({
  connectedComponent: FormModal,
});

const priceText = computed(() => {
  if (centralPrice.value != null && centralPrice.value > 0) {
    return `¥${Number(centralPrice.value).toFixed(2)}`;
  }
  return '无总仓售价';
});

/**
 * 加载绑定卡片数据
 */
async function loadList() {
  if (!drugId.value) {
    items.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    const res = await getDeliveryWarehouseDrugList({
      page: page.value,
      pageSize: pageSize.value,
      drug_id: drugId.value,
    });
    items.value = res?.items || [];
    total.value = Number(res?.total || 0);
  } finally {
    loading.value = false;
  }
}

/**
 * 列表未带售价时，按 drug_id 查总仓补齐
 */
async function ensureCentralPrice() {
  if (centralPrice.value != null && centralPrice.value > 0) return;
  if (!drugId.value) return;
  try {
    const res = await getWarehouseDrugManagementList({
      page: 1,
      pageSize: 1,
      drug_id: drugId.value,
    });
    const row = res?.items?.[0];
    const price = Number(row?.price ?? 0);
    if (price > 0) {
      centralPrice.value = price;
    }
  } catch {
    // 补齐失败不阻断绑仓，表单内仍可手填三费
  }
}

/**
 * 打开新增：药品锁定预填 + 带上 number 类型总仓售价
 */
async function openCreate() {
  await ensureCentralPrice();
  const price =
    centralPrice.value != null && centralPrice.value > 0
      ? Number(centralPrice.value)
      : null;
  formModalApi.setData({
    update: false,
    // 新增成功后刷新业务列表与本卡片列表
    gridApi: {
      query: () => {
        loadList();
        productGridApi.value?.query?.();
      },
      reload: () => {
        loadList();
        productGridApi.value?.query?.();
      },
    },
    lockDrug: true,
    central_price: price,
    presetDrug: {
      id: drugId.value,
      drug_name: drugName.value,
      specification: drugMeta.value.specification || '',
      image: drugMeta.value.image || '',
      central_price: price,
    },
    values: {
      drug_id: drugId.value,
      ...(price != null ? { sale_price: price } : {}),
    },
  });
  formModalApi.open();
}

async function openEdit(row: any) {
  await ensureCentralPrice();
  const price =
    centralPrice.value != null && centralPrice.value > 0
      ? Number(centralPrice.value)
      : resolveCentralPrice(row);
  formModalApi.setData({
    update: true,
    gridApi: {
      query: () => {
        loadList();
        productGridApi.value?.query?.();
      },
      reload: () => {
        loadList();
        productGridApi.value?.query?.();
      },
    },
    central_price: price,
    values: {
      ...row,
      ...(price != null ? { sale_price: price } : {}),
    },
  });
  formModalApi.open();
}

function handleDelete(id: number) {
  deleteDeliveryWarehouseDrug({ ids: [id] }).then(() => {
    message.success('删除成功');
    loadList();
    productGridApi.value?.query?.();
  });
}

function onPageChange(p: number) {
  page.value = p;
  loadList();
}

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      productGridApi.value?.query?.();
      pendingAutoCreate.value = false;
      return;
    }
    const data = modalApi.getData<Record<string, any>>() || {};
    drugId.value = Number(data.drug_id || data.values?.id || 0);
    drugName.value =
      data.drug_name || data.values?.drug_name || `药品#${drugId.value}`;
    drugMeta.value = {
      specification: data.specification || data.values?.specification || '',
      image: data.image || data.values?.image || '',
    };
    // 与表单同源解析：兼容嵌套 central_warehouse_drug
    centralPrice.value =
      resolveCentralPrice(data) ??
      resolveCentralPrice(data.values) ??
      resolveCentralPrice(data.presetDrug) ??
      null;
    productGridApi.value = data.gridApi;
    pendingAutoCreate.value = !!data.autoCreate;
    page.value = 1;
    await ensureCentralPrice();
    await loadList();
    if (pendingAutoCreate.value) {
      pendingAutoCreate.value = false;
      await nextTick();
      await openCreate();
    }
  },
});
</script>
<template>
  <Modal :title="`配送仓绑定 - ${drugName}`" class="w-[720px]">
    <FormModalComp />
    <div class="bind-list-header">
      <div class="bind-list-header__meta">
        <span>药品售价：</span>
        <span
          :class="
            centralPrice && centralPrice > 0
              ? 'bind-list-header__price'
              : 'bind-list-header__price--empty'
          "
        >
          {{ priceText }}
        </span>
      </div>
      <Button type="primary" @click="openCreate">新增绑定</Button>
    </div>
    <Spin :spinning="loading">
      <div v-if="items.length" class="bind-card-list">
        <div v-for="row in items" :key="row.id" class="bind-card">
          <div class="bind-card__head">
            <div class="bind-card__title">
              {{ row.warehouse?.name || `仓库#${row.warehouse_id}` }}
            </div>
            <Tag v-if="row.status === 2" color="green">上架</Tag>
            <Tag v-else color="default">下架</Tag>
          </div>
          <div class="bind-card__body">
            <div class="bind-card__item">
              <span class="bind-card__label">报价</span>
              <span>¥{{ Number(row.quote || 0).toFixed(4) }}</span>
            </div>
            <div class="bind-card__item">
              <span class="bind-card__label">推广费</span>
              <span>¥{{ Number(row.promo_fee || 0).toFixed(4) }}</span>
            </div>
            <div class="bind-card__item">
              <span class="bind-card__label">平台费</span>
              <span>¥{{ Number(row.platform_fee || 0).toFixed(4) }}</span>
            </div>
            <div class="bind-card__item">
              <span class="bind-card__label">库存</span>
              <span>{{ row.stock ?? 0 }}</span>
            </div>
          </div>
          <div class="bind-card__actions">
            <Button type="link" size="small" @click="openEdit(row)">编辑</Button>
            <Button
              type="link"
              size="small"
              danger
              @click="handleDelete(row.id)"
            >
              删除
            </Button>
          </div>
        </div>
      </div>
      <Empty v-else description="暂无绑定" />
    </Spin>
    <div v-if="total > pageSize" class="bind-list-pager">
      <Pagination
        :current="page"
        :page-size="pageSize"
        :total="total"
        size="small"
        @change="onPageChange"
      />
    </div>
  </Modal>
</template>
<style scoped>
.bind-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 16px;
}
.bind-list-header__meta {
  font-size: 13px;
  color: hsl(var(--muted-foreground));
}
.bind-list-header__price {
  font-weight: 600;
  color: hsl(var(--foreground));
}
.bind-list-header__price--empty {
  color: hsl(var(--muted-foreground));
}
.bind-card-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 420px;
  overflow-y: auto;
}
.bind-card {
  border: 1px solid hsl(var(--border));
  border-radius: 8px;
  background: hsl(var(--card));
  padding: 12px 14px;
}
.bind-card__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 10px;
}
.bind-card__title {
  font-weight: 600;
  color: hsl(var(--foreground));
}
.bind-card__body {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px 16px;
  font-size: 13px;
  color: hsl(var(--foreground));
}
.bind-card__item {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}
.bind-card__label {
  color: hsl(var(--muted-foreground));
}
.bind-card__actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  border-top: 1px solid hsl(var(--border));
  padding-top: 4px;
}
.bind-list-pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
