<template>
  <view class="page">
    <NavBar title="邀请好友" :showBack="true" />

    <view class="content">
      <!-- 活动规则展示区 -->
      <view class="activity-rules" v-if="activityInfo">
        <view class="rules-header">
          <view class="gift-icon"></view>
          <text class="rules-title">{{ activityInfo.title || '邀请有礼，双方共赢' }}</text>
        </view>

        <view class="rules-content">
          <view
            class="rule-item"
            v-for="(rule, index) in displayRules"
            :key="index"
          >
            <view class="rule-number">{{ index + 1 }}</view>
            <text class="rule-text">{{ rule }}</text>
          </view>
        </view>

        <!-- 双向奖励亮点提示 -->
        <view class="dual-reward-highlight">
          <view class="highlight-icon">🎁</view>
          <text class="highlight-text">双方均可获得优惠券，上不封顶</text>
        </view>

        <view class="activity-time">
          <view class="time-icon"></view>
          <text>活动时间：{{ activityInfo.startTime }} ~ {{ activityInfo.endTime }}</text>
        </view>
      </view>

      <!-- 邀请数据统计 -->
      <view class="invite-stats" v-if="myStats">
        <view class="stat-card">
          <text class="stat-num">{{ myStats.totalInvite || 0 }}</text>
          <text class="stat-label">累计邀请</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-card">
          <text class="stat-num success">{{ myStats.validInvite || 0 }}</text>
          <text class="stat-label">成功邀请</text>
        </view>
        <view class="stat-divider"></view>
        <view class="stat-card">
          <text class="stat-num primary">{{ myStats.rewardCount || 0 }}</text>
          <text class="stat-label">获得奖励</text>
        </view>
      </view>

      <!-- 邀请码展示 -->
      <view class="invite-code-section" v-if="inviteCodeInfo">
        <view class="code-header">
          <text class="code-title">我的邀请码</text>
          <text class="code-tip">分享给好友，双方各得优惠券</text>
        </view>
        <view class="code-display">
          <text class="code-text">{{ inviteCodeInfo.code }}</text>
          <button class="copy-btn" @click="copyInviteCode">复制</button>
        </view>
      </view>

      <!-- 操作按钮区 -->
      <view class="action-buttons">
        <button class="btn-primary" @click="handleShare" :disabled="isSharing">
          <view class="btn-icon share"></view>
          <text>{{ isSharing ? '分享中...' : '立即邀请，双方得券' }}</text>
        </button>
        <view class="btn-desc">
          <text class="desc-text">邀请好友注册即送新人券，完成首单再送推荐奖励</text>
        </view>
        <button class="btn-secondary" @click="handleGeneratePoster" :disabled="isGenerating">
          <view class="btn-icon poster"></view>
          <text>{{ isGenerating ? '生成中...' : '生成邀请海报' }}</text>
        </button>
        <button class="btn-link" @click="goToRecords">
          查看我的邀请记录
          <view class="arrow-right"></view>
        </button>
      </view>

      <!-- 奖励说明 -->
      <view class="reward-info" v-if="myStats && myStats.totalRewardAmount > 0">
        <view class="reward-header">
          <view class="reward-icon"></view>
          <text class="reward-title">累计奖励</text>
        </view>
        <view class="reward-amount">
          <text class="amount-symbol">¥</text>
          <text class="amount-value">{{ myStats.totalRewardAmount }}</text>
        </view>
        <text class="reward-desc">已获得 {{ myStats.rewardCount }} 张优惠券</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { logger } from '@/utils/logger';
import NavBar from '@/components/NavBar.vue';
import {
  getInviteCode,
  getMyInviteStatistics,
  getActivityInfo,
  generatePoster
} from '@/api/invite';
import type { InviteCodeResponse, InviteStatistics, ActivityInfo } from '@/api/invite';

const inviteCodeInfo = ref<InviteCodeResponse | null>(null);
const myStats = ref<InviteStatistics | null>(null);
const activityInfo = ref<ActivityInfo | null>(null);
const isSharing = ref(false);
const isGenerating = ref(false);

// 双向奖励规则展示（如果后端未返回则使用默认文案）
const displayRules = computed(() => {
  if (activityInfo.value && activityInfo.value.rules && activityInfo.value.rules.length > 0) {
    return activityInfo.value.rules;
  }
  // 默认双向奖励规则
  return [
    '邀请好友注册，好友立即获得新人优惠券',
    '好友完成首单后，您将获得推荐奖励券',
    '双方均可享受专属优惠，上不封顶'
  ];
});

onMounted(() => {
  loadActivityInfo();
  loadStatistics();
  loadInviteCode();
});

const loadActivityInfo = async () => {
  try {
    activityInfo.value = await getActivityInfo();
  } catch (error) {
    logger.warn('加载活动信息失败', error);
  }
};

const loadStatistics = async () => {
  try {
    myStats.value = await getMyInviteStatistics();
  } catch (error) {
    logger.warn('加载统计数据失败', error);
  }
};

