<template>
  <view class="details-page">
    <view class="hero">
      <view class="hero-icon">
        <uni-icons type="folder-add-filled" size="28" color="#ffffff"></uni-icons>
      </view>
      <view class="hero-info">
        <text class="hero-title">{{ record.name || '健康档案' }}</text>
        <text class="hero-subtitle">{{ record.personName || '--' }} · {{ record.occurTime || '--' }}</text>
      </view>
      <view class="hero-action" @click="handleFullExport">
        <uni-icons type="download" size="18" color="#667eea"></uni-icons>
        <text>导出</text>
      </view>
    </view>

    <view class="metric-grid">
      <view v-for="item in metrics" :key="item.key" class="metric-card">
        <text class="metric-label">{{ item.label }}</text>
        <view class="metric-value">
          <text>{{ item.value }}</text>
          <text class="metric-unit">{{ item.unit }}</text>
        </view>
      </view>
    </view>

    <view class="section-card">
      <view class="section-title">
        <text>档案信息</text>
      </view>
      <view class="info-list">
        <view class="info-row">
          <text>档案状态</text>
          <text>{{ dictStr(record.state, stateList) || '--' }}</text>
        </view>
        <view class="info-row">
          <text>档案类型</text>
          <text>{{ dictStr(record.type, typeList) || '--' }}</text>
        </view>
        <view class="info-row" v-if="record.rehabilitationTime">
          <text>康复时间</text>
          <text>{{ record.rehabilitationTime }}</text>
        </view>
        <view class="info-row" v-if="record.duration">
          <text>康复周期</text>
          <text>{{ record.duration }}</text>
        </view>
        <view class="info-row info-full" v-if="record.initialSymptoms">
          <text>初期症状</text>
          <text>{{ record.initialSymptoms }}</text>
        </view>
        <view class="info-row info-full" v-if="record.mediumTermSymptoms">
          <text>中期症状</text>
          <text>{{ record.mediumTermSymptoms }}</text>
        </view>
        <view class="info-row info-full" v-if="record.laterStageSymptoms">
          <text>后期症状</text>
          <text>{{ record.laterStageSymptoms }}</text>
        </view>
      </view>
    </view>

    <view class="tab-bar">
      <view v-for="item in tabs" :key="item.key" :class="['tab-item', activeTab === item.key ? 'active' : '']" @click="activeTab = item.key">
        <text>{{ item.label }}</text>
        <text class="tab-count">{{ item.count }}</text>
      </view>
    </view>

    <view class="record-list">
      <template v-if="activeTab === 'process'">
        <view v-for="item in processRecordList" :key="item.id" class="detail-item">
          <view class="detail-head">
            <text>过程记录</text>
            <text>{{ item.recordingTime || item.createTime || '--' }}</text>
          </view>
          <text class="detail-content">{{ item.content || item.remark || '--' }}</text>
        </view>
      </template>

      <template v-if="activeTab === 'doctor'">
        <view v-for="item in doctorRecordList" :key="item.id" class="detail-item">
          <view class="detail-head">
            <text>{{ item.hospitalName || '就医记录' }}</text>
            <text>{{ item.visitingTime || '--' }}</text>
          </view>
          <view class="detail-grid">
            <text>科室：{{ item.departments || '--' }}</text>
            <text>医生：{{ item.doctor || '--' }}</text>
            <text>费用：{{ item.totalCost || 0 }} 元</text>
          </view>
          <text class="detail-content" v-if="item.diagnosis">诊断：{{ item.diagnosis }}</text>
          <text class="detail-content" v-if="item.prescribe">医嘱：{{ item.prescribe }}</text>
        </view>
      </template>

      <template v-if="activeTab === 'temperature'">
        <view v-for="item in temperatureRecordList" :key="item.id" class="detail-item">
          <view class="detail-head">
            <text :class="['temperature', getTemperatureClass(item.temperature)]">{{ item.temperature || '--' }}℃</text>
            <text>{{ item.measureTime || '--' }}</text>
          </view>
          <text class="detail-content" v-if="item.remark">{{ item.remark }}</text>
        </view>
      </template>

      <template v-if="activeTab === 'medicine'">
        <view v-for="item in marRecordList" :key="item.id" class="detail-item">
          <view class="detail-head">
            <text>{{ item.name || item.medicineName || '用药记录' }}</text>
            <text>{{ item.dosingTime || '--' }}</text>
          </view>
          <view class="detail-grid">
            <text>剂量：{{ item.dosage || '--' }}</text>
            <text>类型：{{ dictStr(item.type, marTypeList) || '--' }}</text>
          </view>
          <text class="detail-content" v-if="item.remark">{{ item.remark }}</text>
        </view>
      </template>

      <u-empty v-if="currentList.length === 0 && !loading" mode="data" text="暂无数据"></u-empty>
      <u-loading-icon v-if="loading" mode="semicircle" size="32"></u-loading-icon>
    </view>
    <suspend></suspend>
  </view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getRecordScreen, exportRecordFull } from '@/api/health/statisticAnalysis'
