<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-4 block">邀请人信息</text>

          <!-- 有邀请人时显示 -->
          <template v-if="userInfo.inviterCode">
            <view class="bg-gradient-to-r from-pink-50 to-rose-50 rounded-xl p-4 mb-4">
              <text class="text-sm text-gray-500 mb-2 block">我的邀请人代码</text>
              <text class="text-2xl font-bold text-pink-500 tracking-wider">
                {{ userInfo.inviterCode }}
              </text>
            </view>
            <text class="text-sm text-gray-500">感谢您使用我们的服务</text>
          </template>

          <!-- 无邀请人时显示 -->
          <template v-else>
            <view class="bg-gray-50 rounded-xl p-6 mb-4">
              <text class="text-gray-500 mb-4 block">您还没有绑定邀请人</text>
              <button
                class="w-full bg-gradient-to-r from-pink-400 to-rose-400 text-white py-3 rounded-xl shadow-sm hover:shadow transition-all duration-300"
                @click="showBindInviter"
              >
                绑定邀请人
              </button>
            </view>
          </template>
        </view>
      </view>
    </view>
  </view>
</template>

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

const userStore = useUserStore()
const userInfo = ref<any>({})
const inviterCode = ref('')

// 获取用户信息
const getUserInfo = async () => {
  try {
    await userStore.setUserInfo()
    userInfo.value = userStore.userInfo
  } catch (error) {
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none',
    })
  }
}

// 显示绑定邀请人弹窗
const showBindInviter = () => {
  uni.showModal({
    title: '绑定邀请人',
    editable: true,
    placeholderText: '请输入邀请人代码',
    success: async (res) => {
      if (res.confirm && res.content) {
        inviterCode.value = res.content
        await bindInviter()
      }
    },
  })
}

// 绑定邀请人
const bindInviter = async () => {
  if (!inviterCode.value) {
    uni.showToast({
      title: '请输入邀请人代码',
      icon: 'none',
    })
    return
  }

  try {
    const res = await bindInviterAPI(inviterCode.value)
    if (res.code === 200) {
      uni.showToast({
        title: '绑定成功',
        icon: 'success',
      })
      getUserInfo()
    } else {
      throw new Error(res.message || '绑定失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '绑定失败',
      icon: 'none',
    })
  }
}

onMounted(() => {
  getUserInfo()
})
</script>

<style>
/* 确保弹窗样式正确加载 */
:deep(.uni-popup) {
  z-index: 999;
}
</style>
