<script setup lang="ts">
import { ref } from 'vue';
import { Form, InputNumber, message } from 'ant-design-vue';
import { useVbenModal } from '@vben/common-ui';
import { updateErpQtyFactor } from '../api';

defineOptions({
  name: 'ErpQtyFactorModal',
});

const formRef = ref();
const loading = ref(false);

const formData = ref<{
  id?: number;
  drugName?: string;
  currentFactor?: number;
}>({});

const erpQtyFactor = ref<number>(1);

const [ModalComponent, modalApi] = useVbenModal({
  class: 'w-[500px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!formRef.value) {
      return;
    }
    try {
      await formRef.value.validate();
    } catch (error) {
      return;
    }
    if (!formData.value.id || erpQtyFactor.value === null) {
      message.error('参数不完整');
      return;
    }

    loading.value = true;
    try {
      await updateErpQtyFactor({
        id: formData.value.id,
        erp_qty_factor: erpQtyFactor.value,
      });
      message.success('设置成功');
      modalApi.close();
      const gridApi = modalApi.getData()?.gridApi;
      if (gridApi) {
        gridApi.query();
      }
    } catch (error: any) {
      console.error('设置失败:', error);
      message.error(error?.message || '设置失败，请重试');
    } finally {
      loading.value = false;
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<typeof formData.value & { gridApi?: any }>();
      if (data) {
        const current = data.currentFactor ?? data.erp_qty_factor;
        formData.value = {
          id: data.id,
          drugName: data.drugName || data.drug_name,
          currentFactor: current != null && current !== '' ? Number(current) : 1,
        };
        erpQtyFactor.value = formData.value.currentFactor ?? 1;
      }
    } else {
      formData.value = {};
      erpQtyFactor.value = 1;
    }
  },
});
</script>

<template>
  <ModalComponent
    title="设置ERP抓取数量倍数"
    :loading="loading"
  >
    <div v-if="formData.drugName" class="erp-qty-factor-modal">
      <div class="mb-4">
        <p><strong>药品名称：</strong>{{ formData.drugName }}</p>
        <p class="mt-2">
          <strong>当前倍数：</strong>{{ Number(formData.currentFactor ?? 1).toFixed(2) }}
        </p>
      </div>

      <Form ref="formRef" :model="{ erpQtyFactor }" layout="vertical">
        <Form.Item
          label="ERP抓取数量倍数"
          name="erpQtyFactor"
          :rules="[
            { required: true, message: '请输入ERP抓取数量倍数' },
            { type: 'number', min: 0.01, message: '倍数必须大于0' },
          ]"
        >
          <InputNumber
            v-model:value="erpQtyFactor"
            :min="0.01"
            :precision="2"
            :step="1"
            style="width: 100%"
            placeholder="请输入ERP抓取数量倍数，默认1"
          />
        </Form.Item>
        <p class="text-gray-500 text-sm mt-2">
          提示：ERP拉取订单时，数量 = 订单数量 × 该倍数
        </p>
      </Form>
    </div>
  </ModalComponent>
</template>

<style scoped>
.erp-qty-factor-modal {
  padding: 8px 0;
}
</style>
