<template>
  <Loading v-if="pageLoading && records.length === 0" text="加载中..." />
  <scroll-view
    v-else
    scroll-y
    class="page-scroll"
    @scrolltolower="onLoadMore"
  >
    <view :class="['page-content', elderClass]">
      <!-- 状态筛选 -->
      <view class="tabs">
        <view
          v-for="tab in STATUS_TABS"
          :key="tab.key"
          :class="['tab', activeStatus === tab.key ? 'tab--active' : '']"
          @tap="handleStatusChange(tab.key)"
        >
          <text>{{ tab.label }}</text>
        </view>
      </view>

      <!-- 列表统计 -->
      <view v-if="records.length > 0" class="list-meta">
        <text class="list-meta__text">共 {{ total }} 条记录</text>
      </view>

      <!-- 透析记录卡片 -->
      <EmptyState v-if="!pageLoading && records.length === 0" icon="💉" title="暂无透析记录" />
      <view v-else class="record-cards">
        <view
          v-for="record in records"
          :key="record.id"
          class="record-card"
          @tap="goDetail(record.id)"
        >
          <view class="record-card__header">
            <text class="record-card__patient">{{ record.patient_name || formatDate(record.dialysis_date, 'MM-DD') }}</text>
            <view
              class="record-card__status"
              :style="getStatusInlineStyle(record.status)"
            >
              <text class="record-card__status-text">
                {{ getStatusLabel(record.status) }}
              </text>
            </view>
          </view>
          <view class="record-card__body">
            <view class="record-card__info-row">
              <text class="record-card__label">透析日期</text>
              <text class="record-card__value">{{ formatDate(record.dialysis_date, 'YYYY-MM-DD') }}</text>
            </view>
            <view class="record-card__info-row">
              <text class="record-card__label">透析方式</text>
              <text class="record-card__value">{{ dialysisTypeLabel(record.dialysis_type) }}</text>
            </view>
            <view v-if="record.dialysis_duration" class="record-card__info-row">
              <text class="record-card__label">时长</text>
              <text class="record-card__value">{{ record.dialysis_duration }} 分钟</text>
            </view>
          </view>
          <view class="record-card__type-tag">
            <text class="record-card__type-tag-text">
              {{ dialysisTypeShort(record.dialysis_type) }}
            </text>
          </view>
        </view>
      </view>

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

    <!-- 新建按钮 -->
    <view class="fab" @tap="goCreate">
      <text class="fab__icon">+</text>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useElderClass } from '@/composables/useElderClass'
import { listDialysisRecords } from '@/services/doctor/dialysis'
import type { DialysisRecord } from '@/services/doctor/dialysis'

// 医生端透析列表后端返回的扩展字段
interface DoctorDialysisRecord extends DialysisRecord {
  patient_name?: string
}
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag'
import { formatDate } from '@/utils/date'
import Loading from '@/components/Loading.vue'
import EmptyState from '@/components/EmptyState.vue'

const STATUS_TABS = [
  { key: '', label: '全部' },
  { key: 'in_progress', label: '进行中' },
  { key: 'completed', label: '已完成' },
  { key: 'cancelled', label: '已取消' },
] as const

const { elderClass } = useElderClass()

const records = ref<DoctorDialysisRecord[]>([])
const activeStatus = ref('')
const pageLoading = ref(true)
const loadingMore = ref(false)
const isLoading = ref(false)
const total = ref(0)
const page = ref(1)
const patientId = ref('')

function dialysisTypeLabel(type: string): string {
  if (type === 'hemodialysis') return '血液透析'
  if (type === 'peritoneal') return '腹膜透析'
  return type
}

function dialysisTypeShort(type: string): string {
  if (type === 'hemodialysis') return 'HD'
  if (type === 'peritoneal') return 'PD'
  return type
}

async function loadRecords(pageNum: number, isRefresh = false) {
  if (isLoading.value) return
  isLoading.value = true
  if (isRefresh) {
    pageLoading.value = true
  } else {
    loadingMore.value = true
  }
  try {
    const params: { page: number; page_size: number; status?: string } = {
      page: pageNum,
      page_size: 20,
    }
    if (activeStatus.value) {
      params.status = activeStatus.value
    }
    const res = await listDialysisRecords(patientId.value, params)
    const list = res.data || []
    if (isRefresh) {
      records.value = list
    } else {
      records.value = [...records.value, ...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 handleStatusChange(key: string) {
  activeStatus.value = key
}

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

function goCreate() {
  uni.navigateTo({
    url: `/pages-sub/doctor/dialysis/create/index${patientId.value ? `?patientId=${patientId.value}` : ''}`,
  })
}

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

watch(activeStatus, () => {
  loadRecords(1, true)
})

onLoad((query) => {
  patientId.value = query?.patientId || ''
})

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

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

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

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

// ── 状态标签 ──
.tabs {
  display: flex;
  background: $card;
  border-radius: $r;
  box-shadow: $shadow-sm;
  margin-bottom: 24px;
  overflow: hidden;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 20px 0;
  font-size: var(--tk-font-body);
  color: $tx2;
  position: relative;

  &--active {
    color: $pri;
    font-weight: 600;
    background: $pri-l;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 20%;
      right: 20%;
      height: 3px;
      background: $pri;
      border-radius: 3px;
    }
  }
}

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

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

// ── 记录卡片 ──
.record-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

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

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

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

  &__patient {
    font-size: var(--tk-font-body-lg);
    font-weight: 600;
    color: $tx;
    flex: 1;
  }

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

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

  &__body {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

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

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

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

  &__type-tag {
    position: absolute;
    top: 28px;
    right: 28px;
    margin-top: 32px;
  }

  &__type-tag-text {
    @include tag($pri-l, $pri);
    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;
}

// ── 浮动新建按钮 ──
.fab {
  position: fixed;
  right: 32px;
  bottom: 100px;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: $pri;
  @include flex-center;
  box-shadow: $shadow-lg;

  &:active {
    opacity: 0.85;
    transform: scale(0.95);
  }

  &__icon {
    font-size: var(--tk-font-h1);
    color: $card;
    font-weight: 300;
    line-height: 1;
  }
}
</style>
