<template>
  <view class="page-invite">
    <!-- 顶部装饰背景 -->
    <view class="hero-bg">
      <view class="hero-circle hero-circle-1"></view>
      <view class="hero-circle hero-circle-2"></view>
      <view class="hero-circle hero-circle-3"></view>
    </view>

    <!-- 顶部标题区 -->
    <view class="header-section">
      <view class="header-icon">
        <u-icon name="gift-fill" :size="32" color="#FF6B35" />
      </view>
      <text class="header-title">邀请好友，共享收益</text>
      <text class="header-subtitle">好友下单，双方获利，躺赚现金奖励</text>
    </view>

    <!-- 余额卡片 -->
    <view class="balance-card">
      <view class="balance-left">
        <view class="balance-header">
          <u-icon name="rmb-circle-fill" :size="18" color="#FF6B35" />
          <text class="balance-title">我的收益</text>
        </view>
        <view class="balance-amount">
          <text class="balance-value">¥{{ wallet.availableBalance || '0.00' }}</text>
          <text v-if="!canWithdraw && config?.config" class="balance-tip">
            满{{ config.config.withdrawThreshold }}元可提现
          </text>
        </view>
      </view>

      <view class="balance-actions">
        <view
          class="action-btn action-btn-primary"
          :class="{ disabled: !canWithdraw }"
          @tap="goWithdraw"
        >
          <text class="action-btn-text">提现</text>
        </view>
        <view class="action-btn action-btn-secondary" @tap="goWithdrawals">
          <text class="action-btn-text">记录</text>
        </view>
      </view>
    </view>

    <!-- 数据统计卡片 -->
    <view class="stats-card">
      <view class="stats-header">
        <u-icon name="list" :size="20" color="#FF6B35" />
        <text class="stats-title">邀请数据</text>
      </view>

      <view class="stats-grid">
        <view class="stat-item">
          <view class="stat-icon-wrapper stat-icon-blue">
            <u-icon name="account-fill" :size="20" color="#4A90E2" />
          </view>
          <text class="stat-value">{{ stats.totalInvites || 0 }}</text>
          <text class="stat-label">邀请人数</text>
        </view>

        <view class="stat-item">
          <view class="stat-icon-wrapper stat-icon-green">
            <u-icon name="shopping-cart-fill" :size="20" color="#52C41A" />
          </view>
          <text class="stat-value">{{ stats.totalOrders || 0 }}</text>
          <text class="stat-label">成功下单</text>
        </view>

        <view class="stat-item">
          <view class="stat-icon-wrapper stat-icon-orange">
            <u-icon name="rmb-circle-fill" :size="20" color="#FF8C00" />
          </view>
          <text class="stat-value">¥{{ stats.totalCashback || '0.00' }}</text>
          <text class="stat-label">累计收益</text>
        </view>
      </view>
    </view>

    <!-- 邀请操作区 -->
    <view class="invite-actions">
      <view class="action-card action-card-primary" @tap="handleShare">
        <view class="action-card-icon">
          <u-icon name="share-fill" :size="28" color="#ffffff" />
        </view>
        <view class="action-card-content">
          <text class="action-card-title">分享给好友</text>
          <text class="action-card-desc">微信、朋友圈快速分享</text>
        </view>
        <u-icon name="arrow-right" :size="18" color="rgba(255,255,255,0.8)" />
      </view>

      <view class="action-card action-card-secondary" @tap="goPoster">
        <view class="action-card-icon">
          <u-icon name="photo-fill" :size="28" color="#FF6B35" />
        </view>
        <view class="action-card-content">
          <text class="action-card-title">生成邀请海报</text>
          <text class="action-card-desc">保存图片，随时分享</text>
        </view>
        <u-icon name="arrow-right" :size="18" color="#999" />
      </view>
    </view>

    <!-- 活动规则 -->
    <view class="rules-card">
      <view class="rules-header">
        <u-icon name="file-text-fill" :size="20" color="#FF6B35" />
        <text class="rules-title">活动规则</text>
      </view>

      <view v-if="config?.config" class="rules-content">
        <view v-for="(rule, index) in rules" :key="index" class="rule-item">
          <view class="rule-number">{{ index + 1 }}</view>
          <view class="rule-content">
            <text class="rule-title-text">{{ rule.title }}</text>
            <text class="rule-desc" v-html="rule.desc"></text>
          </view>
        </view>
      </view>

      <view v-else class="rules-loading">
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 底部记录入口 -->
    <view class="bottom-records">
      <view class="record-link" @tap="goRecords">
        <u-icon name="account" :size="16" color="#666" />
        <text class="record-text">邀请记录</text>
        <u-icon name="arrow-right" :size="14" color="#999" />
      </view>

      <view class="record-divider"></view>

      <view class="record-link" @tap="goCashbacks">
        <u-icon name="rmb-circle" :size="16" color="#666" />
        <text class="record-text">返现记录</text>
        <u-icon name="arrow-right" :size="14" color="#999" />
      </view>
    </view>

    <!-- 底部安全提示 -->
    <view class="bottom-tip">
      <u-icon name="checkmark-circle-fill" :size="14" color="#52C41A" />
      <text class="tip-text">平台担保，收益安全可靠</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getInviteStats, getInviteConfig } from '@/api/user/invite';
