<script setup lang="ts">
/**
 * 设置药品改价底价与最高价
 * 商户改价、订单调价须落在该区间；可按总仓售价快捷填入上下 30%
 */
import { computed, ref } from 'vue';

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

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

import { updateMinAdjustPrice } from '../api';

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

/** 相对总仓售价的浮动比例（上下各 30%） */
const CENTRAL_PRICE_RANGE_RATIO = 0.3;

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

const formData = ref<{
  id?: number;
  drugName?: string;
  currentMinPrice?: number | null;
  currentMaxPrice?: number | null;
  /** 总仓售价，用于快捷填区间 */
  centralPrice?: number | null;
}>({});

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

/** 是否有可用总仓售价 */
const hasCentralPrice = computed(() => {
  const p = Number(formData.value.centralPrice);
  return Number.isFinite(p) && p > 0;
});

/** 预览：底价 = 售价×0.7，最高价 = 售价×1.3 */
const previewRange = computed(() => {
  if (!hasCentralPrice.value) return null;
  const base = Number(formData.value.centralPrice);
  const min = Number((base * (1 - CENTRAL_PRICE_RANGE_RATIO)).toFixed(2));
  const max = Number((base * (1 + CENTRAL_PRICE_RANGE_RATIO)).toFixed(2));
  return { min, max, base };
});

/**
 * 快捷填入总仓售价上下 30% 区间
 * 为什么：运营批量设价时以总仓建议售价为基准，避免手工算错
 */
function fillByCentralPriceRange() {
  if (!previewRange.value) {
    message.warning('暂无总仓售价，无法快捷填入');
    return;
  }
  minPrice.value = previewRange.value.min;
  maxPrice.value = previewRange.value.max;
  message.success(
    `已填入：￥${previewRange.value.min.toFixed(2)} ~ ￥${previewRange.value.max.toFixed(2)}`,
  );
}

const [ModalComponent, modalApi] = useVbenModal({
  class: 'w-[500px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    if (!formRef.value) {
      return;
    }
    try {
      await formRef.value.validate();
    } catch {
      return;
    }
    if (!formData.value.id || minPrice.value === null) {
      message.error('参数不完整');
      return;
    }
    if (
      maxPrice.value !== null &&
      maxPrice.value > 0 &&
      minPrice.value > maxPrice.value
    ) {
      message.error('最高价不能低于底价');
      return;
    }

    loading.value = true;
    try {
      await updateMinAdjustPrice({
        id: formData.value.id,
        min_adjust_price: minPrice.value,
        // 始终提交最高价字段：null/0 表示清空上限
        max_adjust_price:
          maxPrice.value && maxPrice.value > 0 ? maxPrice.value : 0,
      });
      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;
          min_adjust_price?: number | null;
          max_adjust_price?: number | null;
          central_price?: number | null;
          drug_name?: string;
        }
      >();
      if (data) {
        const central = Number(
          data.centralPrice ?? data.central_price ?? 0,
        );
        formData.value = {
          id: data.id,
          drugName: data.drugName || data.drug_name,
          currentMinPrice: data.currentMinPrice || data.min_adjust_price || null,
          currentMaxPrice: data.currentMaxPrice || data.max_adjust_price || null,
          centralPrice: central > 0 ? central : null,
        };
        minPrice.value = formData.value.currentMinPrice;
        maxPrice.value = formData.value.currentMaxPrice;
      }
    } else {
      formData.value = {};
      minPrice.value = null;
      maxPrice.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="hasCentralPrice" class="mt-1 text-sm text-gray-600">
          总仓售价：￥{{ Number(formData.centralPrice).toFixed(2) }}
        </p>
        <p class="mt-2 text-sm text-gray-500">
          商户改价与订单调价须落在底价～最高价之间；最高价留空表示不限制上限。
        </p>
      </div>

      <div class="mb-4">
        <Button
          type="primary"
          ghost
          :disabled="!hasCentralPrice"
          @click="fillByCentralPriceRange"
        >
          快捷填入总仓售价 ±30%
        </Button>
        <p v-if="previewRange" class="mt-2 text-xs text-gray-500">
          将填入 ￥{{ previewRange.min.toFixed(2) }} ~
          ￥{{ previewRange.max.toFixed(2) }}
          （售价 ￥{{ previewRange.base.toFixed(2) }} × 0.7 / 1.3）
        </p>
        <p v-else class="mt-2 text-xs text-orange-500">
          该药品暂无总仓售价，请先入库总仓后再使用快捷填入。
        </p>
      </div>

      <Form ref="formRef" :model="{ minPrice, maxPrice }" 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>
        <Form.Item label="最高价" name="maxPrice">
          <InputNumber
            v-model:value="maxPrice"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入最高价（留空或0表示不限制）"
          />
        </Form.Item>
      </Form>
    </div>
  </ModalComponent>
</template>

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