<template>
  <el-dialog
    v-model="visible"
    title="长者档案"
    width="600px"
    class="large-screen-dialog elder-profile-dialog"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <p>加载中...</p>
    </div>

    <!-- 档案内容 -->
    <div v-else-if="elderData" class="profile-content">
      <!-- 基本信息卡片 -->
      <div class="profile-header">
        <!-- 头像 -->
        <div class="avatar-section">
          <div class="avatar">
            {{ elderData.name?.charAt(0) || '长' }}
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="basic-info">
          <div class="info-row">
            <span class="label">姓名：</span>
            <span class="value">{{ elderData.name }}</span>
          </div>
          <div class="info-row">
            <span class="label">年龄：</span>
            <span class="value">{{ elderData.age }}岁</span>
          </div>
          <div class="info-row">
            <span class="label">性别：</span>
            <span class="value">{{ elderData.gender }}</span>
          </div>
        </div>
      </div>

      <!-- 联系方式 -->
      <div class="contact-section">
        <h4 class="section-title">联系方式</h4>
        <div class="contact-info">
          <div class="contact-item">
            <span class="label">长者电话：</span>
            <span class="value">{{ elderData.elderPhone || '暂无' }}</span>
          </div>
          <div class="contact-item">
            <span class="label">家属电话：</span>
            <span class="value">{{ elderData.relativePhone || '暂无' }}</span>
          </div>
          <div class="contact-item">
            <span class="label">地址：</span>
            <span class="value">{{ elderData.address || '暂无' }}</span>
          </div>
        </div>
      </div>

      <!-- 预警历史 -->
      <div class="warning-section">
        <h4 class="section-title">
          预警历史
          <span v-if="elderData.warningData?.length" class="warning-count">
            ({{ elderData.warningData.length }})
          </span>
        </h4>
        <div v-if="elderData.warningData && elderData.warningData.length > 0" class="warning-list">
          <div v-for="(warning, index) in elderData.warningData" :key="index" class="warning-item">
            <div class="warning-header">
              <span class="event-type">{{ warning.eventType }}</span>
              <span class="time">{{ formatTime(warning.happensAt) }}</span>
            </div>
            <div class="warning-message">{{ warning.message }}</div>
          </div>
        </div>
        <div v-else class="empty-state">
          <p>暂无预警记录</p>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <p>加载失败，请重试</p>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import fetchHttp from '@/config/axios/fetchHttp'
import { getAccessToken } from '@/utils/auth'
import { formatToDateTime } from '@/utils/dateUtil'

// 类型定义
interface WarningRecord {
  eventType: string
  message: string
  happensAt: string
}

interface ElderProfileData {
  id?: number
  name: string
  avatar?: string
  age: number
  gender: string
  relativePhone?: string
  elderPhone?: string
  address?: string
  warningData?: WarningRecord[]
}

// Props 和 Emits
interface Props {
  modelValue: boolean
  elderId?: number
}

const props = withDefaults(defineProps<Props>(), {
  elderId: 0
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 响应式数据
const loading = ref(false)
const elderData = ref<ElderProfileData | null>(null)

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit('update:modelValue', value)
  }
})

// 监听 elderId 变化，自动加载数据
watch(
  () => props.elderId,
  (newId) => {
    if (newId && visible.value) {
      fetchElderDetail(newId)
    }
  }
)

// 监听 visible 变化
watch(
  () => visible.value,
  (newVisible) => {
    if (newVisible && props.elderId) {
      fetchElderDetail(props.elderId)
    }
  }
)

// 方法
const formatTime = (time: string | number) => {
  if (!time) return '未知'
  return formatToDateTime(time)
}

// 生成假数据
const generateMockData = (elderId: number): ElderProfileData => {
  const names = ['王奶奶', '李爷爷', '张奶奶', '刘爷爷', '陈奶奶', '杨爷爷']
  const genders = ['女', '男']
  const addresses = [
    '北京市朝阳区建国路1号',
    '上海市浦东新区世纪大道100号',
    '广州市天河区珠江新城',
    '深圳市南山区科技园路1号',
    '杭州市西湖区文三路477号'
  ]
  const eventTypes = ['跌倒预警', '心率异常', '血压偏高', '离床预警', '体温异常']
  const messages = [
    '检测到长者跌倒，请立即查看',
    '心率过高，建议就医检查',
    '血压偏高，请注意休息',
    '长者离床时间过长，请关注',
    '体温异常，建议测量体温'
  ]

  const warningData: WarningRecord[] = [
    {
      eventType: eventTypes[Math.floor(Math.random() * eventTypes.length)],
      message: messages[Math.floor(Math.random() * messages.length)],
      happensAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    },
    {
      eventType: eventTypes[Math.floor(Math.random() * eventTypes.length)],
      message: messages[Math.floor(Math.random() * messages.length)],
      happensAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    },
    {
      eventType: eventTypes[Math.floor(Math.random() * eventTypes.length)],
      message: messages[Math.floor(Math.random() * messages.length)],
      happensAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    }
  ]

  return {
    id: elderId,
    name: names[elderId % names.length],
    age: 65 + (elderId % 20),
    gender: genders[elderId % 2],
    elderPhone: `1${Math.floor(Math.random() * 9) + 3}${String(Math.floor(Math.random() * 1000000000)).padStart(9, '0')}`,
    relativePhone: `1${Math.floor(Math.random() * 9) + 3}${String(Math.floor(Math.random() * 1000000000)).padStart(9, '0')}`,
    address: addresses[elderId % addresses.length],
    warningData: warningData
  }
}