import { walletApi } from '@/api/user/wallet';
import { useUserStore } from '@/store/user';

const stats = ref<any>({
  totalInvites: 0,
  totalOrders: 0,
  totalCashback: 0,
});

const wallet = ref<any>({
  availableBalance: 0,
});

const config = ref<any>(null);

const userStore = useUserStore();

const canWithdraw = computed(() => {
  const threshold = config.value?.config?.withdrawThreshold || 10;
  return Number(wallet.value.availableBalance) >= threshold;
});

// 格式化百分比，去掉多余的0
const formatPercent = (rate: number) => {
  const percent = rate * 100;
  // 使用parseFloat自动去掉末尾的0
  return parseFloat(percent.toFixed(2));
};

// 动态生成活动规则
const rules = computed(() => {
  if (!config.value?.config) return [];

  const cfg = config.value.config;
  const maxOrderIndex = cfg.maxOrderIndex || 2;

  return [
    {
      title: '首单高返',
      desc: `好友首次下单，您可获得订单金额 ${formatPercent(cfg.firstOrderRate)}% 返现`,
    },
    {
      title: maxOrderIndex > 1 ? '持续收益' : '返现次数',
      desc: maxOrderIndex > 1
        ? `好友再次下单，您仍可获得 ${formatPercent(cfg.secondOrderRate)}% 返现奖励（最多前${maxOrderIndex}单）`
        : '每位好友仅首单可获得返现',
    },
    {
      title: '返现限额',
      desc: `单笔返现最低 ${cfg.minCashback}元，最高 ${cfg.maxCashback}元`,
    },
    {
      title: '提现门槛',
      desc: `余额满 ${cfg.withdrawThreshold}元 即可提现，实时到账`,
    },
  ];
});

onMounted(() => {
  fetchStats();
  fetchWallet();
  fetchConfig();
});

async function fetchStats() {
  try {
    const res = await getInviteStats();
    stats.value = res.data || {};
  } catch (e) {
    console.error('获取邀请数据失败:', e);
  }
}

async function fetchWallet() {
  try {
    const res = await walletApi.getWallet();
    wallet.value = res.data || {};
  } catch (e) {
    console.error('获取钱包信息失败:', e);
  }
}

async function fetchConfig() {
  try {
    const res = await getInviteConfig();
    config.value = res.data || null;
  } catch (e) {
    console.error('获取活动配置失败:', e);
  }
}

function handleShare() {
  uni.showToast({ title: '请点击右上角分享', icon: 'none' });
}

function goWithdraw() {
  if (!canWithdraw.value) {
    const threshold = config.value?.config?.withdrawThreshold || 10;
    uni.showToast({ title: `余额不足${threshold}元，暂不可提现`, icon: 'none' });
    return;
  }
  uni.navigateTo({ url: '/pages/wallet/withdraw' });
}

function goWithdrawals() {
  uni.navigateTo({ url: '/pages/wallet/withdrawals' });
}

function goRecords() {
  uni.navigateTo({ url: '/pages/invite/records' });
}

function goCashbacks() {
  uni.navigateTo({ url: '/pages/invite/cashbacks' });
}

function goPoster() {
  uni.navigateTo({ url: '/pages/invite/poster' });
}
</script>

<style lang="scss" scoped>
@import '@/static/styles/design-tokens.scss';
@import '@/static/styles/mixins.scss';

.page-invite {
  min-height: 100vh;
  background: linear-gradient(180deg, #FFF5F0 0%, #F5F7FA 100%);
  padding-bottom: 40rpx;
  position: relative;
  overflow: hidden;
}

/* ========== 顶部装饰背景 ========== */
.hero-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  overflow: hidden;
  z-index: 0;
}

.hero-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
}

.hero-circle-1 {
  width: 300rpx;
  height: 300rpx;
  background: #FF6B35;
  top: -100rpx;
  right: -50rpx;
}

.hero-circle-2 {
  width: 200rpx;
  height: 200rpx;
  background: #FF8C5A;
  top: 100rpx;
  left: -80rpx;
}

.hero-circle-3 {
  width: 150rpx;
  height: 150rpx;
  background: #FFB800;
  top: 250rpx;
  right: 100rpx;
}

/* ========== 顶部标题区 ========== */
.header-section {
  position: relative;
  z-index: 1;
  padding: 60rpx 32rpx 40rpx;
  text-align: center;
}

.header-icon {
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #FFF5F0 0%, #FFE8DD 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 53, 0.2);
}

