<template>
  <div class="distribution-page">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="nav-left">
        <el-button
            :text="true"
            @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>

      <!-- 下级用户 -->
      <el-button class="lower-users-btn" @click="handleLowerUser">查看下级用户</el-button>
      <el-drawer
          v-model="drawerLowerUsers"
          title="下级用户"
          direction="btt"
          :lockScroll="false"
          size="70%"
          @open="requestLowerUsers(params)"
          @closed="closeScrollerLowerUsers"
      >
        <!-- 一级 -->
        <ul v-if="!showScrollerLowerUsersByUser" v-infinite-scroll="loadScrollerLowerUsers" class="users-list"
            style="overflow: auto"
            :infinite-scroll-immediate="false"
            :infinite-scroll-disabled="scrollLowerUsers">
          <!-- lowerUsers 空数据处理 -->
          <el-empty v-if="lowerUsers.length==0" :image-size="200"/>
          <li v-else v-for="(item, index) in lowerUsers" :key="item.id">
            <el-divider v-if="index!=0" border-style="dashed"/>
            <div class="users-item" @click="handleLowerUserByUserId(item)">
              <el-image
                  :src="getImageUrl(item.avatar)"
                  :preview-src-list="[getImageUrl(item.avatar)]"
                  class="user-avatar"
                  fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div class="user-text">
                <div class="user-username">用户名：{{ item.username }}</div>
                <div class="user-date">时间：{{ item.created_at }}</div>
              </div>
            </div>
          </li>
          <el-divider v-if="scrollLowerUsers" border-style="dashed" content-position="center">到底了~</el-divider>
        </ul>

        <!-- 二级 -->
        <ul v-else v-infinite-scroll="loadScrollerLowerUsersByUser" class="users-list" style="overflow: auto"
            :infinite-scroll-immediate="false"
            :infinite-scroll-disabled="scrollLowerUsersByUser">
          <el-page-header style="margin-bottom: 20px" @back="onBack">
            <template #content>
              <span class="text-large font-600 mr-3"
                    style="font-size: 14px"> 正在查看{{ currentUser.username }}的下级 </span>
            </template>
            <div class="mt-4 text-sm font-bold"></div>
          </el-page-header>
          <!-- lowerUsers 空数据处理 -->
          <el-empty v-if="lowerUsersByUser.length==0" :image-size="200"/>
          <li v-else v-for="(item, index) in lowerUsersByUser" :key="item.id">
            <el-divider v-if="index!=0" border-style="dashed"/>
            <div class="users-item">
              <el-image
                  :src="getImageUrl(item.avatar)"
                  :preview-src-list="[getImageUrl(item.avatar)]"
                  class="user-avatar"
                  fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div class="user-text">
                <div class="user-username">用户名：{{ item.username }}</div>
                <div class="user-date">时间：{{ item.created_at }}</div>
              </div>
            </div>
          </li>
          <el-divider v-if="scrollLowerUsersByUser" border-style="dashed" content-position="center">到底了~</el-divider>
        </ul>
      </el-drawer>

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

<script setup>
import {ref, onMounted, nextTick, reactive} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {ElMessage} from 'element-plus'
import {
  ArrowLeft,
  Loading, Picture
} from '@element-plus/icons-vue'
import QRCode from 'qrcode'
import {distributionAPI} from "@/utils/api.js";
import {getImageUrl} from "@/config/index.js";

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

// 响应式数据
const qrcodeCanvas = ref(null)
const qrcodeGenerated = ref(false)
const generating = ref(false)
const inviteLink = ref('')
// 下级用户
const drawerLowerUsers = ref(false)

// 生成邀请链接
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.250: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('链接已复制到剪贴板')
  }
}

// 查看下级用户
const canMultiLevel = ref(false) // 是否有权查看更多级用户
const showScrollerLowerUsersByUser = ref(false) // 一二级切换
const scrollLowerUsers = ref(false) // 一级是否继续滚动
const scrollLowerUsersByUser = ref(false) // 二级是否继续滚动

const lowerUsers = ref([]) // 一级下级
const currentUser = ref({}) // 二级当前选中
const lowerUsersByUser = ref([]) // 二级下级

// 一级传参
const params = {
  page: 1,
  size: 10
}

// 二级传参
const paramsByUser = {
  page: 1,
  size: 10,
  user_id: ''
}

const pages = ref(1)
const pagesByUser = ref(1)

// 打开查看下级用户抽屉
const handleLowerUser = async () => {
  // 判断是否为*代理查看下下级用户
  var role = JSON.parse(localStorage.getItem('role'))
  if (role.distribution || (role.user_type == 'agent' || role.user_type == 'agent_directly')) {
    canMultiLevel.value = true
  }
  lowerUsers.value = []
  drawerLowerUsers.value = true
}

// 请求一级用户
const requestLowerUsers = async (params) => {
  await distributionAPI.getLowerUsers(params).then((res) => {
    lowerUsers.value = lowerUsers.value.concat(res.data.data)
    pages.value = res.data.pagination.pages
    if (params.page >= pages.value) {
      scrollLowerUsers.value = true
    }
  })
}

// 请求二级用户
const requestLowerUsersByUser = async (params) => {
  await distributionAPI.getLowerUsers(params).then((res) => {
    lowerUsersByUser.value = lowerUsersByUser.value.concat(res.data.data)
    pagesByUser.value = res.data.pagination.pages
    if (params.page >= pagesByUser.value) {
      scrollLowerUsersByUser.value = true
    }
  })
}

// 一级分页请求查看
const loadScrollerLowerUsers = async () => {
  if (scrollLowerUsers.value) {
    return
  }
  params.page += 1
  await requestLowerUsers(params)
}

// 二级分页请求查看
const loadScrollerLowerUsersByUser = async () => {
  if (scrollLowerUsersByUser.value) {
    return
  }
  paramsByUser.page += 1
  await requestLowerUsersByUser(paramsByUser)
}

// 查看二级用户
const handleLowerUserByUserId = async (item) => {
  // 是否有权查看二级
  if (canMultiLevel.value) {
    paramsByUser.user_id = item.user_id
    currentUser.value = item
    await requestLowerUsersByUser(paramsByUser)
    showScrollerLowerUsersByUser.value = true
  }
}

const onBack = () => {
  showScrollerLowerUsersByUser.value = false
}

// 关闭查看下级用户抽屉
const closeScrollerLowerUsers = () => {
  lowerUsers.value = []
  params.page = 0
  scrollLowerUsers.value = false
}


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

<style scoped lang="scss">
.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;
  }
}

.lower-users-btn {
  width: 100%;
  border-radius: 10px;
}

.users-list {
  height: 100%;
  padding: 0 0 0 10px;;
  margin: 0;
  list-style: none;
}

.users-list .users-item {
  display: flex; /* 使用Flexbox布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 1rem; /* 图片与文字之间的间距 */

  .user-avatar {
    width: 50px;
    height: 50px;
    object-fit: cover;
  }

  .user-text {
    .user-username {
      margin-bottom: 5px;
      font-size: 14px;
    }

    .user-date {
      color: #666;
      font-size: 12px;
    }
  }
}

.users-list .users-item + .list-item {
  margin-top: 10px;
}
</style>