<script lang="ts" setup>
/**
 * 药品详情「仓库信息」面板
 * 子 Tab：总仓（只读展示）/ 门店（可改供货价与售价）
 */
import { onMounted, ref, watch } from 'vue';

import {
  Button,
  Descriptions,
  DescriptionsItem,
  Empty,
  InputNumber,
  Spin,
  Table,
  Tabs,
  Tag,
  message,
} from 'ant-design-vue';

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

const props = defineProps<{
  drugId: number;
}>();

const loading = ref(false);
const saving = ref(false);
const warehouseTab = ref('central');
const central = ref<Record<string, any> | null>(null);
const stores = ref<Record<string, any>[]>([]);
const deliveryBinds = ref<Record<string, any>[]>([]);

/**
 * 拉取总仓/门店/配送仓绑定
 */
async function loadWarehouse() {
  const id = Number(props.drugId || 0);
  if (id < 1) {
    central.value = null;
    stores.value = [];
    deliveryBinds.value = [];
    return;
  }
  loading.value = true;
  try {
    const res = await getDrugWarehouseInfo(id);
    central.value = res?.central || null;
    stores.value = (res?.stores || []).map((s: any) => ({
      ...s,
      _buy_price: Number(s.buy_price || 0),
      _price: Number(s.price || 0),
      _dirty: false,
    }));
    deliveryBinds.value = res?.delivery_binds || [];
  } catch {
    central.value = null;
    stores.value = [];
    deliveryBinds.value = [];
  } finally {
    loading.value = false;
  }
}

function markDirty(row: Record<string, any>) {
  row._dirty = true;
}

/**
 * 保存已改动的门店价格
 */
async function saveStorePrices() {
  const dirty = stores.value.filter((s) => s._dirty);
  if (dirty.length === 0) {
    message.info('没有需要保存的修改');
    return;
  }
  for (const row of dirty) {
    if (Number(row._buy_price) < 0 || Number(row._price) < 0) {
      message.warning(`门店「${row.store_name}」价格不能为负`);
      return;
    }
  }
  saving.value = true;
  try {
    await updateStorePricesByDrug({
      drug_id: Number(props.drugId),
      items: dirty.map((s) => ({
        id: Number(s.id),
        buy_price: Number(s._buy_price),
        price: Number(s._price),
      })),
    });
    message.success(`已更新 ${dirty.length} 家门店价格`);
    await loadWarehouse();
  } finally {
    saving.value = false;
  }
}

const storeColumns = [
  { title: '门店', dataIndex: 'store_name', key: 'store_name', ellipsis: true },
  { title: '供货价', key: 'buy_price', width: 140 },
  { title: '售价', key: 'price', width: 140 },
  { title: '状态', key: 'status', width: 80 },
];

watch(
  () => props.drugId,
  () => {
    void loadWarehouse();
  },
);

onMounted(() => {
  void loadWarehouse();
});

defineExpose({ reload: loadWarehouse });
</script>

<template>
  <Spin :spinning="loading">
    <Tabs v-model:active-key="warehouseTab" size="small">
      <Tabs.TabPane key="central" tab="总仓">
        <Empty
          v-if="!central"
          :image="Empty.PRESENTED_IMAGE_SIMPLE"
          description="未入总仓"
        />
        <Descriptions v-else bordered size="small" :column="2">
          <DescriptionsItem label="总仓ID">
            {{ central.id }}
          </DescriptionsItem>
          <DescriptionsItem label="状态">
            <Tag :color="central.status === 2 ? 'green' : 'red'">
              {{ central.status_txt || '-' }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="供货价">
            ¥{{ Number(central.market_price || 0).toFixed(4) }}
          </DescriptionsItem>
          <DescriptionsItem label="建议售价">
            ¥{{ Number(central.price || 0).toFixed(4) }}
          </DescriptionsItem>
          <DescriptionsItem label="库存">
            {{ central.stock ?? '-' }}
          </DescriptionsItem>
          <DescriptionsItem label="更新时间">
            {{ central.updated_at || '-' }}
          </DescriptionsItem>
        </Descriptions>
        <div v-if="deliveryBinds.length" class="mt-3 text-xs" style="color: hsl(var(--muted-foreground))">
          已绑定 {{ deliveryBinds.length }} 个配送仓（改总仓售价时需重分配三费）
        </div>
      </Tabs.TabPane>
      <Tabs.TabPane key="stores" tab="门店">
        <div class="mb-2 flex items-center justify-between">
          <span class="text-xs" style="color: hsl(var(--muted-foreground))">
            共 {{ stores.length }} 家门店；修改后点保存
          </span>
          <Button
            type="primary"
            size="small"
            :loading="saving"
            :disabled="!stores.some((s) => s._dirty)"
            @click="saveStorePrices"
          >
            保存改价
          </Button>
        </div>
        <Empty
          v-if="stores.length === 0"
          :image="Empty.PRESENTED_IMAGE_SIMPLE"
          description="暂无门店价格"
        />
        <Table
          v-else
          size="small"
          :pagination="false"
          :columns="storeColumns"
          :data-source="stores"
          :scroll="{ y: 320 }"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'buy_price'">
              <InputNumber
                v-model:value="record._buy_price"
                :min="0"
                :precision="4"
                class="w-full"
                size="small"
                @change="markDirty(record)"
              />
            </template>
            <template v-else-if="column.key === 'price'">
              <InputNumber
                v-model:value="record._price"
                :min="0"
                :precision="4"
                class="w-full"
                size="small"
                @change="markDirty(record)"
              />
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="record.status === 2 ? 'green' : 'default'">
                {{ record.status === 2 ? '上架' : '下架' }}
              </Tag>
            </template>
          </template>
        </Table>
      </Tabs.TabPane>
    </Tabs>
  </Spin>
</template>
