<template>
  <scroll-view scroll-y :class="['consultation-page', elderClass]">
    <!-- Tab 筛选 -->
    <view class="tabs">
      <view
        v-for="t in TABS"
        :key="t.key"
        :class="['tab', activeTab === t.key ? 'tab--active' : '']"
        @tap="handleTabChange(t.key)"
      >
        <text>{{ t.label }}</text>
      </view>
    </view>

    <!-- 加载态 -->
    <Loading v-if="loading && sessions.length === 0" text="加载中..." />

    <!-- 空态 -->
    <EmptyState v-else-if="sessions.length === 0" icon="💬" title="暂无咨询会话" />

    <!-- 会话列表 -->
    <view v-else class="session-list">
      <view
        v-for="s in sessions"
        :key="s.id"
        class="session-card"
        @tap="goDetail(s.id)"
      >
        <view class="session-card__top">
          <text class="session-card__subject">{{ s.subject || '在线咨询' }}</text>
          <view class="session-card__status" :style="getStatusInlineStyle(s.status)">
            <text class="session-card__status-text">{{ getStatusLabel(s.status) }}</text>
          </view>
        </view>
        <view class="session-card__info">
          <text class="session-card__type">
            {{ s.consultation_type === 'text' ? '图文' : s.consultation_type === 'video' ? '视频' : '咨询' }}
          </text>
          <text class="session-card__time">{{ formatTime(s.last_message_at) }}</text>
        </view>
        <text v-if="s.last_message" class="session-card__preview">{{ s.last_message }}</text>
        <view v-if="(s.unread_count_doctor ?? 0) > 0" class="session-card__badge">
          <text class="session-card__badge-text">{{ s.unread_count_doctor }}</text>
        </view>
      </view>
    </view>

    <!-- 分页 -->
    <view v-if="total > 20" class="pagination">
      <text
        :class="['pagination__btn', page <= 1 ? 'disabled' : '']"
        @tap="page > 1 && (page = page - 1)"
      >上一页</text>
      <text class="pagination__info">{{ page }} / {{ totalPages }}</text>
      <text
        :class="['pagination__btn', page >= totalPages ? 'disabled' : '']"
        @tap="page < totalPages && (page = page + 1)"
      >下一页</text>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import * as doctorApi from '@/services/doctor'
import { useElderClass } from '@/composables/useElderClass'
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag'
import { formatDate } from '@/utils/date'
import Loading from '@/components/Loading.vue'
import EmptyState from '@/components/EmptyState.vue'

const TABS = [
  { key: '', label: '全部' },
  { key: 'active', label: '进行中' },
  { key: 'waiting', label: '等待中' },
  { key: 'closed', label: '已关闭' },
] as const

const { elderClass } = useElderClass()

const sessions = ref<doctorApi.ConsultationSession[]>([])
const activeTab = ref('')
const loading = ref(true)
const total = ref(0)
const page = ref(1)

const totalPages = computed(() => Math.ceil(total.value / 20))

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

function handleTabChange(key: string) {
  activeTab.value = key
  page.value = 1
}

function formatTime(dateStr?: string | null): string {
  if (!dateStr) return ''
  return formatDate(dateStr, 'MM-DD HH:mm')
}

async function loadSessions() {
  loading.value = true
  try {
    const res = await doctorApi.listSessions({
      page: page.value,
      page_size: 20,
      status: activeTab.value || undefined,
    })
    sessions.value = res.data || []
    total.value = res.total || 0
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

watch([page, activeTab], () => { loadSessions() })

onShow(() => {
  loadSessions()
})
</script>

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

.tabs {
  display: flex;
  background: $card;
  padding: 0 16px;
  border-bottom: 1px solid $bd;
}

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

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

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 30%;
      right: 30%;
      height: 4px;
      background: $pri;
      border-radius: $r-xs;
    }
  }
}

.session-list {
  padding: 20px 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

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

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

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

  &__subject {
    font-size: var(--tk-font-body-lg);
    font-weight: 600;
    color: $tx;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 16px;
  }

  &__status {
    display: inline-block;
    border-radius: 6px;
    padding: 2px 8px;
    flex-shrink: 0;
  }

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

  &__info {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 8px;
  }

  &__type {
    @include tag($pri-l, $pri);
  }

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

  &__preview {
    font-size: var(--tk-font-body);
    color: $tx2;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
  }

  &__badge {
    position: absolute;
    top: 20px;
    right: 20px;
    min-width: 36px;
    height: 36px;
    background: $dan;
    border-radius: $r-pill;
    @include flex-center;
    padding: 0 8px;
  }

  &__badge-text {
    @include serif-number;
    font-size: var(--tk-font-body);
    color: $card;
    font-weight: 600;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  padding: 24px;

  &__btn {
    font-size: var(--tk-font-body);
    color: $pri;
    padding: 12px 24px;

    &.disabled {
      color: $tx3;
    }
  }

  &__info {
    font-size: var(--tk-font-body-sm);
    color: $tx2;
  }
}
</style>
