<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getUserInfo, logout as logoutApi } from '@/api/auth'
import { clearToken } from '@/utils/auth'
import type { UserInfo } from '@/api/auth'

// 用户信息
const userInfo = ref<UserInfo | null>(null)

// 加载状态
const loading = ref(false)

// 用户类型文本（优先使用接口返回的 user_type_name）
const userTypeText = computed(() => {
  if (!userInfo.value)
    return ''
  return userInfo.value.user_type_name || '未知'
})

// 用户类型颜色
const userTypeColor = computed(() => {
  if (!userInfo.value)
    return { bg: '#f5f5f5', text: '#999' }

  const colorMap: Record<number, { bg: string, text: string }> = {
    1: { bg: '#ffebee', text: '#c62828' },
    2: { bg: '#e3f2fd', text: '#1976d2' },
    3: { bg: '#e8f5e9', text: '#2e7d32' },
    4: { bg: '#fff3e0', text: '#e65100' },
  }
  return colorMap[userInfo.value.user_type] || { bg: '#f5f5f5', text: '#999' }
})

// 页面加载
onMounted(() => {
  loadUserInfo()
})

// 加载用户信息
async function loadUserInfo() {
  loading.value = true

  try {
    // 调用 API 获取用户信息
    const data = await getUserInfo()
    userInfo.value = data
  }
  catch (error: any) {
    console.error('获取用户信息失败:', error)
    // 如果是前端逻辑错误（非 API 错误），需要手动显示提示
    if (error instanceof Error && error.message && !error.statusCode) {
      uni.$u.toast(error.message)
    }
    // API 请求错误已由拦截器统一处理
  }
  finally {
    loading.value = false
  }
}

// 修改密码
function changePassword() {
  uni.navigateTo({
    url: '/pages/agent-system/change-password/index',
  })
}

// 退出登录
function logout() {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用登出接口
          await logoutApi()
        }
        catch (error) {
          console.error('登出接口调用失败:', error)
        }
        finally {
          // 清除本地登录状态
          clearToken()
          uni.removeStorageSync('refresh_token')
          uni.removeStorageSync('user_info')

          // 跳转到登录页
          uni.reLaunch({
            url: '/pages/common/login/index',
          })
        }
      }
    },
  })
}

// 复制文本
function copyText(text: string, label: string) {
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: `已复制${label}`,
        icon: 'success',
      })
    },
  })
}
</script>

<template>
  <view class="bg-[#fafafa] min-h-screen pb-safe">
    <!-- 顶部背景区域 -->
    <view class="bg-[#212121]">
      <!-- 用户头像卡片 -->
      <view v-if="userInfo" class="px-4 pt-5 pb-6">
        <view class="center flex-col">
          <!-- 头像 -->
          <view class="w-80px h-80px rounded-full bg-[#ffffff25] center mb-3">
            <i class="i-mdi-account text-48px text-white" />
          </view>

          <!-- 用户名 -->
          <text class="text-20px font-700 text-white block mb-1">
            {{ userInfo.username }}
          </text>

          <!-- 用户类型 -->
          <view
            :style="{
              backgroundColor: userTypeColor.bg,
              color: userTypeColor.text,
            }"
            class="px-3 py-1 rounded-8px text-12px font-600"
          >
            {{ userTypeText }}
          </view>
        </view>
      </view>
    </view>

    <!-- 加载中 -->
    <view v-if="loading" class="pt-20 center">
      <i class="i-mdi-loading animate-spin text-40px text-[#999]" />
    </view>

    <!-- 内容区域 -->
    <view v-else-if="userInfo" class="px-4 pt-4">
      <!-- 个人信息 -->
      <view class="bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)] overflow-hidden mb-3">
        <view class="px-4 py-3 border-b-1px border-[#f5f5f5]">
          <text class="text-14px font-600 text-[#212121]">
            个人信息
          </text>
        </view>

        <view class="px-4 py-2">
          <!-- 用户名 -->
          <view
            class="py-3 flex items-center justify-between border-b-1px border-[#f5f5f5]"
            @click="copyText(userInfo.username, '用户名')"
          >
            <text class="text-14px text-[#999]">用户名</text>
            <view class="flex items-center gap-2">
              <text class="text-14px text-[#212121]">{{ userInfo.username }}</text>
              <i class="i-mdi-content-copy text-16px text-[#999]" />
            </view>
          </view>

          <!-- 手机号 -->
          <view
            class="py-3 flex items-center justify-between border-b-1px border-[#f5f5f5]"
            @click="copyText(userInfo.phone, '手机号')"
          >
            <text class="text-14px text-[#999]">手机号</text>
            <view class="flex items-center gap-2">
              <text class="text-14px text-[#212121]">{{ userInfo.phone }}</text>
              <i class="i-mdi-content-copy text-16px text-[#999]" />
            </view>
          </view>

          <!-- 用户类型 -->
          <view class="py-3 flex items-center justify-between">
            <text class="text-14px text-[#999]">用户类型</text>
            <view
              :style="{
                backgroundColor: userTypeColor.bg,
                color: userTypeColor.text,
              }"
              class="px-3 py-1 rounded-6px text-12px font-600"
            >
              {{ userInfo.user_type_name }}
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="space-y-3">
        <!-- 修改密码 -->
        <view
          class="
            bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)]
            py-3 center gap-2
            transition-all duration-200
            active:bg-[#f5f5f5]
          "
          @click="changePassword"
        >
          <i class="i-mdi-lock-reset text-18px text-[#666]" />
          <text class="text-15px font-600 text-[#666]">
            修改密码
          </text>
        </view>

        <!-- 退出登录 -->
        <view
          class="
            bg-white rounded-16px shadow-[0_2px_12px_rgba(0,0,0,0.06)]
            py-3 center gap-2
            transition-all duration-200
            active:bg-[#ffebee]
          "
          @click="logout"
        >
          <i class="i-mdi-logout text-18px text-[#c62828]" />
          <text class="text-15px font-600 text-[#c62828]">
            退出登录
          </text>
        </view>
      </view>

      <!-- 底部留白 -->
      <view class="h-8" />
    </view>
  </view>
</template>

<style scoped>
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.space-y-3 > view:not(:last-child) {
  margin-bottom: 12px;
}

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

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
