<template>
  <CustomNav title="个人中心" leftType="none" />
  <view class="profile-container">
    <view class="header">
      <view class="avatar-section">
        <view class="avatar">
          <view class="avatar-frame">
            <image class="avatar-img" :src="avatarSrc" mode="aspectFill" />
          </view>
        </view>
        <view class="user-info">
          <text class="username">{{ user.nickname || '慢病患者' }}</text>
          <text class="user-id" v-if="user.openid">ID: {{ user.openid }}</text>
        </view>
      </view>
    </view>



    <view class="menu-list">
      <view class="menu-item" @click="onMenuClick('settings')">
        <text class="menu-text">设置</text>
        <text class="menu-arrow"></text>
      </view>
      <view class="menu-item" @click="onMenuClick('about')">
        <text class="menu-text">关于我们</text>
        <text class="menu-arrow"></text>
      </view>
    </view>

    <view class="logout-section">
      <button class="logout-btn" @click="onLogout">退出登录</button>
    </view>
  </view>
  <TabBar />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import CustomNav from '@/components/custom-nav.vue'
import TabBar from '@/components/tab-bar.vue'
import { isLoggedIn as checkLogin, getRole } from '@/composables/useAuth'

const title = ref('个人中心')

const user = ref<{ avatar?: string; nickname?: string; openid?: string }>({})

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

// 计算一个安全的 avatar src：优先使用有效的 user.avatar，否则使用默认头像
const avatarSrc = computed(() => {
  const a = user.value?.avatar
  if (!a) return defaultAvatarUrl
  try {
    const s = String(a)
    // 常见有效前缀：http(s), data:, wxfile://, file://, /static
    if (/^(https?:\/\/|data:|wxfile:\/\/|file:\/\/|\/static\/)/i.test(s)) {
      return s
    }
    // 有时候小程序临时路径也以 / 开头或以 temp 开头，尽量允许以 ./ 或 / 开头
    if (/^(\.|\/|temp)/i.test(s)) return s
  } catch (e) {
    // fallback
  }
  return defaultAvatarUrl
})

const loadUser = () => {
  try {
    const u = uni.getStorageSync('user_info')
    if (u) {
      user.value = u
    }
  } catch (e) {
    // ignore
  }
}

const fetchUserInfo = async () => {
  try {
    const token = uni.getStorageSync('token')
    if (!token) return
    uni.showLoading({ title: '加载中...' })
    const response = await uni.request({
      url: 'https://wx.baiyun.work/user_info',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: {}
    })
    uni.hideLoading()
    console.log('User info response:', response)
    const resp = response.data as any
    if (response.statusCode === 401) {
      // Token 无效，清除并跳转登录
      uni.removeStorageSync('token')
      uni.removeStorageSync('role')
      user.value = {}
      uni.reLaunch({ url: '/pages/public/login/index' })
      return
    }
    if (resp && resp.code === 200 && resp.data) {
      user.value = resp.data
      // 保存到本地存储
      uni.setStorageSync('user_info', resp.data)
    }
  } catch (err) {
    uni.hideLoading()
    console.error('Fetch user info error:', err)
  }
}

// 如果在微信小程序端且未登录，自动跳转到登录页
onShow(() => {
  const token = uni.getStorageSync('token')
  if (!token) {
    // 使用 uni.reLaunch 替代 navigateTo，确保页面栈被清空
    uni.reLaunch({ url: '/pages/public/login/index' })
  } else {
    fetchUserInfo()
    // 检查角色，如果是患者，跳转到患者个人中心
    try {
      const r = getRole()
      if (r === 3) {
        console.log('[profile/index] redirecting to patient profile, role=', r)
        uni.reLaunch({ url: '/pages/patient/profile/index' })
        return
      }
    } catch (err) {
      console.error('检查角色时出错:', err)
    }
  }
})

const onMenuClick = (type: string) => {
  console.log('Menu clicked:', type)
  uni.showToast({
    title: `${type} 功能开发中`,
    icon: 'none'
  })
}

const onLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('token')
        uni.removeStorageSync('role')
        user.value = {}
        uni.showToast({ title: '已退出登录', icon: 'none' })
        uni.reLaunch({ url: '/pages/public/index/index' })
      }
    }
  })
}
</script>

<style>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: calc(var(--status-bar-height) + 44px);
}

.header {
  background-color: #fff;
  padding: 40rpx;
  margin-bottom: 20rpx;
}

.avatar-section {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  /* background-color: #007aff; */
  border: 1px solid rgba(128, 128, 128, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 30rpx;
}

.avatar-frame {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden; /* 裁切超出部分，避免溢出 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 在部分平台下生效，保证图片填充同时裁切 */
}

.avatar-text {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.user-id {
  font-size: 28rpx;
  color: #666;
}

.menu-list {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-text {
  font-size: 32rpx;
  color: #333;
}

.menu-arrow {
  font-size: 28rpx;
  color: #ccc;
}

.logout-section {
  padding: 40rpx;
}

.logout-btn {
  width: 100%;
  background-color: #ff4757;
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
  line-height: 80rpx;
}
</style>