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

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

import { Form, Input, InputNumber, message } from 'ant-design-vue';

import {
  stockInDeliveryWarehouseDrug,
  stockOutDeliveryWarehouseDrug,
} from '#/views/system/delivery-warehouse-stock/api';

defineOptions({ name: 'DeliveryWarehouseStockIoModal' });

const mode = ref<'in' | 'out'>('in');
const row = ref<Record<string, any>>({});
const qty = ref<number>(1);
const remark = ref('');
const reloadFn = ref<null | (() => void)>(null);

const title = computed(() =>
  mode.value === 'in' ? '手动入库' : '手动出库',
);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    const id = Number(row.value?.id);
    const n = Number(qty.value);
    if (!id || n <= 0) {
      message.error('请填写正确的数量');
      return;
    }
    modalApi.setState({ confirmLoading: true });
    try {
      if (mode.value === 'in') {
        await stockInDeliveryWarehouseDrug({
          id,
          qty: n,
          remark: remark.value?.trim() || undefined,
        });
        message.success('入库成功');
      } else {
        await stockOutDeliveryWarehouseDrug({
          id,
          qty: n,
          remark: remark.value?.trim() || undefined,
        });
        message.success('出库成功');
      }
      reloadFn.value?.();
      modalApi.close();
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<{
      mode: 'in' | 'out';
      row: Record<string, any>;
      onSuccess?: () => void;
    }>();
    mode.value = data?.mode === 'out' ? 'out' : 'in';
    row.value = data?.row || {};
    qty.value = 1;
    remark.value = '';
    reloadFn.value = data?.onSuccess || null;
  },
});
</script>

<template>
  <Modal :title="title" class="w-[480px]">
    <div class="mb-3 text-sm text-[hsl(var(--muted-foreground))]">
      {{ row.drug?.drug_name || '-' }} /
      可用 {{ row.available_stock ?? Math.max((row.stock || 0) - (row.frozen_number || 0), 0) }}
      / 冻结 {{ row.frozen_number ?? 0 }}
      / 库存 {{ row.stock ?? 0 }}
    </div>
    <Form layout="vertical">
      <Form.Item :label="mode === 'in' ? '入库数量' : '出库数量'" required>
        <InputNumber v-model:value="qty" :min="1" class="w-full" />
      </Form.Item>
      <Form.Item label="备注">
        <Input.TextArea
          v-model:value="remark"
          :rows="3"
          placeholder="可选，便于追溯"
        />
      </Form.Item>
    </Form>
  </Modal>
</template>
