<template>
  <CustomNav title="二维码" leftType="back" :opacity="0" />
  <view class="page-container">
    <view class="content">
      <view class="qr-card">
        <view class="user-info">
          <view class="title-row">
            <text class="card-title">{{ getPageTitle(user.role) }}</text>
            <view class="role-badge">{{ getRoleText(user.role) }}</view>
          </view>
          <text class="user-name">{{ user.nickname || '未知用户' }}</text>
          <text class="qr-desc">{{ getPageDesc(user.role) }}</text>
        </view>
        <view class="qr-container">
          <canvas
            canvas-id="qrcode"
            class="qr-canvas"
            v-if="qrData"
          ></canvas>
        </view>
        <view class="refresh-btn" @click="refreshAndGenerate">
          <text class="refresh-text">刷新二维码</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getWindowWidth, rpxToPx } from '@/utils/platform'
import { onShow } from '@dcloudio/uni-app'
import CustomNav from '@/components/custom-nav.vue'
// @ts-ignore
import drawQrcode from 'weapp-qrcode'
import { fetchUserInfo as fetchUserInfoApi } from '@/api/user'

const user = ref<{ nickname?: string; role?: string | number; openid?: string; wx_openid?: string }>({})
const qrData = ref('')
const isFetching = ref(false)

const getPageTitle = (role: string | number | undefined) => {
  const roleMap: { [key: number]: string } = {
    2: '医生身份码',
    3: '个人身份码',
    4: '家属身份码'
  }
  return roleMap[Number(role)] || '身份码'
}

const getPageDesc = (role: string | number | undefined) => {
  const roleMap: { [key: number]: string } = {
    2: '扫码绑定医生',
    3: '扫码绑定患者或查看健康档案',
    4: '扫码查看相关患者健康档案'
  }
  return roleMap[Number(role)] || '扫码查看信息'
}

const getRoleText = (role: string | number | undefined) => {
  const roleMap: { [key: number]: string } = {
    2: '医生码',
    3: '患者码',
    4: '家属码'
  }
  return roleMap[Number(role)] || '身份码'
}

const loadUser = () => {
  try {
    const u = uni.getStorageSync('user_info')
    console.log('Loaded user_info from storage:', u)
    if (u) {
      user.value = u
      console.log('User data set:', user.value)
    }
  } catch (e) {
    console.error('Error loading user info:', e)
  }
}

// 从后端刷新用户信息（仅在用户手动触发刷新时调用）
const fetchUserInfo = async () => {
  try {
    const token = uni.getStorageSync('token')
    if (!token) return
    if (isFetching.value) return
    isFetching.value = true
    uni.showLoading({ title: '加载中...' })
    const response: any = await fetchUserInfoApi()
    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' })
      isFetching.value = false
      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)
  } finally {
    isFetching.value = false
  }
}

// 手动刷新：先从后端拉取最新用户信息，再重新生成二维码
const refreshAndGenerate = async () => {
  await fetchUserInfo()
  // fetchUserInfo 可能会在 token 无效时跳转登录，下面仅在本地有用户信息时重绘二维码
  if (user.value && (user.value.wx_openid || user.value.openid)) {
    generateQRCode()
  } else {
    // 如果后端未返回 openid 等，仍尝试使用本地缓存绘制
    loadUser()
    generateQRCode()
  }
}

const generateQRCode = async () => {
  console.log('Generating QR code, user data:', user.value)
  if (!user.value.wx_openid || !user.value.role) {
    console.log('Missing wx_openid or role:', { wx_openid: user.value.wx_openid, role: user.value.role })
    uni.showToast({ title: '用户信息不完整', icon: 'none' })
    return
  }
  const data = JSON.stringify({
    openid: user.value.wx_openid,
    role: user.value.role
  })
  console.log('QR data:', data)
  qrData.value = data
  // 获取屏幕宽度并计算 rpx->px
  const width = await getWindowWidth().catch(() => 375)
  const qrSizePx = rpxToPx(350, width)
  // 使用 weapp-qrcode 生成二维码
  drawQrcode({
    width: qrSizePx,
    height: qrSizePx,
    canvasId: 'qrcode',
    text: data
  })
}

onShow(() => {
  // 首次进入时不主动向后端请求数据（首页已获取），但需要检查登录态
  const token = uni.getStorageSync('token')
  if (!token) {
    uni.reLaunch({ url: '/pages/public/login/index' })
    return
  }
  loadUser()
  generateQRCode()
})
</script>

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

.content {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qr-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 
    0 20rpx 40rpx rgba(0, 0, 0, 0.1),
    0 8rpx 16rpx rgba(0, 0, 0, 0.05),
    inset 0 1rpx 0 rgba(255, 255, 255, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 600rpx;
  width: 90%;
  position: relative;
  overflow: hidden;
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

/* 渐变边框效果 */
.qr-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 32rpx;
  padding: 2rpx;
  background: linear-gradient(135deg, #667eea, #764ba2, #f093fb);
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  pointer-events: none;
}

.user-info {
  text-align: center;
  margin-bottom: 60rpx;
  position: relative;
  width: 100%;
}

.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  padding: 20rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #2c3e50;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.role-badge {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 600;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.user-name {
  font-size: 48rpx;
  font-weight: 700;
  color: #2c3e50;
  display: block;
  margin: 20rpx 0;
  background: linear-gradient(135deg, #2c3e50, #4a6572);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.qr-desc {
  font-size: 28rpx;
  color: #6c757d;
  font-weight: 400;
  display: block;
  margin-top: 15rpx;
  line-height: 1.5;
  padding: 0 20rpx;
}

.qr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 24rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  box-shadow: 
    inset 0 2rpx 4rpx rgba(255, 255, 255, 0.8),
    0 8rpx 20rpx rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

/* 二维码装饰角 */
.qr-container::before,
.qr-container::after {
  content: '';
  position: absolute;
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #667eea;
}

.qr-container::before {
  top: 10rpx;
  left: 10rpx;
  border-right: none;
  border-bottom: none;
}

.qr-container::after {
  bottom: 10rpx;
  right: 10rpx;
  border-left: none;
  border-top: none;
}

.qr-container:active {
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.qr-canvas {
  opacity: 0.75;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(0, 0, 0, 0.1);
}

@keyframes cardEntrance {
  0% {
    opacity: 0;
    transform: translate3d(0, 30rpx, 0) scale(0.95);
  }
  100% {
    opacity: 1;
    transform: translate3d(0, 0, 0) scale(1);
  }
}

/* 响应式优化 */
/* 针对不同屏幕尺寸的适配 */
@media (max-width: 375px) {
  .qr-card {
    padding: 40rpx 30rpx;
    width: 95%;
  }
  
  .user-name {
    font-size: 40rpx;
  }
  
  .qr-canvas {
    width: 350rpx;
    height: 350rpx;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .qr-card {
    background: rgba(40, 40, 40, 0.95);
    color: #ffffff;
  }
  
  .card-title, .user-name {
    color: #ffffff;
  }
  
  .qr-desc {
    color: #b0b0b0;
  }
}

/* 添加刷新按钮（可选） */
.refresh-btn {
  margin-top: 40rpx;
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: 500;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.refresh-btn:active {
  box-shadow: 0 2rpx 6rpx rgba(102, 126, 234, 0.4);
}
</style>
