<template>
  <view class="min-h-screen p-4 promote">
    <view class="mb-4 card !bg-gradient-to-b from-orange-200 to-orange-200/80">
      <view>
        <text class="text-lg font-bold text-orange-500 block">直推用户查询</text>
        <text class="font-bold text-orange-400 mt-1 block">自定义价格，赚取差价</text>
      </view>

      <view class="mt-6">
        <view class="mt-2 text-gray-600 bg-orange-100 rounded-xl px-4 py-2">
          在下方 "自定义价格" 处选择报告类型，设置客户查询价（元）即可立即推广。
        </view>
      </view>
    </view>
    <VipBanner />

    <!-- 推广内容 -->
    <view>
      <view class="card mb-4">
        <view>
          <text class="text-xl font-semibold mb-2 block">生成推广码</text>
          <wd-form :model="formData" ref="promotionForm">
            <wd-cell-group border>
              <!-- 报告类型 -->
              <wd-picker label="报告类型" label-width="100px" v-model="formData.productType" :columns="[reportTypes]"
                title="选择报告类型" prop="productType" placeholder="请选择报告类型" @confirm="onConfirmType"
                :rules="[{ required: true, message: '请选择报告类型' }]" />

              <!-- 定价 -->
              <wd-input label="客户查询价" label-width="100px" v-model="formData.clientPrice" placeholder="请输入价格" readonly
                clickable @click="showPricePicker = true" prop="clientPrice"   suffix-icon="arrow-right"
                :rules="[{ required: true, message: '请输入客户查询价' }]" />
            </wd-cell-group>

            <view class="flex items-center justify-between my-2">
              <text class="text-sm text-gray-500">推广收益为 <text class="text-orange-500">{{ promotionRevenue }}</text>
                元</text>
              <text class="text-sm text-gray-500">我的成本为 <text class="text-orange-500">{{ costPrice }}</text> 元</text>
            </view>
          </wd-form>
        </view>

        <view class="mt-6">
          <button type="primary" block @click="generatePromotionCode">点击立即推广</button>
        </view>
      </view>
    </view>
    <PriceInputPopup v-model:show="showPricePicker" :default-price="formData.clientPrice"
      :product-config="pickerProductConfig" @change="onPriceChange" />

    <QRcode v-model:show="showQRcode" :linkIdentifier="linkIdentifier" />
  </view>
</template>

<script setup>
import { getProductConfig, generatePromotionLink } from '@/apis/agent'
import PriceInputPopup from '@/components/PriceInputPopup.vue'
import VipBanner from '@/components/VipBanner.vue'
import QRcode from '@/components/QRcode.vue'

// 报告类型
const reportTypes = [
  { label: '人事背调', value: 'backgroundcheck', id: 1 },
  { label: '老板企业报告', value: 'companyinfo', id: 2 },
  { label: '家政风险', value: 'homeservice', id: 3 },
  { label: '婚恋风险', value: 'marriage', id: 4 },
  { label: '贷前背调', value: 'preloanbackgroundcheck', id: 5 },
  { label: '租赁风险', value: 'rentalrisk', id: 6 },
  { label: '个人风险', value: 'riskassessment', id: 7 }
]

// 状态管理
const promotionForm = ref(null)
const showPricePicker = ref(false)
const pickerProductConfig = ref(null)
const productConfig = ref(null)
const linkIdentifier = ref("")
const showQRcode = ref(false)

// 表单数据对象
const formData = ref({
  productType: '',
  clientPrice: null
})

// 计算成本价格
const costPrice = computed(() => {
  if (!pickerProductConfig.value) return '0.00'
  // 平台定价成本
  let platformPricing = 0
  platformPricing += pickerProductConfig.value.cost_price
  if (formData.value.clientPrice > pickerProductConfig.value.p_pricing_standard) {
    platformPricing += (formData.value.clientPrice - pickerProductConfig.value.p_pricing_standard) * pickerProductConfig.value.p_overpricing_ratio
  }

  if (pickerProductConfig.value.a_pricing_standard > platformPricing &&
    pickerProductConfig.value.a_pricing_end > platformPricing &&
    pickerProductConfig.value.a_overpricing_ratio > 0) {
    if (formData.value.clientPrice > pickerProductConfig.value.a_pricing_standard) {
      if (formData.value.clientPrice > pickerProductConfig.value.a_pricing_end) {
        platformPricing += (pickerProductConfig.value.a_pricing_end - pickerProductConfig.value.a_pricing_standard) * pickerProductConfig.value.a_overpricing_ratio
      } else {
        platformPricing += (formData.value.clientPrice - pickerProductConfig.value.a_pricing_standard) * pickerProductConfig.value.a_overpricing_ratio
      }
    }
  }

  return safeTruncate(platformPricing)
})

// 计算推广收益
const promotionRevenue = computed(() => {
  return safeTruncate(formData.value.clientPrice - costPrice.value)
})

// 安全截断数字（保留2位小数）
function safeTruncate(num, decimals = 2) {
  if (isNaN(num) || !isFinite(num)) return "0.00"

  const factor = 10 ** decimals
  const scaled = Math.trunc(num * factor)
  const truncated = scaled / factor

  return truncated.toFixed(decimals)
}

// 生成推广码
const generatePromotionCode = async () => {
  // 表单验证
  try {
    await promotionForm.value.validate()
  } catch (e) {
    return
  }

  try {
    // 获取选中产品的完整信息
    const reportType = reportTypes.find(item => item.value === formData.value.productType)
    if (!reportType) {
      uni.showToast({
        title: '请选择有效的报告类型',
        icon: 'none'
      })
      return
    }

    const res = await generatePromotionLink({
      product: formData.value.productType,
      price: formData.value.clientPrice
    })

    if (res.code === 200) {
      linkIdentifier.value = res.data.link_identifier
      showQRcode.value = true
    } else {
      uni.showToast({
        title: res.msg || '生成推广码失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 选择类型
const selectProductType = (reportTypeValue) => {
  const reportType = reportTypes.find(item => item.id === reportTypeValue || item.value === reportTypeValue)

  if (!reportType) return

  formData.value.productType = reportType.value

  if (productConfig.value) {
    for (let i of productConfig.value) {
      if (i.product_id === reportType.id) {
        pickerProductConfig.value = i
        formData.value.clientPrice = i.p_pricing_standard.toString()
      }
    }
  }
}

// 获取产品配置
const getPromoteConfig = async () => {
  try {
    const res = await getProductConfig()

    if (res.code === 200) {
      productConfig.value = res.data.AgentProductConfig
      // 选择第一个报告类型
      selectProductType(1) // 使用ID 1选择第一个报告类型
    } else {
      uni.showToast({
        title: res.msg || '获取配置失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.log(error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 价格变更
const onPriceChange = (price) => {
  formData.value.clientPrice = price
}

// 类型选择确认
const onConfirmType = (e) => {
  // picker在单列模式下返回的是选中项的值
  if (e && e.value && e.value.length > 0) {
    const selectedValue = e.value[0]
    selectProductType(selectedValue)
  }
}

// 页面加载
onMounted(() => {
  getPromoteConfig()
})
</script>

<style>
.card {
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  margin-bottom: 16px;
}
</style>
<route type="page" lang="json">{
  "layout": "page",
  "title": "推广",
  "agent": true,
  "auth": true
}</route>
