<template>
  <view :class="['dialysis-prescriptions-page', elderClass]">
    <text class="page-title">透析处方</text>

    <template v-if="!authStore.currentPatient">
      <EmptyState icon="📋" title="请先在就诊人管理中选择就诊人" />
    </template>
    <template v-else>
      <view v-if="prescriptions.length === 0 && !loading" class="empty-wrap">
        <EmptyState icon="📋" title="暂无透析处方" />
      </view>

      <scroll-view v-else scroll-y class="prescription-scroll" @scrolltolower="loadMore">
        <view
          v-for="p in prescriptions" :key="p.id"
          class="prescription-card"
          @tap="goDetail(p.id)"
        >
          <view class="prescription-card-top">
            <text class="prescription-model">{{ p.dialyzer_model || '未指定型号' }}</text>
            <text :class="['status-tag', statusInfo(p.status).cls]">{{ statusInfo(p.status).label }}</text>
          </view>
          <view class="prescription-meta">
            <text v-if="p.frequency_per_week != null" class="meta-item">{{ p.frequency_per_week }}次/周</text>
            <text v-if="p.duration_minutes != null" class="meta-item">每次{{ p.duration_minutes }}分钟</text>
          </view>
          <text v-if="p.effective_from || p.effective_to" class="prescription-date">
            {{ p.effective_from || '...' }} ~ {{ p.effective_to || '...' }}
          </text>
        </view>
        <Loading v-if="loading" text="加载中..." />
        <view v-if="!loading && prescriptions.length >= total && total > 0" class="no-more"><text class="no-more-text">没有更多了</text></view>
      </scroll-view>
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { listDialysisPrescriptions, type DialysisPrescription } from '@/services/dialysis'
import EmptyState from '@/components/EmptyState.vue'
import Loading from '@/components/Loading.vue'
import { useAuthStore } from '@/stores/auth'
import { useElderClass } from '@/composables/useElderClass'

const STATUS_MAP: Record<string, { label: string; cls: string }> = {
  active: { label: '生效中', cls: 'active' },
  inactive: { label: '已停用', cls: 'inactive' },
  expired: { label: '已过期', cls: 'expired' },
}

const { elderClass } = useElderClass()
const authStore = useAuthStore()
const prescriptions = ref<DialysisPrescription[]>([])
const page = ref(1)
const total = ref(0)
const loading = ref(false)
let loadingGuard = false

const statusInfo = (s: string) => STATUS_MAP[s] || { label: s, cls: '' }

const fetchData = async (p: number, append = false) => {
  if (!authStore.currentPatient || loadingGuard) return
  loadingGuard = true
  loading.value = true
  try {
    const res = await listDialysisPrescriptions({ patient_id: authStore.currentPatient.id, page: p, page_size: 20 })
    const list = res.data || []
    prescriptions.value = append ? [...prescriptions.value, ...list] : list
    total.value = res.total
    page.value = p
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loadingGuard = false
    loading.value = false
  }
}

const loadMore = () => {
  if (!loading.value && prescriptions.value.length < total.value) {
    fetchData(page.value + 1, true)
  }
}

const goDetail = (id: string) => {
  uni.navigateTo({ url: `/pages-sub/pkg-profile/dialysis-prescriptions/detail/index?id=${id}` })
}

onShow(() => { fetchData(1) })
onPullDownRefresh(() => { fetchData(1).finally(() => uni.stopPullDownRefresh()) })
</script>

<style lang="scss" scoped>
.dialysis-prescriptions-page { min-height: 100vh; background: $bg; padding: 24px; }
.page-title { @include section-title; }
.prescription-scroll { height: calc(100vh - 80px); }
.prescription-card { @include card; margin-bottom: 12px; }
.prescription-card-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.prescription-model { font-size: var(--tk-font-body); font-weight: 500; color: $tx; }
.status-tag { padding: 2px 10px; border-radius: 4px; font-size: var(--tk-font-cap);
  &.active { background: rgba(82,196,26,0.1); color: $acc; }
  &.inactive { background: rgba(0,0,0,0.04); color: $tx3; }
  &.expired { background: rgba(255,77,79,0.1); color: $dan; }
}
.prescription-meta { display: flex; gap: 16px; margin-top: 4px; }
.meta-item { font-size: var(--tk-font-cap); color: $tx2; }
.prescription-date { font-size: var(--tk-font-cap); color: $tx3; display: block; margin-top: 4px; }
.no-more { @include flex-center; padding: 20px; }
.no-more-text { font-size: var(--tk-font-cap); color: $tx3; }
.empty-wrap { padding-top: 40px; }
</style>
