<script lang="ts" setup>
/**
 * 未来7天预约号卡片：总数 + 按天分布横条，点击打开明细弹窗（分页 + 日期筛选）
 * scope 由后端按登录身份判定：医生=本人 / 诊所管理员=本店 / 平台管理员=全平台，
 * 前端不传身份参数，防止越权拉取他人数据
 */
import type {
  AppointmentUpcomingDay,
  AppointmentUpcomingItem,
  AppointmentUpcomingResult,
} from '../api';

import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { IconifyIcon as VbenIcon } from '@vben/icons';

import { Empty, Pagination, Spin, Tag } from 'ant-design-vue';

import { getAppointmentUpcomingApi, getAppointmentUpcomingListApi } from '../api';
import KpiCard from './KpiCard.vue';
import StatChip from './StatChip.vue';

interface Props {
  title: string;
}
defineProps<Props>();

const data = ref<AppointmentUpcomingResult | null>(null);
const loading = ref(true);
const error = ref(false);

/** 明细弹窗状态：列表/分页/日期筛选（'' = 全部7天） */
const listItems = ref<AppointmentUpcomingItem[]>([]);
const listTotal = ref(0);
const listLoading = ref(false);
const listPage = ref(1);
const listPageSize = ref(10);
const filterDate = ref('');

/** 明细弹窗：footer 关闭（纯查看），标题带统计窗口说明 */
const [DetailModal, detailModalApi] = useVbenModal({
  footer: false,
  title: '未来7天预约明细',
  class: 'w-[720px]',
});

/**
 * 拉取卡片统计；失败进入错误态可重试
 */
async function fetchSummary() {
  loading.value = true;
  error.value = false;
  try {
    data.value = await getAppointmentUpcomingApi();
  } catch {
    error.value = true;
  } finally {
    loading.value = false;
  }
}

/**
 * 拉取明细分页（按当前筛选日期与页码）
 */
async function fetchList() {
  listLoading.value = true;
  try {
    const res = await getAppointmentUpcomingListApi({
      page: listPage.value,
      page_size: listPageSize.value,
      visit_date: filterDate.value,
    });
    listItems.value = res.items || [];
    listTotal.value = res.total || 0;
  } catch {
    listItems.value = [];
    listTotal.value = 0;
  } finally {
    listLoading.value = false;
  }
}

/**
 * 打开明细弹窗：默认展示全部 7 天，从第一页开始
 */
function openDetail(day?: AppointmentUpcomingDay) {
  filterDate.value = day ? day.date : '';
  listPage.value = 1;
  detailModalApi.open();
  fetchList();
}

/**
 * 切换日期筛选（弹窗内 pill 点击）：回到第一页重查
 */
function switchFilter(date: string) {
  if (filterDate.value === date) return;
  filterDate.value = date;
  listPage.value = 1;
  fetchList();
}

/**
 * 翻页
 */
function onPageChange(page: number, pageSize: number) {
  listPage.value = page;
  listPageSize.value = pageSize;
  fetchList();
}

/**
 * 状态标签颜色：待支付/待接诊需要关注用暖色，其余中性
 */
function statusColor(item: AppointmentUpcomingItem) {
  if (item.is_pay !== 1) return 'orange';
  if (item.status === 1) return 'blue';
  if (item.status === 2) return 'processing';
  return 'default';
}

onMounted(fetchSummary);
</script>

