<template>
  <CustomNav title="我的家人" leftType="back" />
  <view class="page-container">
    <view class="family-card" v-for="family in families" :key="family.id">
      <view class="family-header">
        <view class="avatar-section">
          <view class="avatar-frame">
            <image class="avatar-img" :src="familyAvatar(family)" mode="aspectFill" />
          </view>
        </view>
        <view class="family-info">
          <text class="family-name">{{ family.boundUserNickname }}</text>
          <text class="family-phone" v-if="family.boundUserPhone">联系电话: {{ family.boundUserPhone }}</text>
          <text class="family-phone" v-else>联系电话: 未提供</text>
        </view>
      </view>
      
      <view class="action-buttons">
        <button class="action-btn primary" @click="viewHealthData(family)">健康数据</button>
        <button class="action-btn danger" @click="unbindFamily(family)">解除绑定</button>
      </view>
    </view>
    
    <view class="empty-state" v-if="families.length === 0">
      <image class="empty-icon" src="/static/icons/remixicon/account-circle-line.svg" />
      <text class="empty-text">暂无绑定的家人</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import CustomNav from '@/components/custom-nav.vue'
import { listUserBindingsByBoundUser, deleteUserBinding, type UserBindingResponse, type UserBindingPageResponse } from '@/api/userBinding'
import { downloadAvatar } from '@/api/user'
import { avatarCache } from '@/utils/avatarCache'

interface FamilyInfo extends UserBindingResponse {
  avatar?: string
}

const families = ref<FamilyInfo[]>([])
const pageData = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

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

// 获取家人列表
const fetchFamilies = async () => {
  uni.showLoading({ title: '加载中...' })
  
  try {
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.hideLoading()
      uni.showToast({
        title: '未登录',
        icon: 'none'
      })
      return
    }
    
    // 获取当前用户ID（家属ID）
    const userInfo = uni.getStorageSync('user_info')
    const familyUserId = userInfo?.id
    
    if (!familyUserId) {
      uni.hideLoading()
      uni.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
      return
    }
    
    // 查询家属绑定的家人列表（使用新的接口）
    const response = await listUserBindingsByBoundUser(
      familyUserId, 
      'FAMILY', 
      {
        pageNum: pageData.value.pageNum,
        pageSize: pageData.value.pageSize
      }
    )
    
    uni.hideLoading()
    
    const resp = response.data as any
    
    if (resp && resp.code === 200 && resp.data) {
      const pageResult = resp.data as UserBindingPageResponse
      families.value = pageResult.records as FamilyInfo[]
      pageData.value.total = pageResult.total
      pageData.value.pages = pageResult.pages
      
      // 为每个家人尝试下载头像
      for (const family of families.value) {
        try {
          if (family.patientUserId) {
            // 检查是否有缓存的头像
            if (avatarCache.has(family.patientUserId)) {
              family.avatar = avatarCache.get(family.patientUserId)
            } else {
              const dlRes: any = await downloadAvatar(String(family.patientUserId))
              if (dlRes && dlRes.statusCode === 200 && dlRes.tempFilePath) {
                family.avatar = dlRes.tempFilePath
                // 缓存头像路径
                avatarCache.set(family.patientUserId, dlRes.tempFilePath)
              }
            }
          }
        } catch (err) {
          console.warn('下载家人头像失败:', err)
        }
      }
    } else {
      uni.showToast({
        title: '获取家人信息失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取家人信息失败:', error)
    uni.showToast({
      title: '获取家人信息失败',
      icon: 'none'
    })
  }
}

const familyAvatar = (family: FamilyInfo) => {
  if (family.avatar) {
    return family.avatar
  }
  return defaultAvatar
}

const viewHealthData = (family: FamilyInfo) => {
  // 跳转到公共健康数据查看页面，传递患者ID和绑定类型参数
  uni.navigateTo({
    url: `/pages/public/health/index?patientId=${family.patientUserId}&bindingType=FAMILY`
  })
}

const unbindFamily = (family: FamilyInfo) => {
  uni.showModal({
    title: '确认解除绑定',
    content: `确定要解除与 ${family.boundUserNickname} 的绑定关系吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '正在解除绑定...' })
          
          // 调用解除绑定接口
          const response = await deleteUserBinding({
            patientUserId: family.patientUserId,
            boundUserId: family.boundUserId
          })
          
          uni.hideLoading()
          
          const resp = response.data as any
          if (resp && resp.code === 200) {
            uni.showToast({
              title: '解除绑定成功',
              icon: 'success'
            })
            
            // 重新加载家人列表
            fetchFamilies()
          } else {
            uni.showToast({
              title: resp?.message || '解除绑定失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.hideLoading()
          console.error('解除绑定失败:', error)
          uni.showToast({
            title: '解除绑定失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

onLoad(() => {
  fetchFamilies()
})

// 如果在微信小程序端且未登录，自动跳转到登录页
onShow(() => {
  const token = uni.getStorageSync('token')
  if (!token) {
    uni.reLaunch({ url: '/pages/public/login/index' })
  }
})
</script>

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

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

.family-header {
  display: flex;
  padding: 40rpx;
  border-bottom: 1rpx solid #eee;
}

.avatar-section {
  margin-right: 30rpx;
}

.avatar-frame {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid rgba(128, 128, 128, 0.5);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.family-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.family-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.family-phone {
  font-size: 28rpx;
  color: #666;
}

.action-buttons {
  display: flex;
  padding: 30rpx 40rpx;
  gap: 20rpx;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  border-radius: 10rpx;
  font-size: 28rpx;
  line-height: 70rpx;
  min-width: 40%;
}

.primary {
  background-color: #3742fa;
  color: #fff;
}

.secondary {
  background-color: #f0f0f0;
  color: #333;
}

.danger {
  background-color: #ff4757;
  color: #fff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 40rpx;
}
</style>