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

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

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

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

const minPrice = ref<number | null>(null);

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 || minPrice.value === null) {
      message.error('参数不完整');
      return;
    }

    loading.value = true;
    try {
      await updateMinAdjustPrice({
        id: formData.value.id,
        min_adjust_price: minPrice.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) {
        formData.value = {
          id: data.id,
          drugName: data.drugName || data.drug_name,
          currentMinPrice: data.currentMinPrice || data.min_adjust_price || null,
        };
        minPrice.value = formData.value.currentMinPrice;
      }
    } else {
      formData.value = {};
      minPrice.value = null;
    }
  },
});
</script>

<template>
  <ModalComponent
    title="设置最低调整金额"
    :loading="loading"
  >
    <div v-if="formData.drugName" class="min-price-modal">
      <div class="mb-4">
        <p><strong>药品名称：</strong>{{ formData.drugName }}</p>
        <p v-if="formData.currentMinPrice" class="mt-2">
          <strong>当前最低调整金额：</strong>￥{{ Number(formData.currentMinPrice).toFixed(2) }}
        </p>
        <p v-else class="mt-2" style="color: #999">
          <strong>当前最低调整金额：</strong>未设置
        </p>
      </div>

      <Form ref="formRef" :model="{ minPrice }" layout="vertical">
        <Form.Item
          label="最低调整金额"
          name="minPrice"
          :rules="[
            { required: true, message: '请输入最低调整金额' },
            { type: 'number', min: 0, message: '金额不能小于0' },
          ]"
        >
          <InputNumber
            v-model:value="minPrice"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入最低调整金额（设置为0或留空表示不允许调整）"
          />
        </Form.Item>
        <p class="text-gray-500 text-sm mt-2">
          提示：设置为0或留空表示该商品不允许调整价格
        </p>
      </Form>
    </div>
  </ModalComponent>
</template>

<style scoped>
.min-price-modal {
  padding: 8px 0;
}
</style>