const loadInviteCode = async () => {
  try {
    inviteCodeInfo.value = await getInviteCode();
  } catch (error) {
    logger.warn('获取邀请码失败', error);
  }
};

const copyInviteCode = () => {
  if (!inviteCodeInfo.value) return;

  uni.setClipboardData({
    data: inviteCodeInfo.value.code,
    success: () => {
      uni.showToast({
        title: '邀请码已复制',
        icon: 'success'
      });
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  });
};

const handleShare = async () => {
  if (!inviteCodeInfo.value) {
    uni.showToast({
      title: '请先获取邀请码',
      icon: 'none'
    });
    return;
  }

  isSharing.value = true;

  try {
    // #ifdef MP-WEIXIN
    uni.share({
      provider: 'weixin',
      scene: 'WXSceneSession',
      type: 0,
      title: `【双享福利】${activityInfo.value?.title || '邀请您领取专属优惠券'}`,
      summary: `接受邀请即得新人券，完成首单再送推荐奖\n\n我的邀请码：${inviteCodeInfo.value.code}`,
      href: inviteCodeInfo.value.inviteUrl,
      imageUrl: '',
      success: () => {
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: (err: any) => {
        // 如果分享失败，尝试使用小程序分享
        logger.log('share failed, try fallback', err);
        showShareMenu();
      }
    });
    // #endif

    // #ifndef MP-WEIXIN
    showShareMenu();
    // #endif
  } catch (error) {
    logger.warn('分享失败', error);
    uni.showToast({
      title: '分享失败，请重试',
      icon: 'none'
    });
  } finally {
    setTimeout(() => {
      isSharing.value = false;
    }, 1000);
  }
};

const showShareMenu = () => {
  // 使用系统分享菜单
  // #ifdef MP-WEIXIN
  // 在微信小程序中，可以通过按钮 open-type="share" 触发
  uni.showModal({
    title: '分享提示',
    content: `邀请码：${inviteCodeInfo.value?.code}\n\n请点击右上角菜单分享给好友`,
    showCancel: false,
    confirmText: '我知道了'
  });
  // #endif

  // #ifndef MP-WEIXIN
  uni.showActionSheet({
    itemList: ['复制邀请链接', '复制邀请码'],
    success: (res) => {
      if (res.tapIndex === 0 && inviteCodeInfo.value) {
        uni.setClipboardData({
          data: inviteCodeInfo.value.inviteUrl,
          success: () => {
            uni.showToast({ title: '链接已复制', icon: 'success' });
          }
        });
      } else if (res.tapIndex === 1) {
        copyInviteCode();
      }
    }
  });
  // #endif
};

const handleGeneratePoster = async () => {
  isGenerating.value = true;

  try {
    const result = await generatePoster();

    // 预览海报图片
    uni.previewImage({
      urls: [result.posterUrl],
      current: result.posterUrl
    });

    uni.showToast({
      title: '海报生成成功',
      icon: 'success'
    });
  } catch (error) {
    logger.warn('生成海报失败', error);
    uni.showToast({
      title: '生成海报失败',
      icon: 'none'
    });
  } finally {
    isGenerating.value = false;
  }
};

const goToRecords = () => {
  uni.navigateTo({
    url: '/pages/invite/records'
  });
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: $bg-color-page;
}

.content {
  padding: 24rpx;
  padding-top: 0;
}

.activity-rules {
  background: linear-gradient(135deg, $primary-color 0%, $primary-color-dark 100%);
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  color: $bg-color-card;
}

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

.gift-icon {
  width: 48rpx;
  height: 48rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12rpx;
  margin-right: 16rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -60%);
    width: 24rpx;
    height: 16rpx;
    border: 3rpx solid $bg-color-card;
    border-radius: 4rpx 4rpx 0 0;
  }

  &::after {
    content: '';
    position: absolute;
    top: 60%;
    left: 50%;
    transform: translateX(-50%);
    width: 4rpx;
    height: 12rpx;
    background: $bg-color-card;
  }
}

.rules-title {
  font-size: 32rpx;
  font-weight: 700;
  color: $bg-color-card;
}

.rules-content {
  margin-bottom: 24rpx;
}

.rule-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.rule-number {
  width: 36rpx;
  height: 36rpx;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  font-weight: 600;
  color: $bg-color-card;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.rule-text {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.95);
  line-height: 36rpx;
}

.activity-time {
  display: flex;
  align-items: center;
  padding: 16rpx 20rpx;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 10rpx;
}

.dual-reward-highlight {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 24rpx;
  margin-bottom: 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 10rpx;
  border: 1rpx dashed rgba(255, 255, 255, 0.4);
}

.highlight-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}

.highlight-text {
  font-size: 26rpx;
  font-weight: 600;
  color: $bg-color-card;
}

.time-icon {
  width: 28rpx;
  height: 28rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.7);
  border-radius: 6rpx;
  margin-right: 12rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8rpx;
    height: 8rpx;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 50%;

  }

  text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.9);
  }
}

