<template>
  <div class="page">
    <h2 class="page-title">入库流水</h2>
    <div class="panel">
      <div class="inline-form">
        <t-button theme="primary" @click="load">刷新</t-button>
        <t-button variant="outline" @click="openCreate">新增入库</t-button>
      </div>
    <t-table :data="list" :columns="columns" row-key="id">
      <template #drugId="{ row }">
        {{ getDrugName(row.drugId) }}
      </template>
    </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" header="新增入库" :on-confirm="submitCreate">
      <t-form :data="form">
        <t-form-item label="药品" required>
          <t-select v-model="form.drugId" :options="drugOptions" placeholder="请选择药品" clearable />
        </t-form-item>
        <t-form-item label="数量"><t-input v-model="form.quantity" /></t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../api';

const list = ref([] as any[]);
const dialogVisible = ref(false);
const form = reactive({ drugId: '', quantity: '' });
const drugs = ref([] as any[]);

const drugOptions = computed(() => {
  return drugs.value.map((drug: any) => ({
    label: drug.name,
    value: drug.id,
  }));
});

const getDrugName = (drugId: number) => {
  const drug = drugs.value.find((item: any) => item.id === drugId);
  if (!drug) return drugId ? `药品ID ${drugId}` : '-';
  return drug.name || `药品${drug.id}`;
};

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'drugId', title: '药品' },
  { colKey: 'quantity', title: '数量' },
  { colKey: 'stockInTime', title: '入库时间' },
];

const load = async () => {
  const res = await api.stockIn({ page: 1, size: 20 });
  if (res.code === 0) list.value = res.data.records || [];
};

const loadDrugs = async () => {
  const res = await api.drugs({ page: 1, size: 200 });
  if (res.code === 0) drugs.value = res.data?.records || [];
};

const openCreate = () => {
  form.drugId = '';
  form.quantity = '';
  dialogVisible.value = true;
};

const submitCreate = async () => {
  const res = await api.createStockIn({ ...form, stockInTime: new Date().toISOString() });
  if (res.code === 0) {
    MessagePlugin.success('创建成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '创建失败');
  }
};

onMounted(() => {
  load();
  loadDrugs();
});
</script>
