<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '邀请好友',
  },
}
</route>

<template>
  <view class="min-h-screen bg-gray-50 pb-20">
    <!-- 邀请码卡片 -->
    <view class="mx-4 mt-4">
      <view class="bg-white rounded-2xl shadow-sm p-6">
        <view class="text-center">
          <text class="text-lg font-bold text-gray-800 mb-2 block">我的邀请码</text>
          <view class="flex items-center justify-center space-x-2 mb-4">
            <text class="text-3xl font-bold text-sky-500">{{ inviteCode }}</text>
            <button
              class="px-3 py-1 bg-sky-50 text-sky-500 rounded-full text-sm"
              @click="copyInviteCode"
            >
              复制
            </button>
          </view>
          <text class="text-sm text-gray-500">邀请好友注册时填写此邀请码，双方均可获得奖励</text>
        </view>
      </view>
    </view>

    <!-- 邀请记录 -->
    <view class="mx-4 mt-4">
      <view class="bg-white rounded-2xl shadow-sm overflow-hidden">
        <view class="p-4 border-b border-gray-100">
          <text class="text-base font-bold text-gray-800">邀请记录</text>
        </view>
        <view v-if="inviteList.length === 0" class="p-8 text-center">
          <text class="text-gray-500">暂无邀请记录</text>
        </view>
        <view v-else class="divide-y divide-gray-100">
          <view v-for="(item, index) in inviteList" :key="index" class="p-4">
            <!-- 一级用户 -->
            <view class="flex items-center justify-between">
              <view class="flex-1">
                <text class="text-gray-800 block">{{ item.nickname }}</text>
                <text class="text-sm text-gray-500">{{ item.createTime }}</text>
              </view>
              <view class="flex items-center space-x-2">
                <button
                  class="px-2 py-1 bg-gradient-to-r from-sky-400 to-indigo-400 text-white rounded-lg text-xs flex items-center shadow-sm hover:shadow transition-all duration-300"
                  @click.stop="
                    navigateTo('/pages/my/spend-detail', {
                      nickname: item.nickname,
                      id: item.id,
                      points: item.points,
                    })
                  "
                >
                  <i class="i-carbon-money text-xs mr-1"></i>
                  消费明细
                </button>
                <view class="w-8 h-8 flex items-center justify-center" @click="toggleExpand(index)">
                  <i
                    :class="[
                      expandedItems[index] ? 'i-carbon-chevron-down' : 'i-carbon-chevron-right',
                      'text-gray-400',
                    ]"
                  ></i>
                </view>
              </view>
            </view>

            <!-- 子用户列表 -->
            <view
              v-if="item.child && item.child.length > 0 && expandedItems[index]"
              class="mt-3 ml-4 pl-4 border-l-2 border-gray-100"
            >
              <view v-for="(child, childIndex) in item.child" :key="childIndex" class="py-3">
                <!-- 子用户信息 -->
                <view class="flex items-center justify-between">
                  <view class="flex-1">
                    <text class="text-gray-800 block">{{ child.nickname }}</text>
                    <text class="text-sm text-gray-500">{{ child.createTime }}</text>
                  </view>
                  <view class="flex items-center space-x-2">
                    <button
                      class="px-2 py-1 bg-gradient-to-r from-sky-400 to-indigo-400 text-white rounded-lg text-xs flex items-center shadow-sm hover:shadow transition-all duration-300"
                      @click.stop="
                        navigateTo('/pages/my/spend-detail', {
                          nickname: child.nickname,
                          id: child.id,
                          points: child.points,
                        })
                      "
                    >
                      <i class="i-carbon-money text-xs mr-1"></i>
                      消费明细
                    </button>
                    <view
                      class="w-8 h-8 flex items-center justify-center"
                      @click="toggleChildExpand(index, childIndex)"
                    >
                      <i
                        :class="[
                          expandedChildItems[`${index}-${childIndex}`]
                            ? 'i-carbon-chevron-down'
                            : 'i-carbon-chevron-right',
                          'text-gray-400',
                        ]"
                      ></i>
                    </view>
                  </view>
                </view>

                <!-- 孙用户列表 -->
                <view
                  v-if="
                    child.child &&
                    child.child.length > 0 &&
                    expandedChildItems[`${index}-${childIndex}`]
                  "
                  class="mt-3 ml-4 pl-4 border-l-2 border-gray-100"
                >
                  <view
                    v-for="(grandChild, grandChildIndex) in child.child"
                    :key="grandChildIndex"
                    class="py-3 flex items-center justify-between"
                  >
                    <view class="flex-1">
                      <text class="text-gray-800 block">{{ grandChild.nickname }}</text>
                      <text class="text-sm text-gray-500">{{ grandChild.createTime }}</text>
                    </view>
                    <view class="flex items-center space-x-2">
                      <button
                        class="px-2 py-1 bg-gradient-to-r from-sky-400 to-indigo-400 text-white rounded-lg text-xs flex items-center shadow-sm hover:shadow transition-all duration-300"
                        @click.stop="
                          navigateTo('/pages/my/spend-detail', {
                            nickname: grandChild.nickname,
                            id: grandChild.id,
                            points: grandChild.points,
                          })
                        "
                      >
                        <i class="i-carbon-money text-xs mr-1"></i>
                        消费明细
                      </button>
                      <view class="w-8 h-8 flex items-center justify-center">
                        <i class="i-carbon-chevron-right text-gray-300"></i>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 邀请说明 -->
    <view class="mx-4 mt-4">
      <view class="bg-white rounded-2xl shadow-sm p-4">
        <text class="text-base font-bold text-gray-800 mb-2 block">邀请说明</text>
        <view class="space-y-2 text-sm text-gray-600">
          <text class="block">1. 邀请好友填写您的邀请码</text>
          <text class="block">2. 好友注册成功后，双方均可获得奖励</text>
          <text class="block">3. 邀请记录将在好友注册成功后显示</text>
          <text class="block">4. 如有疑问，请联系客服</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getInviteCodeAPI, getMyInviteListAPI } from '@/service/login'

