<template>
  <div class="distribution-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-left">
        <el-button 
          type="text" 
          @click="$router.go(-1)"
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </div>
      <div class="nav-center">
        <h1 class="nav-title">分销推广</h1>
      </div>
      <div class="nav-right">
        <!-- 占位元素，保持标题居中 -->
      </div>
    </nav>

    <div class="page-content">
      <!-- 分销说明 -->
      <div class="intro-section">
        <div class="intro-card">
          <h3 class="intro-title">邀请好友注册</h3>
          <p class="intro-desc">分享您的专属二维码，邀请好友注册</p>
        </div>
      </div>

      <!-- 二维码区域 -->
      <div class="qrcode-section">
        <div class="qrcode-card">
          <h4 class="qrcode-title">我的推广二维码</h4>
          <div class="qrcode-container">
            <canvas 
              ref="qrcodeCanvas" 
              class="qrcode-canvas"
              v-show="qrcodeGenerated"
            ></canvas>
            <div v-show="!qrcodeGenerated" class="qrcode-loading">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>生成中...</span>
            </div>
          </div>
          <p class="qrcode-tip">扫描二维码，好友可直接注册并绑定您的推荐关系</p>
          
        </div>
      </div>

      <!-- 推广链接 -->
      <div class="link-section">
        <div class="link-card">
          <h4 class="link-title">推广链接</h4>
          <div class="link-container">
            <el-input 
              v-model="inviteLink" 
              readonly 
              class="link-input"
            >
              <template #append>
                <el-button @click="copyLink" type="primary">
                  复制
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>


    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft,
  Loading
} from '@element-plus/icons-vue'
import QRCode from 'qrcode'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const qrcodeCanvas = ref(null)
const qrcodeGenerated = ref(false)
const generating = ref(false)
const inviteLink = ref('')


// 生成邀请链接
const generateInviteLink = () => {
  const userId = userStore.user?.id || 'guest'
  console.log(userId)
  const baseUrl = `${window.location.origin}/frontend`
  // return `${baseUrl}/register?inviter=${userId}`// 实施用
  return `http://192.168.1.124:5173/register?inviter=${userId}`// 测试用
}

// 生成二维码
const generateQRCode = async () => {
  try {
    generating.value = true
    qrcodeGenerated.value = false
    
    // 生成邀请链接
    const link = generateInviteLink()
    inviteLink.value = link
    
    // 等待DOM更新
    await nextTick()
    
    if (qrcodeCanvas.value) {
      // 生成二维码到canvas
      await QRCode.toCanvas(qrcodeCanvas.value, link, {
        width: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      })
      
      qrcodeGenerated.value = true
    }
  } catch (error) {
    console.error('生成二维码失败:', error)
    ElMessage.error('生成二维码失败')
  } finally {
    generating.value = false
  }
}



// 复制链接
const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(inviteLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = inviteLink.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('链接已复制到剪贴板')
  }
}


// 生命周期
onMounted(() => {
  generateQRCode()
})
</script>

<style scoped>
.distribution-page {
  min-height: 100vh;
  background: linear-gradient(to bottom, #72c9ffae, #f3f3f3);
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 56px;
  background: white;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-left,
.nav-right {
  flex: 1;
}

.nav-right {
  display: flex;
  justify-content: flex-end;
}

.back-btn {
  color: #409eff;
  font-size: 14px;
}

.nav-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.page-content {
  padding: 16px;
}

.intro-section,
.qrcode-section,
.link-section {
  margin-bottom: 16px;
}

.intro-card,
.qrcode-card,
.link-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.intro-title,
.qrcode-title,
.link-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.intro-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.qrcode-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  min-height: 200px;
}

.qrcode-canvas {
  border: 1px solid #eee;
  border-radius: 8px;
}

.qrcode-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #666;
}

.loading-icon {
  font-size: 24px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.qrcode-tip {
  text-align: center;
  font-size: 12px;
  color: #999;
  margin: 0 0 20px 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.link-container {
  margin-top: 12px;
}

.link-input {
  width: 100%;
}

:deep(.link-input .el-input-group__append) {
  padding: 0;
  width: 50px;
}

:deep(.link-input .el-input-group__append .el-button) {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 15px;
}

/* 确保按钮内文字垂直居中 */
:deep(.link-input .el-input-group__append .el-button span) {
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
  }
}
</style>