<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

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

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

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

import StockIoModal from './components/stock-io-modal.vue';
import StockLogDrawer from './components/stock-log-drawer.vue';

defineOptions({ name: 'DeliveryWarehouseStockIndex' });

const loading = ref(false);
const keyword = ref('');
const list = ref<Record<string, any>[]>([]);
const pager = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0,
});

const [IoModal, ioModalApi] = useVbenModal({
  connectedComponent: StockIoModal,
});

const [LogDrawer, logDrawerApi] = useVbenDrawer({
  connectedComponent: StockLogDrawer,
});

/**
 * 加载库存卡片（绑药列表）
 */
async function loadList() {
  loading.value = true;
  try {
    const res = await getDeliveryWarehouseDrugList({
      page: pager.currentPage,
      pageSize: pager.pageSize,
      // 后端无药名 like 时仅本地过滤；有则透传
      drug_name: keyword.value?.trim() || undefined,
    });
    let items = res?.items ?? res?.list ?? [];
    const kw = keyword.value?.trim();
    if (kw) {
      items = items.filter((row: any) => {
        const name = String(row.drug?.drug_name || '');
        const no = String(row.drug?.drug_number || '');
        return name.includes(kw) || no.includes(kw);
      });
    }
    list.value = items;
    pager.total = Number(res?.total ?? 0);
  } finally {
    loading.value = false;
  }
}

function openIo(row: Record<string, any>, mode: 'in' | 'out') {
  ioModalApi.setData({
    mode,
    row,
    onSuccess: () => loadList(),
  });
  ioModalApi.open();
}

function openLogs(row: Record<string, any>) {
  logDrawerApi.setData({ row });
  logDrawerApi.open();
}

function available(row: Record<string, any>) {
  if (row.available_stock !== undefined && row.available_stock !== null) {
    return Number(row.available_stock);
  }
  return Math.max(Number(row.stock || 0) - Number(row.frozen_number || 0), 0);
}

onMounted(() => {
  void loadList();
});
</script>

<template>
  <Page auto-content-height title="库存管理">
    <IoModal />
    <LogDrawer />
    <div class="flex flex-col gap-4">
      <div class="flex flex-wrap items-center gap-3">
        <Input
          v-model:value="keyword"
          allow-clear
          class="w-64"
          placeholder="药品名称/编号"
          @press-enter="() => { pager.currentPage = 1; void loadList(); }"
        />
        <Button
          type="primary"
          @click="
            () => {
              pager.currentPage = 1;
              void loadList();
            }
          "
        >
          查询
        </Button>
        <span class="text-sm text-[hsl(var(--muted-foreground))]">
          库存变动请用入库/出库，禁止直接改数量
        </span>
      </div>

      <Spin :spinning="loading">
        <div
          v-if="list.length"
          class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3"
        >
          <Card
            v-for="row in list"
            :key="row.id"
            size="small"
          >
            <template #title>
              <div class="flex flex-col gap-1">
                <span>{{ row.drug?.drug_name || '-' }}</span>
                <span class="text-xs font-normal text-[hsl(var(--muted-foreground))]">
                  规格：{{ row.drug?.specification?.trim() || '-' }}
                </span>
                <span class="text-xs font-normal text-[hsl(var(--muted-foreground))]">
                  {{ row.drug?.drug_number || '-' }}
                  <template v-if="row.warehouse?.name">
                    · {{ row.warehouse.name }}
                  </template>
                </span>
              </div>
            </template>
            <template #extra>
              <Tag :color="Number(row.status) === 2 ? 'green' : 'default'">
                {{ Number(row.status) === 2 ? '上架' : '下架' }}
              </Tag>
            </template>

            <div class="grid grid-cols-3 gap-2 text-center text-sm">
              <div class="rounded bg-[hsl(var(--muted)/0.35)] p-2">
                <div class="text-lg font-semibold text-emerald-600">
                  {{ available(row) }}
                </div>
                <div class="text-xs text-[hsl(var(--muted-foreground))]">
                  可用
                </div>
              </div>
              <div class="rounded bg-[hsl(var(--muted)/0.35)] p-2">
                <div class="text-lg font-semibold text-orange-500">
                  {{ row.frozen_number ?? 0 }}
                </div>
                <div class="text-xs text-[hsl(var(--muted-foreground))]">
                  冻结
                </div>
              </div>
              <div class="rounded bg-[hsl(var(--muted)/0.35)] p-2">
                <div class="text-lg font-semibold">
                  {{ row.stock ?? 0 }}
                </div>
                <div class="text-xs text-[hsl(var(--muted-foreground))]">
                  总库存
                </div>
              </div>
            </div>

            <template #actions>
              <Space wrap>
                <Button size="small" type="link" @click="openIo(row, 'in')">
                  入库
                </Button>
                <Button size="small" type="link" @click="openIo(row, 'out')">
                  出库
                </Button>
                <Button size="small" type="link" @click="openLogs(row)">
                  出入库记录
                </Button>
              </Space>
            </template>
          </Card>
        </div>
        <Empty v-else class="py-16" description="暂无库存药品" />
      </Spin>

      <div v-if="pager.total > 0" class="flex justify-end">
        <Pagination
          v-model:current="pager.currentPage"
          v-model:page-size="pager.pageSize"
          :total="pager.total"
          show-size-changer
          :page-size-options="['12', '24', '48']"
          @change="loadList"
          @show-size-change="loadList"
        />
      </div>
    </div>
  </Page>
</template>
