<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我的',
  },
}
</route>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 顶部背景 -->
    <view
      class="h-56 bg-gradient-to-br from-pink-50 via-rose-50 to-purple-50 relative overflow-hidden"
    >
      <view class="absolute top-0 left-0 right-0 bottom-0">
        <view
          class="absolute top-0 right-0 w-72 h-72 bg-gradient-to-br from-pink-200/40 to-transparent rounded-full blur-3xl"
        ></view>
        <view
          class="absolute bottom-0 left-0 w-72 h-72 bg-gradient-to-tr from-rose-200/40 to-transparent rounded-full blur-3xl"
        ></view>
      </view>
    </view>

    <!-- 个人信息卡片 -->
    <view class="mx-4 -mt-24 relative">
      <view class="bg-white/95 backdrop-blur-md rounded-3xl shadow-xl p-6 border border-pink-100">
        <view class="flex items-center">
          <view class="relative">
            <image
              class="w-24 h-24 rounded-2xl border-4 border-white shadow-xl"
              :src="userInfo.avatar || defaultAvatar"
              mode="aspectFill"
              @click="handleUploadAvatar"
            />
            <view
              v-if="userInfo.vipLevel"
              class="absolute -bottom-2 -right-2 bg-gradient-to-r from-pink-400 to-rose-400 text-white px-3 py-1 rounded-full text-xs flex items-center shadow-lg"
            >
              <i class="i-carbon-crown text-sm mr-1"></i>
              <text>VIP{{ userInfo.points }}</text>
            </view>
          </view>
          <view class="flex-1 ml-6">
            <view class="flex flex-wrap items-center gap-2 mb-3">
              <text class="text-xl font-bold text-gray-800 truncate max-w-[140px]">
                {{ userInfo.nickName }}
              </text>
              <view
                class="px-3 py-1 bg-pink-50 text-pink-600 rounded-full text-xs border border-pink-100 whitespace-nowrap"
              >
                ID: {{ userInfo.id }}
              </view>
              <view
                class="px-3 py-1 bg-rose-50 text-rose-600 rounded-full text-xs border border-rose-100 whitespace-nowrap"
              >
                <i class="i-carbon-money text-xs mr-1"></i>
                余额: {{ userInfo.points || 0 }}
              </view>
            </view>
            <view class="flex space-x-3">
              <button
                class="flex-1 bg-gradient-to-r from-pink-400 to-rose-400 text-white text-sm py-2 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 flex items-center justify-center"
                @click="navigateTo('/pages/my/profile')"
              >
                <i class="i-carbon-user-profile text-base mr-2"></i>
                <text class="truncate">我的资料</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 数据统计 -->
    <!-- <view class="mx-4 mt-4">
      <view class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-4 border border-gray-100">
        <view class="grid grid-cols-3 gap-4">
          <view class="text-center">
            <view
              class="w-12 h-12 bg-sky-50 rounded-full flex items-center justify-center mx-auto mb-2"
            >
              <i class="i-carbon-calendar text-2xl text-sky-500"></i>
            </view>
            <text class="text-2xl font-bold text-sky-500 block">
              {{ userInfo.activityCount || 0 }}
            </text>
            <text class="text-sm text-gray-600">活动</text>
          </view>
          <view class="text-center">
            <view
              class="w-12 h-12 bg-indigo-50 rounded-full flex items-center justify-center mx-auto mb-2"
            >
              <i class="i-carbon-favorite text-2xl text-indigo-500"></i>
            </view>
            <text class="text-2xl font-bold text-indigo-500 block">
              {{ userInfo.matchCount || 0 }}
            </text>
            <text class="text-sm text-gray-600">配对</text>
          </view>
          <view class="text-center">
            <view
              class="w-12 h-12 bg-purple-50 rounded-full flex items-center justify-center mx-auto mb-2"
            >
              <i class="i-carbon-group text-2xl text-purple-500"></i>
            </view>
            <text class="text-2xl font-bold text-purple-500 block">
              {{ userInfo.groupCount || 0 }}
            </text>
            <text class="text-sm text-gray-600">群组</text>
          </view>
        </view>
      </view>
    </view> -->

    <!-- 功能菜单 -->
    <view class="mx-4 mt-6">
      <view
        class="bg-white/95 backdrop-blur-md rounded-3xl shadow-xl overflow-hidden border border-pink-100"
      >
        <view
          class="flex items-center justify-between px-6 py-4 border-b border-pink-50 active:bg-pink-50/50 transition-colors"
          v-for="(item, index) in menuItems"
          :key="index"
          @click="navigateTo(item.path)"
        >
          <view class="flex items-center">
            <view
              class="w-12 h-12 rounded-2xl bg-gradient-to-br from-pink-50 to-rose-50 flex items-center justify-center mr-4 shadow-sm"
            >
              <i :class="item.icon" class="text-xl text-pink-500"></i>
            </view>
            <view>
              <text class="text-base font-medium text-gray-800 block">{{ item.title }}</text>
              <text class="text-xs text-gray-500">{{ item.desc }}</text>
            </view>
          </view>
          <i class="i-carbon-chevron-right text-pink-300"></i>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="mx-4 my-6 mb-20">
      <button
        class="w-full h-14 bg-white text-rose-500 rounded-xl text-base font-medium flex items-center justify-center shadow-md hover:shadow-lg transition-all duration-300 border border-rose-100"
        @click="handleLogout"
      >
        退出登录
      </button>
    </view>

    <!-- 在线客服 -->
    <!-- <view class="fixed bottom-6 left-0 right-0 px-4">
      <button
        class="w-full h-12 bg-gradient-to-r from-sky-400 to-indigo-400 text-white rounded-full text-base flex items-center justify-center shadow-lg hover:shadow-xl transition-shadow"
        open-type="contact"
      >
        <i class="i-carbon-chat text-lg mr-2"></i>
        在线客服
      </button>
    </view> -->
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { logoutAPI, updateUserInfoAPI } from '@/service/login'
import { uploadImageAPI } from '@/service/file'
import type { UserInfo as ApiUserInfo } from '@/service/login/type'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store'