.invite-stats {
  background: $bg-color-card;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  border: 1rpx solid $border-color;
}

.stat-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-num {
  font-size: 44rpx;
  font-weight: 700;
  color: $text-color-primary;
  margin-bottom: 8rpx;

  &.success {
    color: $primary-color;
  }

  &.primary {
    color: $info-color;
  }
}

.stat-label {
  font-size: 24rpx;
  color: $text-color-tertiary;
}

.stat-divider {
  width: 1rpx;
  height: 60rpx;
  background: $border-color;
}

.invite-code-section {
  background: $bg-color-card;
  border-radius: 20rpx;
  padding: 28rpx;
  margin-bottom: 24rpx;
  border: 1rpx solid $border-color;
}

.code-header {
  margin-bottom: 20rpx;
}

.code-title {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-color-primary;
  display: block;
  margin-bottom: 4rpx;
}

.code-tip {
  font-size: 24rpx;
  color: $text-color-muted;
}

.code-display {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.code-text {
  flex: 1;
  font-size: 36rpx;
  font-weight: 700;
  color: $info-color;
  letter-spacing: 4rpx;
  padding: 16rpx 24rpx;
  background: $info-color-bg;
  border-radius: 12rpx;
  text-align: center;
}

.copy-btn {
  padding: 16rpx 32rpx;
  line-height: 1;
  background: $info-color;
  border-radius: 12rpx;
  font-size: 26rpx;
  font-weight: 500;
  color: $bg-color-card;
  border: none;

  &:active {
    opacity: 0.9;
  }
}

.action-buttons {
  margin-bottom: 24rpx;
}

.btn-primary {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  padding: 0;
  background: linear-gradient(135deg, $primary-color 0%, $primary-color-dark 100%);
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 600;
  color: $bg-color-card;
  border: none;
  margin-bottom: 12rpx;

  &[disabled] {
    background: $text-color-placeholder;
    color: $text-color-muted;
  }

  &:active:not([disabled]) {
    opacity: 0.9;
  }
}

.btn-desc {
  margin-bottom: 20rpx;
  text-align: center;
}

.desc-text {
  font-size: 24rpx;
  color: $text-color-tertiary;
}

.btn-secondary {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  padding: 0;
  background: $bg-color-card;
  border: 2rpx solid $info-color;
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  font-weight: 500;
  color: $info-color;
  margin-bottom: 20rpx;

  &[disabled] {
    border-color: $text-color-placeholder;
    color: $text-color-muted;
  }

  &:active:not([disabled]) {
    background: $info-color-bg;
  }
}

.btn-link {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  padding: 0;
  background: transparent;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: $text-color-tertiary;

  &:active {
    color: $text-color-secondary;
  }
}

.btn-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;

  &.share {
    border: 3rpx solid $bg-color-card;
    border-radius: 50%;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: -8rpx;
      right: -8rpx;
      width: 14rpx;
      height: 14rpx;
      background: $bg-color-card;
      border-radius: 50%;
    }

    &::after {
      content: '';
      position: absolute;
      bottom: -4rpx;
      right: -4rpx;
      width: 18rpx;
      height: 10rpx;
      border-left: 3rpx solid $bg-color-card;
      border-bottom: 3rpx solid $bg-color-card;
      transform: rotate(-45deg);
    }
  }

  &.poster {
    border: 3rpx solid $info-color;
    border-radius: 6rpx;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 12rpx;
      height: 12rpx;
      background: $info-color;
      border-radius: 2rpx;
    }

    &::after {
      content: '';
      position: absolute;
      bottom: 5rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 3rpx;
      height: 6rpx;
      background: $info-color;
    }
  }
}

.arrow-right {
  width: 12rpx;
  height: 12rpx;
  border-top: 3rpx solid $text-color-muted;
  border-right: 3rpx solid $text-color-muted;
  transform: rotate(45deg);
  margin-left: 8rpx;
}

.reward-info {
  background: linear-gradient(135deg, $primary-color-bg 0%, $primary-color-light 100%);
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1rpx solid $primary-color-light;
}

.reward-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.reward-icon {
  width: 40rpx;
  height: 40rpx;
  background: $warning-color;
  border-radius: 50%;
  margin-right: 12rpx;
  position: relative;

  &::before {
    content: '¥';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 22rpx;
    font-weight: 700;
    color: $bg-color-card;
  }
}

.reward-title {
  font-size: 26rpx;
  font-weight: 500;
  color: $primary-color-dark;
}

.reward-amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.amount-symbol {
  font-size: 32rpx;
  font-weight: 600;
  color: $primary-color-dark;
  margin-right: 4rpx;
}

.amount-value {
  font-size: 56rpx;
  font-weight: 700;
  color: $primary-color-dark;
}

.reward-desc {
  font-size: 24rpx;
  color: $primary-color-dark;
}
</style>
