<script lang="ts" setup>
/**
 * 出入库记录抽屉：卡片列表展示
 * 含手动入库/出库、绑定初始入库及操作人
 */
import { reactive, ref } from 'vue';

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

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

import { getDeliveryWarehouseStockLogList } from '#/views/system/delivery-warehouse-stock/api';

defineOptions({ name: 'DeliveryWarehouseStockLogDrawer' });

const loading = ref(false);
const rows = ref<Record<string, any>[]>([]);
const drugName = ref('');
const pager = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});
const filter = reactive({
  warehouse_drug_id: 0 as number,
});

/** 类型 Tag 颜色：入绿 / 出橙 / 其它默认 */
function bizTagColor(bizType: string) {
  if (bizType === 'manual_in' || bizType === 'refund_in') return 'success';
  if (bizType === 'manual_out' || bizType === 'ship_out') return 'warning';
  return 'default';
}

async function loadLogs() {
  if (!filter.warehouse_drug_id) {
    rows.value = [];
    return;
  }
  loading.value = true;
  try {
    // 只传 warehouse_drug_id，避免与 drug_id AND 干扰
    const res = await getDeliveryWarehouseStockLogList({
      page: pager.current,
      pageSize: pager.pageSize,
      warehouse_drug_id: filter.warehouse_drug_id,
    });
    rows.value = res?.items ?? res?.list ?? [];
    pager.total = Number(res?.total ?? 0);
  } finally {
    loading.value = false;
  }
}

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-[720px]',
  showConfirmButton: false,
  onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = drawerApi.getData<{ row: Record<string, any> }>();
    const row = data?.row || {};
    drugName.value = row.drug?.drug_name || '';
    filter.warehouse_drug_id = Number(row.id || 0);
    pager.current = 1;
    void loadLogs();
  },
});
</script>

<template>
  <Drawer :title="`出入库记录${drugName ? ` - ${drugName}` : ''}`">
    <Spin :spinning="loading">
      <div v-if="rows.length" class="log-card-list">
        <div
          v-for="record in rows"
          :key="record.id"
          class="log-card border-border bg-card"
        >
          <div class="log-card__head">
            <Tag :color="bizTagColor(record.biz_type)">
              {{ record.biz_type_txt || record.biz_type }}
            </Tag>
            <span class="text-muted-foreground text-xs">{{
              record.created_at
            }}</span>
          </div>
          <div class="log-card__body">
            <div class="log-card__row">
              <span class="text-muted-foreground">数量</span>
              <span class="text-foreground font-medium">{{ record.qty }}</span>
            </div>
            <div class="log-card__row">
              <span class="text-muted-foreground">库存</span>
              <span class="text-foreground"
                >{{ record.stock_before }} → {{ record.stock_after }}</span
              >
            </div>
            <div class="log-card__row">
              <span class="text-muted-foreground">冻结</span>
              <span class="text-foreground"
                >{{ record.frozen_before }} → {{ record.frozen_after }}</span
              >
            </div>
            <div class="log-card__row">
              <span class="text-muted-foreground">操作人</span>
              <span class="text-foreground">{{
                record.operator_name || '系统'
              }}</span>
            </div>
            <div v-if="Number(record.order_id) > 0" class="log-card__row">
              <span class="text-muted-foreground">订单ID</span>
              <span class="text-foreground">{{ record.order_id }}</span>
            </div>
            <div v-if="record.remark" class="log-card__row">
              <span class="text-muted-foreground">备注</span>
              <span class="text-foreground">{{ record.remark }}</span>
            </div>
          </div>
        </div>
        <div class="mt-4 flex justify-end">
          <Pagination
            v-model:current="pager.current"
            :page-size="pager.pageSize"
            :total="pager.total"
            size="small"
            @change="
              (p: number) => {
                pager.current = p;
                void loadLogs();
              }
            "
          />
        </div>
      </div>
      <Empty v-else class="py-10" description="暂无出入库记录" />
    </Spin>
  </Drawer>
</template>

<style scoped>
.log-card-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.log-card {
  border: 1px solid hsl(var(--border));
  border-radius: 10px;
  padding: 12px 14px;
  background: hsl(var(--card));
}
.log-card__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.log-card__body {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.log-card__row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 13px;
}
</style>
