<template>
  <Loading v-if="pageLoading && alerts.length === 0" text="加载中..." />
  <scroll-view
    v-else
    scroll-y
    class="page-scroll"
    @scrolltolower="onLoadMore"
  >
    <view :class="['page-content', elderClass]">
      <!-- 严重程度筛选 -->
      <scroll-view scroll-x class="tab-bar">
        <view
          v-for="tab in SEVERITY_TABS"
          :key="tab.key"
          :class="['tab-chip', { 'tab-chip--active': activeSeverity === tab.key }]"
          @tap="handleSeverityChange(tab.key)"
        >
          <text class="tab-chip__text">{{ tab.label }}</text>
        </view>
      </scroll-view>

      <!-- 列表统计 -->
      <view v-if="filteredAlerts.length > 0" class="list-meta">
        <text class="list-meta__text">共 {{ filteredAlerts.length }} 条告警</text>
      </view>

      <!-- 告警卡片 -->
      <EmptyState v-if="!pageLoading && filteredAlerts.length === 0" icon="🔔" title="暂无告警" />
      <view v-else class="alert-cards">
        <view
          v-for="alert in filteredAlerts"
          :key="alert.id"
          class="alert-card"
          @tap="goDetail(alert.id)"
        >
          <view class="alert-card__header">
            <text class="alert-card__title">{{ alert.title }}</text>
            <view
              class="alert-card__severity"
              :style="getSeverityStyle(alert.severity)"
            >
              <text class="alert-card__severity-text">
                {{ getSeverityLabel(alert.severity) }}
              </text>
            </view>
          </view>
          <view class="alert-card__body">
            <text v-if="alert.detail?.patient_name" class="alert-card__patient">
              {{ alert.detail.patient_name }}
            </text>
            <text v-if="alert.detail?.indicator_name" class="alert-card__indicator">
              {{ alert.detail.indicator_name }}
            </text>
          </view>
          <view class="alert-card__footer">
            <text class="alert-card__time">{{ formatAlertTime(alert.created_at) }}</text>
            <view
              class="alert-card__status"
              :style="getStatusInlineStyle(alert.status)"
            >
              <text class="alert-card__status-text">{{ getStatusLabel(alert.status) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="!loadingMore && alerts.length >= total && total > 0" class="load-hint-wrap">
        <text class="load-hint">没有更多了</text>
      </view>
      <Loading v-if="loadingMore" text="加载中..." />
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useElderClass } from '@/composables/useElderClass'
import { listAlerts, cacheAlerts } from '@/services/doctor/alerts'
import type { Alert } from '@/services/doctor/alerts'
import { getStatusInlineStyle, getStatusLabel, getSeverityStyle, getSeverityLabel } from '@/utils/statusTag'
import { formatDate, getRelativeTime } from '@/utils/date'
import Loading from '@/components/Loading.vue'
import EmptyState from '@/components/EmptyState.vue'

const SEVERITY_TABS = [
  { key: '', label: '全部' },
  { key: 'info', label: getSeverityLabel('info') },
  { key: 'warning', label: getSeverityLabel('warning') },
  { key: 'critical', label: getSeverityLabel('critical') },
  { key: 'urgent', label: getSeverityLabel('urgent') },
] as const

const { elderClass } = useElderClass()

const alerts = ref<Alert[]>([])
const activeSeverity = ref('')
const pageLoading = ref(true)
const loadingMore = ref(false)
const isLoading = ref(false)
const total = ref(0)
const page = ref(1)

const filteredAlerts = computed(() => {
  if (!activeSeverity.value) return alerts.value
  return alerts.value.filter((a) => a.severity === activeSeverity.value)
})

function formatAlertTime(dateStr: string): string {
  const d = new Date(dateStr)
  const now = new Date()
  const diffDays = Math.floor((now.getTime() - d.getTime()) / (1000 * 60 * 60 * 24))
  if (diffDays < 1) return getRelativeTime(dateStr)
  if (diffDays < 7) return `${diffDays}天前`
  return formatDate(dateStr, 'MM-DD HH:mm')
}

async function loadAlerts(pageNum: number, isRefresh = false) {
  if (isLoading.value) return
  isLoading.value = true
  if (isRefresh) {
    pageLoading.value = true
  } else {
    loadingMore.value = true
  }
  try {
    const res = await listAlerts({
      page: pageNum,
      page_size: 20,
    })
    const list = res.data || []
    if (isRefresh) {
      alerts.value = list
    } else {
      alerts.value = [...alerts.value, ...list]
    }
    cacheAlerts(list)
    total.value = res.total || 0
    page.value = pageNum
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    pageLoading.value = false
    loadingMore.value = false
    isLoading.value = false
  }
}

function handleSeverityChange(key: string) {
  activeSeverity.value = key
}

function goDetail(id: string) {
  uni.navigateTo({ url: `/pages-sub/doctor/alerts/detail/index?id=${id}` })
}

function onLoadMore() {
  if (!isLoading.value && alerts.value.length < total.value) {
    loadAlerts(page.value + 1)
  }
}

onShow(() => {
  loadAlerts(1, true)
})

onPullDownRefresh(() => {
  loadAlerts(1, true).finally(() => {
    uni.stopPullDownRefresh()
  })
})
</script>

<style lang="scss" scoped>
.page-scroll {
  height: 100vh;
  background: $bg;
}

.page-content {
  padding: 24px;
  padding-bottom: 120px;
}

// ── 标签栏 ──
.tab-bar {
  white-space: nowrap;
  margin-bottom: 24px;
  width: 100%;
}

.tab-chip {
  display: inline-flex;
  align-items: center;
  padding: 10px 28px;
  min-height: $touch-min;
  border-radius: $r-pill;
  background: $card;
  box-shadow: $shadow-sm;
  margin-right: 12px;

  &--active {
    background: $pri;

    .tab-chip__text {
      color: $card;
    }
  }

  &__text {
    font-size: var(--tk-font-body);
    color: $tx2;
    font-weight: 500;
  }
}

// ── 列表统计 ──
.list-meta {
  margin-bottom: 16px;

  &__text {
    font-size: var(--tk-font-body-sm);
    color: $tx3;
  }
}

// ── 告警卡片 ──
.alert-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.alert-card {
  @include card;
  position: relative;

  &:active {
    background: $bd-l;
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  &__title {
    font-size: var(--tk-font-body-lg);
    font-weight: 600;
    color: $tx;
    flex: 1;
    margin-right: 16px;
    line-height: 1.4;
  }

  &__severity {
    @include status-inline;
    flex-shrink: 0;
  }

  &__severity-text {
    font-size: var(--tk-font-body-sm);
    font-weight: 600;
  }

  &__body {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 12px;
  }

  &__patient {
    font-size: var(--tk-font-body);
    color: $tx2;
    font-weight: 500;
  }

  &__indicator {
    font-size: var(--tk-font-body-sm);
    color: $tx3;
  }

  &__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &__time {
    font-size: var(--tk-font-cap);
    color: $tx3;
  }

  &__status {
    @include status-inline;
  }

  &__status-text {
    font-size: var(--tk-font-body-sm);
  }
}

// ── 加载提示 ──
.load-hint-wrap {
  text-align: center;
  padding: 20px;
}

.load-hint {
  font-size: var(--tk-font-body-sm);
  color: $tx3;
}
</style>
