<script lang="ts" setup>
/**
 * 处方失效时间展示
 * - 剩余 ≤2 小时：标红
 * - 剩余 ≤10 分钟：额外显示倒计时（每秒刷新）
 */
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';

const props = defineProps<{
  /** 失效时间戳（秒）或已格式化的字符串 */
  autoExpireTime?: number | string | null;
}>();

const nowTs = ref(Math.floor(Date.now() / 1000));
let timer: ReturnType<typeof setInterval> | null = null;

/** 解析为秒级时间戳 */
function resolveExpireTs(raw: number | string | null | undefined): number {
  if (raw == null || raw === '') return 0;
  if (typeof raw === 'number') {
    return raw > 1e12 ? Math.floor(raw / 1000) : raw;
  }
  const n = Number(raw);
  if (Number.isFinite(n) && n > 0) {
    return n > 1e12 ? Math.floor(n / 1000) : n;
  }
  const parsed = Date.parse(String(raw).replace(/-/g, '/'));
  return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : 0;
}

const expireTs = computed(() => resolveExpireTs(props.autoExpireTime));

const remainSec = computed(() => {
  if (!expireTs.value) return null;
  return expireTs.value - nowTs.value;
});

const isUrgent = computed(() => {
  const r = remainSec.value;
  return r != null && r > 0 && r <= 2 * 3600;
});

const showCountdown = computed(() => {
  const r = remainSec.value;
  return r != null && r > 0 && r <= 10 * 60;
});

const displayText = computed(() => {
  if (!expireTs.value) return '—';
  const r = remainSec.value ?? 0;
  if (r <= 0) return '已过期';
  const d = new Date(expireTs.value * 1000);
  const pad = (n: number) => String(n).padStart(2, '0');
  const base = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  if (showCountdown.value) {
    const m = Math.floor(r / 60);
    const s = r % 60;
    return `${base}（剩余 ${m}:${pad(s)}）`;
  }
  return base;
});

function startTimer() {
  stopTimer();
  timer = setInterval(() => {
    nowTs.value = Math.floor(Date.now() / 1000);
  }, 1000);
}

function stopTimer() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}

watch(
  () => props.autoExpireTime,
  () => {
    nowTs.value = Math.floor(Date.now() / 1000);
  },
);

onMounted(startTimer);
onBeforeUnmount(stopTimer);
</script>

<template>
  <span
    class="expire-time"
    :class="{
      'expire-time--urgent': isUrgent || (remainSec != null && remainSec <= 0),
      'expire-time--countdown': showCountdown,
    }"
  >
    {{ displayText }}
  </span>
</template>

<style scoped>
.expire-time {
  font-size: 12px;
  color: inherit;
}
.expire-time--urgent {
  color: #cf1322;
  font-weight: 600;
}
.expire-time--countdown {
  font-variant-numeric: tabular-nums;
}
</style>