import { getDicts } from '@/api/system/dict/data.js'

const loading = ref(false)
const activeTab = ref('process')
const screenData = ref({})
const typeList = ref([])
const stateList = ref([])
const marTypeList = ref([])

const record = computed(() => screenData.value.record || {})
const summary = computed(() => screenData.value.summary || {})
const temperature = computed(() => screenData.value.temperature || {})
const processRecordList = computed(() => screenData.value.processRecordList || [])
const doctorRecordList = computed(() => screenData.value.doctorRecordList || [])
const temperatureRecordList = computed(() => screenData.value.temperatureRecordList || [])
const marRecordList = computed(() => screenData.value.marRecordList || [])
const recordId = ref(null)

const tabs = computed(() => [
  { key: 'process', label: '过程', count: processRecordList.value.length },
  { key: 'doctor', label: '就医', count: doctorRecordList.value.length },
  { key: 'temperature', label: '体温', count: temperatureRecordList.value.length },
  { key: 'medicine', label: '用药', count: marRecordList.value.length }
])

const currentList = computed(() => {
  const map = {
    process: processRecordList.value,
    doctor: doctorRecordList.value,
    temperature: temperatureRecordList.value,
    medicine: marRecordList.value
  }
  return map[activeTab.value] || []
})

const metrics = computed(() => [
  { key: 'process', label: '过程记录', value: summary.value.processRecordCount || 0, unit: '条' },
  { key: 'doctor', label: '就医次数', value: summary.value.doctorCount || 0, unit: '次' },
  { key: 'cost', label: '就医费用', value: summary.value.doctorCost || 0, unit: '元' },
  { key: 'medicineDays', label: '用药天数', value: summary.value.marDayCount || 0, unit: '天' },
  { key: 'medicineCount', label: '用药次数', value: summary.value.marCount || 0, unit: '次' },
  { key: 'fever', label: '发烧天数', value: summary.value.feverDayCount || 0, unit: '天' },
  { key: 'maxTemp', label: '最高体温', value: temperature.value.maxTemp || 0, unit: '℃' },
  { key: 'avgTemp', label: '平均体温', value: temperature.value.averageTemp || 0, unit: '℃' }
])

function dictStr(val, arr) {
  const item = arr.find((dict) => dict.dictValue === val || dict.value === val)
  return item ? item.dictLabel || item.label : ''
}

function getTemperatureClass(value) {
  const temp = Number(value)
  if (temp >= 38.5) return 'danger'
  if (temp >= 37) return 'warning'
  return 'normal'
}

function loadDicts() {
  getDicts('record_type').then((res) => {
    typeList.value = res.data || []
  })
  getDicts('health_record_state').then((res) => {
    stateList.value = res.data || []
  })
  getDicts('mar_type').then((res) => {
    marTypeList.value = res.data || []
  })
}

