<template>
  <wd-popup v-model="visible" position="bottom" :safe-area-inset-bottom="true" custom-style="border-radius: 16px 16px 0 0;">
    <view class="min-h-[400px] bg-gray-50 text-gray-600 px-4 pb-4">
      <view class="h-12 flex items-center justify-center font-semibold text-lg text-gray-800">设置客户查询价</view>
      <view class="rounded-xl bg-white p-4 shadow">
        <view class="text-base text-gray-700 mb-2">客户查询价 (元)</view>
        <input
          v-model="priceStr"
          type="digit"
          class="border-b border-gray-200 py-2 text-2xl"
          :placeholder="pricePlaceholder"
          @blur="onBlurPrice"
        />
        <view class="flex justify-between mt-3 text-sm">
          <text>推广收益为</text>
          <text class="text-orange-500 font-medium">¥ {{ promotionRevenue }}</text>
        </view>
        <view class="flex justify-between mt-1 text-sm">
          <text>底价成本 ¥ {{ baseCost }}</text>
          <text>提价成本 ¥ {{ raiseCost }}</text>
        </view>
      </view>
      <view class="rounded-xl bg-white p-4 mt-3 shadow">
        <view class="text-base mb-2 text-gray-800">收益与成本说明</view>
        <text class="text-sm">推广收益 = 客户查询价 - 我的成本</text>
        <text class="text-sm block mt-1">我的成本 = 实际底价 + 提价成本</text>
        <text class="text-sm block mt-1">设定范围：¥{{ productConfig?.price_range_min ?? 0 }} - ¥{{ productConfig?.price_range_max ?? 9999 }}</text>
      </view>
      <wd-button type="primary" block class="mt-4" @click="onConfirm">确认</wd-button>
    </view>
  </wd-popup>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  show: { type: Boolean, default: false },
  defaultPrice: { type: Number, required: true },
  productConfig: { type: Object, required: true },
})

const emit = defineEmits(['update:show', 'change'])

const visible = computed({
  get: () => props.show,
  set: (v) => emit('update:show', v),
})

const pricePlaceholder = computed(() => {
  const cfg = props.productConfig
  const min = cfg?.price_range_min ?? 0
  const max = cfg?.price_range_max ?? 9999
  return `${min} - ${max}`
})

const priceStr = ref('')

watch(
  () => props.show,
  (show) => {
    if (show) priceStr.value = String(props.defaultPrice ?? '')
  },
)

function safeTruncate(num, decimals = 2) {
  if (isNaN(num) || !isFinite(num)) return '0.00'
  const factor = 10 ** decimals
  const scaled = Math.trunc(num * factor)
  return (scaled / factor).toFixed(decimals)
}

const baseCost = computed(() => {
  if (!props.productConfig?.actual_base_price) return '0.00'
  return safeTruncate(Number(props.productConfig.actual_base_price))
})

const raiseCost = computed(() => {
  const cfg = props.productConfig
  if (!cfg) return '0.00'
  const priceNum = Number(priceStr.value) || 0
  const threshold = Number(cfg.price_threshold) || 0
  const rate = Number(cfg.price_fee_rate) || 0
  let cost = 0
  if (priceNum > threshold) cost = (priceNum - threshold) * rate
  return safeTruncate(cost)
})

const costPrice = computed(() => {
  const base = parseFloat(baseCost.value) || 0
  const raise = parseFloat(raiseCost.value) || 0
  return base + raise
})

const promotionRevenue = computed(() => {
  const priceNum = Number(priceStr.value) || 0
  return safeTruncate(Math.max(0, priceNum - costPrice.value))
})

function validatePrice() {
  const cfg = props.productConfig
  const min = Number(cfg?.price_range_min) ?? 0
  const max = Number(cfg?.price_range_max) ?? Infinity
  let num = Number(priceStr.value)
  if (isNaN(num)) {
    num = props.defaultPrice
    uni.showToast({ title: '请输入有效价格', icon: 'none' })
    return { valid: false, value: num }
  }
  if (num < min) {
    uni.showToast({ title: `价格不能低于 ${min} 元`, icon: 'none' })
    priceStr.value = String(min)
    return { valid: false, value: min }
  }
  if (num > max) {
    uni.showToast({ title: `价格不能高于 ${max} 元`, icon: 'none' })
    priceStr.value = String(max)
    return { valid: false, value: max }
  }
  return { valid: true, value: num }
}

function onBlurPrice() {
  const { value } = validatePrice()
  if (value != null) priceStr.value = String(value)
}

function onConfirm() {
  const { valid, value } = validatePrice()
  if (valid) {
    emit('change', value)
    visible.value = false
  }
}
</script>
