<template>
  <CustomNav title="首页" leftType="scan" @scan="handleScan" :opacity="0" />
  <view class="page-container">
    <view class="content">
      <view class="user-info">
        <view class="avatar-section">
          <view class="avatar">
            <view class="avatar-frame">
              <image class="avatar-img" :src="avatarSrc" mode="aspectFill" />
            </view>
          </view>
          <view class="user-details">
            <text class="username">{{ user.nickname || '未登录' }}</text>
            <text class="user-age" v-if="user.age">年龄: {{ user.age }}</text>
          </view>
          <view class="qr-button" @click="onQrClick">
            <image src="/static/icons/remixicon/qr-code-line.svg" class="qr-icon" />
          </view>
        </view>
      </view>

      <view class="function-container">
        <view class="function-row">
          <view class="function-item green" @click="onItemClick('我的医生')">
            <view class="item-content">
              <view class="title-row">
                <view class="item-line"></view>
                <text class="item-title">我的医生</text>
              </view>
              <text class="item-desc">一键预约复诊</text>
            </view>
          </view>
          <view class="function-item blue" @click="onItemClick('疑问解答')">
            <view class="item-content">
              <view class="title-row">
                <view class="item-line"></view>
                <text class="item-title">疑问解答</text>
              </view>
              <text class="item-desc">解答您的健康疑问</text>
            </view>
          </view>

        </view>
        <view class="function-row">
          <view class="function-item orange" @click="onItemClick('提醒管理')">
            <view class="item-content">
              <view class="title-row">
                <view class="item-line"></view>
                <text class="item-title">提醒管理</text>
              </view>
              <text class="item-desc">管理您的健康提醒</text>
            </view>
          </view>
          <view class="function-item purple" @click="onItemClick('个人中心')">
            <view class="item-content">
              <view class="title-row">
                <view class="item-line"></view>
                <text class="item-title">个人中心</text>
              </view>
              <text class="item-desc">管理您的个人健康档案</text>
            </view>
          </view>
        </view>
      </view>

      <view class="health-news-card">
        <view class="card-header">
          <text class="card-title">健康资讯</text>
        </view>
        <view class="card-content">
          <view class="news-item" v-for="(news, index) in newsList" :key="index">
            <view v-if="news.image" class="news-image-container">
              <image class="news-image" :src="news.image" mode="aspectFill" />
            </view>
            <view v-else class="news-placeholder">
              <image class="placeholder-icon" src="/static/icons/remixicon/image-line.svg" />
            </view>
            <view class="news-text">
              <text class="news-title">{{ news.title }}</text>
              <text class="news-desc">{{ news.desc }}</text>
            </view>
          </view>
        </view>
      </view>

    </view>
  </view>
  <TabBar />
</template>

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

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

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

const avatarSrc = computed(() => {
  const a = user.value?.avatar
  if (!a) return defaultAvatarUrl
  try {
    const s = String(a)
    if (/^(https?:\/\/|data:|wxfile:\/\/|file:\/\/|\/static\/)/i.test(s)) {
      return s
    }
    if (/^(\.|\/|temp)/i.test(s)) return s
  } catch (e) {
    // fallback
  }
  return defaultAvatarUrl
})

const newsList = ref([
  {
    title: '健康饮食指南',
    desc: '了解均衡饮食的重要性，掌握健康饮食的基本原则。',
    image: '/static/carousel/BHFIIABBCDJII-5kCEkD6zh9.jpg'
  },
  {
    title: '运动与健康',
    desc: '定期运动对身体的好处，以及如何制定适合自己的运动计划。'
  },
  {
    title: '心理健康维护',
    desc: '保持良好的心理状态，应对日常生活中的压力和挑战。'
  },
  {
    title: '运动与健康',
    desc: '定期运动对身体的好处，以及如何制定适合自己的运动计划。'
  },
  {
    title: '心理健康维护',
    desc: '保持良好的心理状态，应对日常生活中的压力和挑战。'
  }
])

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)
      if (!resp.data.nickname || !resp.data.avatar) {
        uni.navigateTo({ url: '/pages/patient/profile/infos/base-info' })
      }
    }
  } 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()
  }
})

function handleScan(res: any) {
  console.log('[index] scan result', res)
  const resultText = res?.result || ''
  if (resultText) {
    uni.showToast({ title: String(resultText), icon: 'none', duration: 2000 })
  } else {
    uni.showToast({ title: '未识别到有效内容', icon: 'none' })
  }
}

function onItemClick(type: string) {
  if (type === '个人中心') {
    uni.switchTab({ url: '/pages/patient/profile/index' })
  }
  if (type === '提醒管理') {
    uni.navigateTo({ url: '/pages/patient/health/reminder' })
  }
  else {
    uni.showToast({ title: '功能正在开发中', icon: 'none' })
  }
}

function onQrClick() {
  uni.showToast({ title: '二维码功能开发中', icon: 'none' })
}</script>

<style>
.page-container {
  min-height: 100vh;
  padding-top: calc(var(--status-bar-height) + 44px);
  padding-bottom: 100rpx;
  box-sizing: border-box;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.content {
  width: 100%;
}

.user-info {
  /* background-color: #fff; */
  padding: 40rpx;
  margin-top: 0rpx;
}

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

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  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;
}

.user-details {
  flex: 1;
}

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

.user-age {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}

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

.qr-button {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.qr-icon {
  width: 60rpx;
  height: 60rpx;
}

.function-container {
  padding-inline: 20rpx;
}

.function-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.function-row:last-child {
  margin-bottom: 0;
}

.function-item {
  flex: 1;
  height: 160rpx;
  background-color: #fff;
  border-radius: 20rpx;
  margin: 0 10rpx;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.item-content {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  display: flex;
  flex-direction: column;
}

.title-row {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.item-line {
  width: 8rpx;
  height: 48rpx;
  margin-right: 15rpx;
  border-radius: 10rpx;
}

.green .item-line {
  background-color: #2ed573;
}

.blue .item-line {
  background-color: #3742fa;
}

.orange .item-line {
  background-color: #ffa502;
}

.purple .item-line {
  background-color: #9c88ff;
}

.item-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.item-desc {
  font-size: 28rpx;
  color: #666;
}

.health-news-card {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.card-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.card-content {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
}

.news-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.news-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.news-image-container {
  width: 180rpx;
  height: 130rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  overflow: hidden;
}

.news-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.news-placeholder {
  width: 180rpx;
  height: 130rpx;
  background-color: #f0f0f0;
  border-radius: 10rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-icon {
  width: 40rpx;
  height: 40rpx;
  opacity: 0.5;
}

.news-text {
  flex: 1;
}

.news-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.news-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}
</style>
