<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';

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

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

import type { QuickDiscountOption } from '#/utils/pricePercentAdjust';
import {
  applyRatioPrice,
  formatPriceDiscountLabel,
  normalizeQuickOptions,
  resolvePriceDiscount,
} from '#/utils/pricePercentAdjust';
import { adjustOrderPercent } from '#/api/order/priceAdjust';

defineOptions({ name: 'OrderPricePercentAdjustDrawer' });

type DrawerData = {
  stage: 'pre_send' | 'post_order';
  priceDiscount?: number;
  price_discount?: number;
  productOrderId?: number;
  registerId?: number;
  priceAdjustScope?: 'both' | 'sale_only';
  quickOptions?: QuickDiscountOption[];
  previewOriginPrice?: number;
  onApplyPreSend?: (payload: { priceDiscount: number }) => void;
  onSuccess?: () => void;
};

const loading = ref(false);
const priceDiscount = ref<number>(100);
const formData = ref<DrawerData>({ stage: 'pre_send', quickOptions: [] });

const currentLabel = computed(() => formatPriceDiscountLabel(priceDiscount.value));

const previewPrice = computed(() => {
  const base = Number(formData.value.previewOriginPrice ?? 0);
  if (!base) return null;
  return applyRatioPrice(base, priceDiscount.value);
});

const discountQuickOptions = computed(() =>
  (formData.value.quickOptions || []).filter((o) => o.value < 100),
);
const markupQuickOptions = computed(() =>
  (formData.value.quickOptions || []).filter((o) => o.value > 100),
);

const [DrawerComponent, drawerApi] = useVbenDrawer({
  class: 'w-[520px]',
  onConfirm: async () => {
    const d = Number(priceDiscount.value);
    if (!d || d <= 0) {
      message.warning('请输入有效比例值');
      return;
    }
    if (formData.value.stage === 'pre_send') {
      formData.value.onApplyPreSend?.({ priceDiscount: d });
      drawerApi.close();
      return;
    }
    loading.value = true;
    try {
      await adjustOrderPercent({
        product_order_id: formData.value.productOrderId,
        price_discount: d,
        register_id: formData.value.registerId || 0,
      });
      message.success(d === 100 ? '已清除价格浮动' : '调价成功');
      formData.value.onSuccess?.();
      drawerApi.close();
    } catch (e: any) {
      message.error(e?.message || '调价失败');
    } finally {
      loading.value = false;
    }
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = { stage: 'pre_send', quickOptions: [] };
      priceDiscount.value = 100;
    }
  },
});

function syncFromDrawerData() {
  const data = drawerApi.getData<DrawerData>();
  const discount = resolvePriceDiscount(data);
  formData.value = {
    ...data,
    stage: data.stage || 'pre_send',
    quickOptions: normalizeQuickOptions(data.quickOptions),
    priceDiscount: discount,
    price_discount: discount,
  };
  priceDiscount.value = discount;
}

function scheduleSyncFromDrawerData() {
  void nextTick(() => {
    syncFromDrawerData();
    void nextTick(() => syncFromDrawerData());
  });
}

const drawerIsOpen = drawerApi.useStore((state) => state.isOpen);

watch(drawerIsOpen, (isOpen) => {
  if (isOpen) {
    scheduleSyncFromDrawerData();
  }
});

function pickQuick(opt: QuickDiscountOption) {
  priceDiscount.value = opt.value;
}

function clearFloat() {
  priceDiscount.value = 100;
}

defineExpose({ drawerApi });
</script>

<template>
  <DrawerComponent title="整单调价" :loading="loading">
    <Descriptions v-if="currentLabel" :column="1" bordered size="small" class="mb-4">
      <Descriptions.Item label="当前浮动">
        <Tag color="processing">{{ currentLabel }}（{{ priceDiscount }}%）</Tag>
      </Descriptions.Item>
    </Descriptions>

    <Form layout="vertical">
      <Form.Item label="价格比例（100=原价，90=九折，120=涨20%）">
        <InputNumber v-model:value="priceDiscount" :min="1" :max="500" class="w-full" />
      </Form.Item>

      <Form.Item v-if="discountQuickOptions.length" label="快捷打折">
        <Space wrap>
          <Button
            v-for="opt in discountQuickOptions"
            :key="'d-' + opt.value"
            size="small"
            @click="pickQuick(opt)"
          >
            {{ opt.name }}（{{ opt.value }}%）
          </Button>
        </Space>
      </Form.Item>

      <Form.Item v-if="markupQuickOptions.length" label="快捷涨价">
        <Space wrap>
          <Button
            v-for="opt in markupQuickOptions"
            :key="'m-' + opt.value"
            size="small"
            @click="pickQuick(opt)"
          >
            {{ opt.name }}（{{ opt.value }}%）
          </Button>
        </Space>
      </Form.Item>

      <Form.Item v-if="previewPrice != null" label="示例：原价100预览">
        <span class="text-primary font-medium">￥{{ previewPrice.toFixed(4) }}</span>
      </Form.Item>

      <Button block @click="clearFloat">清除浮动（恢复100%）</Button>
    </Form>
  </DrawerComponent>
</template>