<template>
  <div class="appt-widget">
    <KpiCard
      :title="title"
      subtitle="含今天"
      :loading="loading"
      :error="error"
      @refresh="fetchSummary"
    >
      <template v-if="data">
        <StatChip
          :highlight="data.total > 0"
          :value="data.total"
          icon="lucide:calendar-clock"
          label="未来7天预约"
          @click="openDetail()"
        />
        <!-- 按天分布横条：每天一格，点击直接按天筛选打开明细 -->
        <div class="appt-days">
          <div
            v-for="day in data.days"
            :key="day.date"
            class="appt-day"
            :class="{ 'appt-day--active': day.count > 0 }"
            role="button"
            tabindex="0"
            @click="openDetail(day)"
            @keydown.enter="openDetail(day)"
          >
            <span class="appt-day__label">{{ day.label }}</span>
            <span class="appt-day__count">{{ day.count }}</span>
            <span class="appt-day__week">{{ day.week }}</span>
          </div>
        </div>
      </template>
    </KpiCard>

    <!-- 明细弹窗：日期筛选 pill + 明细行 + 分页（放卡片外层，避免随加载态卸载） -->
    <DetailModal>
      <div class="appt-detail">
        <div class="appt-detail__filters">
          <span
            class="appt-pill"
            :class="{ 'appt-pill--active': filterDate === '' }"
            role="button"
            tabindex="0"
            @click="switchFilter('')"
            @keydown.enter="switchFilter('')"
          >
            全部7天
          </span>
          <span
            v-for="day in data ? data.days : []"
            :key="day.date"
            class="appt-pill"
            :class="{ 'appt-pill--active': filterDate === day.date }"
            role="button"
            tabindex="0"
            @click="switchFilter(day.date)"
            @keydown.enter="switchFilter(day.date)"
          >
            {{ day.label }}({{ day.count }})
          </span>
        </div>

        <Spin :spinning="listLoading">
          <ul v-if="listItems.length > 0" class="appt-detail__list">
            <li v-for="item in listItems" :key="item.register_id" class="appt-row">
              <div class="appt-row__date">
                <span class="appt-row__day">{{ item.visit_date }}</span>
                <span class="appt-row__week">{{ item.week }}</span>
              </div>
              <div class="appt-row__main">
                <div class="appt-row__line1">
                  <span class="appt-row__patient">{{ item.patient_name || '未知就诊人' }}</span>
                  <span class="appt-row__slot">{{ item.slot_label }}</span>
                </div>
                <div class="appt-row__line2">
                  <span v-if="item.doctor_name">医生：{{ item.doctor_name }}</span>
                  <span v-if="item.store_name">门店：{{ item.store_name }}</span>
                  <span v-if="item.order_no">单号：{{ item.order_no }}</span>
                </div>
              </div>
              <Tag :color="statusColor(item)">{{ item.status_text }}</Tag>
            </li>
          </ul>
          <Empty v-else-if="!listLoading" description="暂无预约" />
        </Spin>

        <div v-if="listTotal > 0" class="appt-detail__pager">
          <Pagination
            :current="listPage"
            :page-size="listPageSize"
            :total="listTotal"
            :show-size-changer="false"
            size="small"
            @change="onPageChange"
          />
        </div>
      </div>
    </DetailModal>
  </div>
</template>

<style scoped>
/* ===== 卡片内按天分布横条 ===== */
.appt-days {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  align-items: stretch;
}

.appt-day {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
  min-width: 52px;
  padding: 8px 6px;
  border: 1px solid hsl(var(--border) / 0.6);
  border-radius: 10px;
  cursor: pointer;
  transition:
    border-color 0.15s ease,
    background 0.15s ease;
}

.appt-day:hover,
.appt-day:focus-visible {
  border-color: hsl(var(--primary) / 0.4);
  background: hsl(var(--primary) / 0.05);
  outline: none;
}

/* 有预约的天：主色轻着色突出 */
.appt-day--active {
  background: hsl(var(--primary) / 0.06);
  border-color: hsl(var(--primary) / 0.25);
}

.appt-day__label {
  font-size: 11px;
  color: hsl(var(--muted-foreground));
}

.appt-day__count {
  font-size: 16px;
  font-weight: 650;
  color: hsl(var(--foreground));
}

.appt-day--active .appt-day__count {
  color: hsl(var(--primary));
}

.appt-day__week {
  font-size: 10px;
  color: hsl(var(--muted-foreground) / 0.8);
}

/* ===== 明细弹窗 ===== */
.appt-detail {
  padding: 2px 2px 6px;
}

.appt-detail__filters {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.appt-pill {
  padding: 3px 10px;
  border: 1px solid hsl(var(--border));
  border-radius: 999px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
  cursor: pointer;
  transition:
    color 0.15s ease,
    border-color 0.15s ease,
    background 0.15s ease;
}

.appt-pill:hover {
  color: hsl(var(--primary));
  border-color: hsl(var(--primary) / 0.4);
}

.appt-pill--active {
  color: hsl(var(--primary));
  background: hsl(var(--primary) / 0.08);
  border-color: hsl(var(--primary) / 0.4);
}

.appt-detail__list {
  margin: 0;
  padding: 0;
  list-style: none;
  max-height: 48vh;
  overflow-y: auto;
}

.appt-row {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 10px 6px;
}

.appt-row + .appt-row {
  border-top: 1px solid hsl(var(--border) / 0.5);
}

.appt-row__date {
  display: flex;
  flex-direction: column;
  gap: 1px;
  align-items: center;
  min-width: 78px;
  flex-shrink: 0;
}

.appt-row__day {
  font-size: 13px;
  font-weight: 600;
  color: hsl(var(--foreground));
}

.appt-row__week {
  font-size: 11px;
  color: hsl(var(--muted-foreground));
}

.appt-row__main {
  flex: 1;
  min-width: 0;
}

.appt-row__line1 {
  display: flex;
  gap: 8px;
  align-items: center;
  min-width: 0;
}

.appt-row__patient {
  font-size: 13px;
  font-weight: 550;
  color: hsl(var(--foreground));
}

.appt-row__slot {
  font-size: 12px;
  color: hsl(var(--primary));
}

.appt-row__line2 {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 2px;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}

.appt-detail__pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