interface InviteUserItem {
  nickname: string
  id: string | number
  createTime?: string
  child?: InviteUserItem[]
  points?: number
}

const inviteCode = ref('')
const inviteList = ref<InviteUserItem[]>([])
const expandedItems = ref<{ [key: number]: boolean }>({})
const expandedChildItems = ref<{ [key: string]: boolean }>({})

// 切换一级用户展开/收起状态
const toggleExpand = (index: number) => {
  expandedItems.value[index] = !expandedItems.value[index]
}

// 切换子用户展开/收起状态
const toggleChildExpand = (parentIndex: number, childIndex: number) => {
  const key = `${parentIndex}-${childIndex}`
  expandedChildItems.value[key] = !expandedChildItems.value[key]
}

// 获取邀请码
const getInviteCode = async () => {
  try {
    const res = await getInviteCodeAPI()
    if (res.code === 200) {
      inviteCode.value = res.data
      console.log('邀请码:', res.data) // 添加日志查看数据
    }
  } catch (error) {
    console.error('获取邀请码失败:', error) // 添加错误日志
    uni.showToast({
      title: '获取邀请码失败',
      icon: 'none',
    })
  }
}

// 获取邀请记录
const getInviteList = async () => {
  try {
    const res = await getMyInviteListAPI()
    if (res.code === 200 && Array.isArray(res.data)) {
      inviteList.value = res.data
      console.log('邀请记录数据:', res.data) // 添加日志查看数据
    }
  } catch (error) {
    console.error('获取邀请记录失败:', error) // 添加错误日志
    uni.showToast({
      title: '获取邀请记录失败',
      icon: 'none',
    })
  }
}

// 复制邀请码
const copyInviteCode = () => {
  if (!inviteCode.value) {
    uni.showToast({
      title: '邀请码获取失败',
      icon: 'none',
    })
    return
  }

  uni.setClipboardData({
    data: inviteCode.value,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'success',
      })
    },
  })
}

const navigateTo = (url: string, params?: Record<string, any>) => {
  if (params) {
    console.log('传递的参数:', params) // 添加日志
    const query = Object.entries(params)
      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
      .join('&')
    url = `${url}?${query}`
    console.log('最终URL:', url) // 添加日志
  }
  uni.navigateTo({ url })
}

onMounted(() => {
  getInviteCode()
  getInviteList()
})
</script>