const userStore = useUserStore()

const defaultAvatar = '/static/images/default-avatar.png'

interface UserInfo {
  avatar: string
  name: string
  vipLevel: number
  userId: string
  profileCompletion: number
  activityCount: number
  matchCount: number
  groupCount: number
  points: number
}

const userInfo = ref<UserInfo>({
  avatar: '',
  name: '未设置',
  vipLevel: 0,
  userId: '---',
  profileCompletion: 0,
  activityCount: 0,
  matchCount: 0,
  groupCount: 0,
  points: 0,
})

const menuItems = [
  {
    title: '我的活动',
    desc: '查看已参与的活动',
    path: '/pages/my/activities',
    icon: 'i-carbon-calendar',
  },
  {
    title: '我的配对',
    desc: '查看配对信息',
    path: '/pages/my/matches',
    icon: 'i-carbon-favorite',
  },
  {
    title: '邀请好友',
    desc: '邀请好友加入',
    path: '/pages/my/invite',
    icon: 'i-carbon-user-multiple',
  },
  {
    title: '消费记录',
    desc: '查看消费明细',
    path: '/pages/my/spend',
    icon: 'i-carbon-money',
  },
  {
    title: '充值记录',
    desc: '查看充值',
    path: '/pages/my/recharge',
    icon: 'i-carbon-wallet',
  },
  {
    title: '退款记录',
    desc: '查看退款',
    path: '/pages/my/refund',
    icon: 'i-carbon-money',
  },
  // {
  //   title: '投诉',
  //   desc: '反馈问题或违规行为',
  //   path: '/pages/my/complaint',
  //   icon: 'i-carbon-warning',
  // },
  {
    title: '意见反馈',
    desc: '帮助我们提供更好的服务',
    path: '/pages/my/feedback',
    icon: 'i-carbon-chat-bot',
  },
  {
    title: '我的邀请人',
    desc: '查看或绑定邀请人',
    path: '/pages/my/inviter',
    icon: 'i-carbon-user-follow',
  },
  {
    title: '我的下级',
    desc: '查看我的下级',
    path: '/pages/my/subordinate',
    icon: 'i-carbon-user-multiple',
  },
]

const navigateTo = (url: string) => {
  uni.navigateTo({ url })
}

// 退出登录
const handleLogout = async () => {
  try {
    const res = await logoutAPI()
    if (res.code === 200) {
      uni.showToast({
        title: '退出成功',
        icon: 'success',
      })
      // 清除本地存储的用户信息
      uni.removeStorageSync('x-token')
      uni.removeStorageSync('userInfo')
      // 跳转到登录页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/login/index',
        })
      }, 1500)
    }
  } catch (error) {
    uni.showToast({
      title: '退出失败',
      icon: 'none',
    })
  }
}

const handleUploadAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      try {
        // 显示上传中提示
        uni.showLoading({
          title: '上传中...',
          mask: true,
        })

        // 直接上传临时文件路径
        const uploadRes = await uploadImageAPI(tempFilePath, 'avatar')

        if (uploadRes.url) {
          // 更新用户头像
          const updateRes = await userStore.updateUserInfo({
            avatar: uploadRes.url,
          })

          if (updateRes.code === 200) {
            // 更新本地用户信息
            userInfo.value.avatar = uploadRes.url
            uni.showToast({
              title: '头像更新成功',
              icon: 'success',
            })
          } else {
            throw new Error(updateRes.message)
          }
        } else {
          throw new Error('上传失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none',
        })
      } finally {
        uni.hideLoading()
      }
    },
  })
}
onShow(() => {
  // 页面显示时获取用户信息
  getUserInfo()
})

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

<style lang="scss" scoped>
// 移除之前的 iconfont 样式，因为现在使用 Carbon 图标
</style>