.header-title {
  display: block;
  font-size: 40rpx;
  font-weight: 700;
  color: #1A1A1A;
  margin-bottom: 12rpx;
  letter-spacing: 1rpx;
}

.header-subtitle {
  display: block;
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

/* ========== 余额卡片 ========== */
.balance-card {
  position: relative;
  z-index: 1;
  margin: 0 24rpx 24rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(255, 107, 53, 0.18);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
}

.balance-left {
  flex: 1;
  min-width: 0;
}

.balance-header {
  display: flex;
  align-items: center;
  gap: 6rpx;
  margin-bottom: 8rpx;
}

.balance-title {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.85);
  font-weight: 500;
}

.balance-amount {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.balance-value {
  font-size: 40rpx;
  color: #ffffff;
  font-weight: 700;
  line-height: 1.2;
  letter-spacing: 0.5rpx;
}

.balance-tip {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 2rpx;
}

.balance-actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  flex-shrink: 0;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14rpx 28rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
  min-width: 120rpx;

  &:active {
    transform: scale(0.95);
  }
}

.action-btn-primary {
  background: #ffffff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

  &.disabled {
    background: rgba(255, 255, 255, 0.4);
    opacity: 0.7;
  }

  .action-btn-text {
    color: #FF6B35;
    font-weight: 600;
    font-size: 26rpx;
  }
}

.action-btn-secondary {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);

  .action-btn-text {
    color: #ffffff;
    font-weight: 500;
  }
}

.action-btn-text {
  font-size: 28rpx;
}

/* ========== 数据统计卡片 ========== */
.stats-card {
  position: relative;
  z-index: 1;
  margin: 0 24rpx 24rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.stats-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 28rpx;
}

.stats-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.stats-grid {
  display: flex;
  gap: 24rpx;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 16rpx;
  background: #F8F9FA;
  border-radius: 16rpx;
  transition: all 0.3s ease;

  &:active {
    background: #F0F2F5;
    transform: scale(0.96);
  }
}

.stat-icon-wrapper {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.stat-icon-blue {
  background: rgba(74, 144, 226, 0.1);
}

.stat-icon-green {
  background: rgba(82, 196, 26, 0.1);
}

.stat-icon-orange {
  background: rgba(255, 140, 0, 0.1);
}

.stat-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #1A1A1A;
  margin-bottom: 8rpx;
  line-height: 1;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

/* ========== 邀请操作区 ========== */
.invite-actions {
  position: relative;
  z-index: 1;
  margin: 0 24rpx 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.action-card {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 28rpx 24rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
  }
}

.action-card-primary {
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  box-shadow: 0 8rpx 24rpx rgba(255, 107, 53, 0.3);
}

.action-card-secondary {
  background: #ffffff;
  border: 2rpx solid #FFE8DD;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.action-card-icon {
  width: 64rpx;
  height: 64rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.action-card-primary .action-card-icon {
  background: rgba(255, 255, 255, 0.2);
}

.action-card-secondary .action-card-icon {
  background: #FFF5F0;
}

.action-card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.action-card-title {
  font-size: 30rpx;
  font-weight: 600;
  line-height: 1.3;
}

.action-card-primary .action-card-title {
  color: #ffffff;
}

.action-card-secondary .action-card-title {
  color: #1A1A1A;
}

.action-card-desc {
  font-size: 24rpx;
  line-height: 1.4;
}

.action-card-primary .action-card-desc {
  color: rgba(255, 255, 255, 0.8);
}

.action-card-secondary .action-card-desc {
  color: #999;
}

/* ========== 活动规则 ========== */
.rules-card {
  position: relative;
  z-index: 1;
  margin: 0 24rpx 24rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.rules-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 28rpx;
}

.rules-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.rules-content {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.rule-item {
  display: flex;
  gap: 20rpx;
  align-items: flex-start;
}

.rule-number {
  width: 44rpx;
  height: 44rpx;
  background: linear-gradient(135deg, #FF8C5A 0%, #FF6B35 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 700;
  flex-shrink: 0;
}

.rule-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  padding-top: 4rpx;
}

.rule-title-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  line-height: 1.3;
}

.rule-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.highlight {
  color: #FF6B35;
  font-weight: 600;
}

.rules-loading {
  padding: 40rpx 0;
  text-align: center;
}

.loading-text {
  font-size: 26rpx;
  color: #999;
}

/* ========== 底部记录入口 ========== */
.bottom-records {
  position: relative;
  z-index: 1;
  margin: 0 24rpx 24rpx;
  background: #ffffff;
  border-radius: 20rpx;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.record-link {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.6;
  }
}

.record-text {
  font-size: 26rpx;
  color: #666;
}

.record-divider {
  width: 2rpx;
  height: 32rpx;
  background: #E5E5E5;
}

/* ========== 底部安全提示 ========== */
.bottom-tip {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 24rpx;
}

.bottom-tip .tip-text {
  font-size: 24rpx;
  color: #999;
}
</style>
