<template>
  <view :class="['consents-page', elderClass]">
    <text class="page-title">知情同意</text>

    <view class="consent-list">
      <view v-for="c in consents" :key="c.id" class="consent-card">
        <view class="consent-card__header">
          <text class="consent-card__type">{{ CONSENT_TYPE_MAP[c.consent_type] || c.consent_type }}</text>
          <text :class="['status-tag', (STATUS_MAP[c.status] || { cls: '' }).cls]">
            {{ (STATUS_MAP[c.status] || { label: c.status }).label }}
          </text>
        </view>
        <text class="consent-card__scope">范围: {{ c.consent_scope }}</text>
        <text v-if="c.granted_at" class="consent-card__date">签署时间: {{ c.granted_at }}</text>
        <text v-if="c.revoked_at" class="consent-card__date">撤回时间: {{ c.revoked_at }}</text>
        <text v-if="c.expiry_date" class="consent-card__expiry">有效期至: {{ c.expiry_date }}</text>
        <view
          v-if="c.status === 'granted'"
          :class="['revoke-btn', revoking === c.id ? 'revoke-btn--disabled' : '']"
          @tap="handleRevoke(c)"
        >
          <text class="revoke-btn__text">{{ revoking === c.id ? '处理中...' : '撤回同意' }}</text>
        </view>
      </view>
    </view>

    <EmptyState
      v-if="consents.length === 0 && !loading"
      :text="authStore.currentPatient ? '暂无知情同意记录' : '请先在就诊人管理中选择就诊人'"
    />

    <Loading v-if="loading" text="加载中..." />
  </view>
</template>

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

const CONSENT_TYPE_MAP: Record<string, string> = {
  data_processing: '数据处理同意',
  health_data_collection: '健康数据采集',
  research_use: '科研使用',
  third_party_share: '第三方共享',
  genetic_testing: '基因检测',
  telemedicine: '远程医疗',
}

const STATUS_MAP: Record<string, { label: string; cls: string }> = {
  granted: { label: '已签署', cls: 'granted' },
  revoked: { label: '已撤回', cls: 'revoked' },
}

const { elderClass } = useElderClass()
const authStore = useAuthStore()
const consents = ref<Consent[]>([])
const page = ref(1)
const total = ref(0)
const loading = ref(false)
const revoking = ref<string | null>(null)

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

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

const handleRevoke = async (consent: Consent) => {
  const res = await uni.showModal({
    title: '确认撤回',
    content: `确定要撤回「${CONSENT_TYPE_MAP[consent.consent_type] || consent.consent_type}」的同意吗？`,
  })
  if (!res.confirm) return
  revoking.value = consent.id
  try {
    const updated = await revokeConsent(consent.id, consent.version)
    consents.value = consents.value.map((c) => c.id === updated.id ? updated : c)
    uni.showToast({ title: '已撤回', icon: 'success' })
  } catch {
    uni.showToast({ title: '撤回失败', icon: 'none' })
  } finally {
    revoking.value = null
  }
}

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

<style lang="scss" scoped>
.consents-page { min-height: 100vh; background: $bg; padding: 32px 24px; padding-bottom: 40px; }
.page-title { @include section-title; padding-left: 4px; }
.consent-list { display: flex; flex-direction: column; gap: 16px; }
.consent-card { background: $card; border-radius: $r; padding: 28px; box-shadow: $shadow-sm; }
.consent-card__header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.consent-card__type { font-size: var(--tk-font-body-lg); font-weight: bold; color: $tx; }
.status-tag {
  @include tag($bd-l, $tx3);
  &.granted { @include tag($acc-l, $acc); }
  &.revoked { @include tag($dan-l, $dan); }
}
.consent-card__scope,
.consent-card__date,
.consent-card__expiry {
  font-size: var(--tk-font-h2);
  color: $tx2;
  display: block;
  margin-bottom: 4px;
  font-variant-numeric: tabular-nums;
}
.revoke-btn {
  margin-top: 16px;
  padding: 12px 0;
  min-height: $touch-min;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-radius: $r-sm;
  border: 1px solid $dan;
  &:active { background: $dan-l; }
  &--disabled { opacity: 0.5; }
}
.revoke-btn__text { font-size: var(--tk-font-h2); color: $dan; font-weight: 500; }
</style>