const fetchElderDetail = async (elderId: number) => {
  if (!elderId) return

  loading.value = true
  try {
    const res = await fetchHttp.get(
      `/api/pc/admin/getElderDetail?elderId=${elderId}`,
      {},
      {
        headers: {
          Authorization: `Bearer ${getAccessToken()}`
        }
      }
    )

    if (res) {
      elderData.value = res
    } else {
      // 接口暂无数据，使用假数据
      console.log('接口暂无数据，使用假数据')
      elderData.value = generateMockData(elderId)
    }
  } catch (error) {
    console.error('获取长者档案失败:', error)
    // 接口出错，使用假数据
    elderData.value = generateMockData(elderId)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  elderData.value = null
}
</script>

<style lang="scss" scoped>
$primary-color: #1a73e8;
$secondary-color: #00c6ff;
$accent-color: #7b61ff;
$text-light: #fff;
$text-gray: #8a8f98;
$success-color: #26de81;
$warning-color: #fd9644;
$danger-color: #ff6b6b;

.elder-profile-dialog {
  :deep(.el-dialog__header) {
    padding: 20px !important;
    background: linear-gradient(90deg, $primary-color, $accent-color) !important;
    border-radius: 12px 12px 0 0 !important;
  }

  :deep(.el-dialog__title) {
    font-size: 18px !important;
    font-weight: 600 !important;
    color: white !important;
  }

  :deep(.el-dialog__body) {
    padding: 24px !important;
  }

  :deep(.el-dialog__close) {
    color: white !important;
  }
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: $text-gray;

  .el-icon {
    font-size: 32px;
    margin-bottom: 16px;
    color: $primary-color;

    &.is-loading {
      animation: spin 1s linear infinite;
    }
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

// 档案头部
.profile-header {
  display: flex;
  gap: 20px;
  padding: 20px;
  background: linear-gradient(135deg, rgb(26 115 232 / 15%), rgb(123 97 255 / 10%));
  border-radius: 12px;
  border: 1px solid rgb(255 255 255 / 10%);

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

    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: linear-gradient(135deg, $primary-color, $accent-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32px;
      font-weight: bold;
      color: white;
      box-shadow: 0 4px 15px rgb(26 115 232 / 30%);
    }
  }

  .basic-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 12px;

    .info-row {
      display: flex;
      gap: 12px;

      .label {
        color: $text-gray;
        min-width: 60px;
        font-weight: 500;
      }

      .value {
        color: $text-light;
        font-weight: 600;
      }
    }
  }
}

// 联系方式
.contact-section {
  padding: 20px;
  background: rgb(255 255 255 / 4%);
  border: 1px solid rgb(255 255 255 / 10%);
  border-radius: 12px;

  .section-title {
    margin: 0 0 16px 0;
    font-size: 14px;
    font-weight: 600;
    color: $secondary-color;
    text-transform: uppercase;
    letter-spacing: 1px;
  }

  .contact-info {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .contact-item {
      display: flex;
      gap: 12px;

      .label {
        color: $text-gray;
        min-width: 80px;
        font-weight: 500;
      }

      .value {
        color: $text-light;
        flex: 1;
        word-break: break-all;
      }
    }
  }
}

// 预警历史
.warning-section {
  padding: 20px;
  background: rgb(255 255 255 / 4%);
  border: 1px solid rgb(255 255 255 / 10%);
  border-radius: 12px;

  .section-title {
    margin: 0 0 16px 0;
    font-size: 14px;
    font-weight: 600;
    color: $secondary-color;
    text-transform: uppercase;
    letter-spacing: 1px;

    .warning-count {
      color: $warning-color;
      font-weight: 700;
    }
  }

  .warning-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    max-height: 300px;
    overflow-y: auto;

    .warning-item {
      padding: 12px;
      background: rgb(253 150 68 / 10%);
      border-left: 3px solid $warning-color;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      gap: 8px;

      .warning-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .event-type {
          color: $warning-color;
          font-weight: 600;
          font-size: 13px;
          padding: 2px 8px;
          background: rgb(253 150 68 / 20%);
          border-radius: 4px;
        }

        .time {
          color: $text-gray;
          font-size: 12px;
        }
      }

      .warning-message {
        color: $text-light;
        font-size: 13px;
        line-height: 1.5;
      }
    }
  }

  .empty-state {
    padding: 40px 20px;
    text-align: center;
    color: $text-gray;

    p {
      margin: 0;
      font-size: 14px;
    }
  }
}

// 滚动条样式
.warning-list::-webkit-scrollbar {
  width: 6px;
}

.warning-list::-webkit-scrollbar-track {
  background: rgb(255 255 255 / 5%);
  border-radius: 3px;
}

.warning-list::-webkit-scrollbar-thumb {
  background: rgb(26 115 232 / 50%);
  border-radius: 3px;

  &:hover {
    background: rgb(26 115 232 / 70%);
  }
}
</style>
