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

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

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

const formData = ref<{
  productOrderId?: number;
  productOrderItemId?: number;
  drugId?: number;
  drugName?: string;
  currentPrice?: number;
  minAdjustPrice?: number;
  registerId?: number | null;
  onSuccess?: () => void;
}>({});

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

// 价格验证规则
const getPriceRules = () => {
  return [
    { required: true, message: '请输入新价格' },
    {
      validator: (_rule: any, value: any) => {
        return new Promise<void>((resolve, reject) => {
          if (!value && value !== 0) {
            reject(new Error('请输入新价格'));
            return;
          }
          const minPrice = formData.value.minAdjustPrice ? Number(formData.value.minAdjustPrice) : 0;
          if (minPrice > 0 && Number(value) < minPrice) {
            reject(new Error(`新价格不能低于最低调整金额：￥${minPrice.toFixed(2)}`));
            return;
          }
          resolve();
        });
      },
    },
  ];
};

const [DrawerComponent, drawerApi] = useVbenDrawer({
  class: 'w-[500px]',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    // 验证表单
    if (!formRef.value) {
      return;
    }
    try {
      await formRef.value.validate();
    } catch (error) {
      return;
    }
    if (!formData.value.productOrderId || !formData.value.productOrderItemId || !newPrice.value) {
      message.error('参数不完整');
      return;
    }

    const minPrice = formData.value.minAdjustPrice ? Number(formData.value.minAdjustPrice) : 0;
    if (minPrice > 0 && newPrice.value < minPrice) {
      message.error(`新价格不能低于最低调整金额：￥${minPrice.toFixed(2)}`);
      return;
    }

    loading.value = true;
    try {
      await adjustOrderItemPrice({
        product_order_id: formData.value.productOrderId,
        product_order_item_id: formData.value.productOrderItemId,
        new_price: newPrice.value,
        register_id: formData.value.registerId || 0,
      });
      message.success('价格调整成功');
      
      // 先执行回调刷新列表，再关闭抽屉
      const onSuccessCallback = formData.value.onSuccess;
      if (onSuccessCallback) {
        onSuccessCallback();
      }
      
      // 延迟关闭，确保回调执行完成
      setTimeout(() => {
        drawerApi.close();
      }, 100);
    } catch (error: any) {
      console.error('调整价格失败:', error);
      message.error(error?.message || '调整价格失败，请重试');
    } finally {
      loading.value = false;
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = drawerApi.getData<typeof formData.value>();
      if (data) {
        formData.value = {
          ...data,
          currentPrice: data.currentPrice ? Number(data.currentPrice) : undefined,
          minAdjustPrice: data.minAdjustPrice ? Number(data.minAdjustPrice) : undefined,
        };
        newPrice.value = formData.value.currentPrice || null;
      }
    } else {
      formData.value = {};
      newPrice.value = null;
    }
  },
});
</script>

<template>
  <DrawerComponent
    title="调整商品价格"
    :loading="loading"
  >
    <div v-if="formData.drugName" class="price-adjust-modal">
      <Descriptions :column="1" bordered size="small" class="mb-4">
        <Descriptions.Item label="药品名称">
          {{ formData.drugName }}
        </Descriptions.Item>
        <Descriptions.Item label="当前价格">
          ￥{{ formData.currentPrice ? Number(formData.currentPrice).toFixed(4) : '0.0000' }}
        </Descriptions.Item>
        <Descriptions.Item label="最低调整金额">
          <span v-if="formData.minAdjustPrice && Number(formData.minAdjustPrice) > 0">
            ￥{{ Number(formData.minAdjustPrice).toFixed(2) }}
          </span>
          <span v-else style="color: #999">未设置</span>
        </Descriptions.Item>
      </Descriptions>

      <Form ref="formRef" :model="{ newPrice }" layout="vertical">
        <Form.Item
          label="新价格"
          name="newPrice"
          :rules="getPriceRules()"
        >
          <InputNumber
            v-model:value="newPrice"
            :min="formData.minAdjustPrice ? Number(formData.minAdjustPrice) : 0"
            :precision="4"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入新价格"
          />
        </Form.Item>
      </Form>
    </div>
  </DrawerComponent>
</template>

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