<script lang="ts" setup>
/**
 * 总仓入库弹窗（从药品列表「未入库」打开）
 * 药品已预填，只填供货价/销售价后 createWarehouseDrugManagement
 */
import { ref } from 'vue';

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

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createWarehouseDrugManagement } from '#/views/business/warehouse-drug-management/admin/api';

const drugId = ref(0);
const drugName = ref('');
const productType = ref(2);
const productGridApi = ref();

const [Form, formApi] = useVbenForm({
  wrapperClass: 'grid-cols-12',
  commonConfig: {
    formItemClass: 'col-span-12',
    componentProps: { class: 'w-full' },
  },
  layout: 'horizontal',
  showDefaultActions: false,
  schema: [
    {
      component: 'VbenInput',
      fieldName: 'drug_id',
      label: '药品ID',
      componentProps: { disabled: true },
    },
    {
      component: 'VbenInput',
      fieldName: 'drug_name',
      label: '药品名称',
      componentProps: { disabled: true },
    },
    {
      component: 'InputNumber',
      fieldName: 'market_price',
      label: '供货价格',
      rules: 'required',
      componentProps: {
        min: 0,
        precision: 4,
        class: 'w-full',
        placeholder: '请输入供货价格',
      },
    },
    {
      component: 'InputNumber',
      fieldName: 'price',
      label: '销售价格',
      rules: 'required',
      componentProps: {
        min: 0,
        precision: 4,
        class: 'w-full',
        placeholder: '请输入销售价格',
      },
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const result = await formApi.validate();
    if (!result.valid) return;
    const values = await formApi.getValues();
    modalApi.setState({ loading: true, confirmLoading: true });
    try {
      // 总仓入库接口必填：drug_id / market_price / price（type 由药品本身决定）
      await createWarehouseDrugManagement({
        drug_id: drugId.value,
        market_price: values.market_price,
        price: values.price,
      });
      message.success('入库成功');
      productGridApi.value?.query?.();
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const data = modalApi.getData<Record<string, any>>() || {};
    drugId.value = Number(data.drug_id || data.values?.id || 0);
    drugName.value =
      data.drug_name || data.values?.drug_name || `药品#${drugId.value}`;
    productType.value = Number(data.productType || data.type || 2);
    productGridApi.value = data.gridApi;
    formApi.setValues({
      drug_id: drugId.value,
      drug_name: drugName.value,
      market_price: undefined,
      price: undefined,
    });
  },
});
</script>
<template>
  <Modal :title="`总仓入库 - ${drugName}`" class="w-[420px]">
    <Form />
  </Modal>
</template>