function loadDetails(id) {
  loading.value = true
  getRecordScreen({ recordId: id, type: '1' })
    .then((res) => {
      screenData.value = res.data || {}
    })
    .finally(() => {
      loading.value = false
    })
}

function handleFullExport() {
  if (!recordId.value) {
    return
  }
  uni.showLoading({ title: '正在导出' })
  exportRecordFull(
    { recordId: recordId.value },
    `${record.value.name || '健康档案'}_完整信息_${Date.now()}.xlsx`
  ).then(() => {
    uni.showToast({ title: '导出成功', icon: 'success' })
  }).finally(() => {
    uni.hideLoading()
  })
}

onLoad((options) => {
  loadDicts()
  if (options && options.id) {
    recordId.value = options.id
    loadDetails(options.id)
  }
})
</script>

<style lang="scss" scoped>
.details-page {
  min-height: 100vh;
  padding: 24rpx;
  background: #f5f7fb;
  box-sizing: border-box;
}

.hero {
  display: flex;
  align-items: center;
  gap: 18rpx;
  padding: 28rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.hero-icon {
  width: 74rpx;
  height: 74rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.22);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.hero-info {
  display: flex;
  flex-direction: column;
  min-width: 0;
  flex: 1;
}

.hero-title {
  font-size: 36rpx;
  font-weight: 700;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hero-subtitle {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.86);
}

.hero-action {
  height: 58rpx;
  padding: 0 20rpx;
  border-radius: 29rpx;
  background: #fff;
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-shrink: 0;

  text {
    color: #667eea;
    font-size: 24rpx;
    font-weight: 700;
  }
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 18rpx;
  margin-top: 20rpx;
}

.metric-card,
.section-card,
.detail-item {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 14rpx rgba(0, 0, 0, 0.06);
}

.metric-card {
  padding: 22rpx;
}

.metric-label {
  color: #667085;
  font-size: 24rpx;
}

.metric-value {
  margin-top: 12rpx;
  display: flex;
  align-items: baseline;
  gap: 6rpx;

  text:first-child {
    color: #1f2937;
    font-size: 40rpx;
    font-weight: 800;
  }
}

.metric-unit {
  color: #8a94a6;
  font-size: 24rpx;
}

.section-card {
  margin-top: 20rpx;
  padding: 24rpx;
}

.section-title {
  color: #1f2937;
  font-size: 30rpx;
  font-weight: 700;
}

.info-list {
  margin-top: 10rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #eef1f6;

  text:first-child {
    color: #667eea;
    flex-shrink: 0;
  }

  text:last-child {
    color: #344054;
    text-align: right;
  }
}

.info-full {
  flex-direction: column;

  text:last-child {
    text-align: left;
    line-height: 1.55;
  }
}

.tab-bar {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12rpx;
  margin-top: 20rpx;
}

.tab-item {
  height: 72rpx;
  border-radius: 14rpx;
  background: #fff;
  color: #667085;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  font-size: 26rpx;
  font-weight: 600;

  &.active {
    background: #667eea;
    color: #fff;
  }
}

.tab-count {
  font-size: 22rpx;
  opacity: 0.8;
}

.record-list {
  margin-top: 18rpx;
  padding-bottom: 40rpx;
}

.detail-item {
  padding: 22rpx;
  margin-bottom: 16rpx;
}

.detail-head {
  display: flex;
  justify-content: space-between;
  gap: 16rpx;

  text:first-child {
    color: #1f2937;
    font-size: 28rpx;
    font-weight: 700;
  }

  text:last-child {
    color: #8a94a6;
    font-size: 24rpx;
    flex-shrink: 0;
  }
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12rpx;
  margin-top: 16rpx;
  color: #475467;
  font-size: 25rpx;
}

.detail-content {
  display: block;
  margin-top: 16rpx;
  color: #475467;
  font-size: 26rpx;
  line-height: 1.55;
}

.temperature {
  &.normal {
    color: #12b76a;
  }

  &.warning {
    color: #f79009;
  }

  &.danger {
    color: #f04438;
  }
}
</style>
