<template>
  <view :class="['page-scroll', elderClass]">
    <view class="page-content">
      <text class="page-title">随访任务</text>

      <!-- Tab filter -->
      <view class="tabs">
        <view
          v-for="tab in TABS" :key="tab.key"
          :class="['tab', activeTab === tab.key ? 'active' : '']"
          @tap="handleTabChange(tab.key)"
        >
          <text :class="['tab-text', activeTab === tab.key ? 'active' : '']">{{ tab.label }}</text>
        </view>
      </view>

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

      <!-- Empty -->
      <EmptyState v-else-if="tasks.length === 0" icon="📋" title="暂无随访任务" />

      <!-- Task list -->
      <scroll-view v-else scroll-y class="list-scroll" @scrolltolower="loadMore">
        <view
          v-for="item in tasks" :key="item.id"
          class="task-card"
          @tap="goDetail(item.id)"
        >
          <view class="card-header">
            <view class="type-badge" :style="getTypeStyle(item.follow_up_type)">
              <text class="type-text">{{ getTypeLabel(item.follow_up_type) }}</text>
            </view>
            <text :class="['status-tag', item.status]" :style="getStatusInlineStyle(item.status)">
              {{ getStatusLabel(item.status) }}
            </text>
          </view>

          <text class="patient-name">{{ item.patient_name || '未知患者' }}</text>

          <view class="card-footer">
            <text class="planned-date">计划日期：{{ item.planned_date }}</text>
          </view>
        </view>

        <Loading v-if="loading" text="加载中..." />
        <view v-if="!loading && tasks.length >= total && total > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

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

const TABS = [
  { key: '', label: '全部' },
  { key: 'pending', label: '待处理' },
  { key: 'in_progress', label: '进行中' },
  { key: 'completed', label: '已完成' },
  { key: 'overdue', label: '已逾期' },
]

const TYPE_MAP: Record<string, { label: string; bg: string; color: string }> = {
  phone: { label: '电话', bg: '#E8F0E8', color: '#5B7A5E' },
  visit: { label: '门诊', bg: '#F0DDD4', color: '#C4623A' },
  online: { label: '线上', bg: '#E0F0FF', color: '#3B82B8' },
  home: { label: '家访', bg: '#FFF3E0', color: '#C4873A' },
}

const { elderClass } = useElderClass()
const tasks = ref<doctorApi.FollowUpTask[]>([])
const total = ref(0)
const page = ref(1)
const activeTab = ref('')
const loading = ref(false)
let patientId = ''
let loadingGuard = false

function getTypeLabel(type: string): string {
  return TYPE_MAP[type]?.label || type
}

function getTypeStyle(type: string): Record<string, string> {
  const info = TYPE_MAP[type]
  if (!info) return { background: '#F1F5F9', color: '#78716C' }
  return { background: info.bg, color: info.color }
}

async function fetchTasks(pageNum: number, status: string, isRefresh = false) {
  if (loadingGuard) return
  loadingGuard = true
  loading.value = true
  try {
    const params: Record<string, unknown> = { page: pageNum, page_size: 20 }
    if (status) params.status = status
    if (patientId) params.patient_id = patientId
    const res = await doctorApi.listFollowUpTasks(params as Parameters<typeof doctorApi.listFollowUpTasks>[0])
    const list = res.data || []
    tasks.value = isRefresh ? list : [...tasks.value, ...list]
    total.value = res.total
    page.value = pageNum
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loadingGuard = false
    loading.value = false
  }
}

function handleTabChange(key: string) {
  activeTab.value = key
  fetchTasks(1, key, true)
}

function loadMore() {
  if (!loading.value && tasks.value.length < total.value) {
    fetchTasks(page.value + 1, activeTab.value)
  }
}

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

onLoad((query) => {
  patientId = query?.patientId || ''
  fetchTasks(1, '', true)
})

onPullDownRefresh(() => {
  fetchTasks(1, activeTab.value, true).finally(() => uni.stopPullDownRefresh())
})
</script>

<style lang="scss" scoped>
.page-scroll { min-height: 100vh; background: $bg; }
.page-content { padding: 28px 0 120px; }
.page-title { @include section-title; margin-left: 24px; }

.tabs {
  display: flex;
  padding: 0 24px 16px;
  gap: 8px;
  flex-wrap: wrap;
}

.tab {
  padding: 6px 16px;
  min-height: $touch-min;
  display: flex;
  align-items: center;
  border-radius: 20px;
  background: rgba(0, 0, 0, 0.04);
}

.tab.active { background: $pri; }

.tab-text {
  font-size: var(--tk-font-cap);
  color: $tx2;
}

.tab-text.active { color: $card; }

.list-scroll { height: calc(100vh - 160px); }

.task-card {
  background: $card;
  border-radius: $r;
  padding: 20px 24px;
  margin: 0 24px 16px;
  box-shadow: $shadow-sm;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.type-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: $r-xs;
}

.type-text {
  font-size: var(--tk-font-cap);
  font-weight: 500;
}

.status-tag {
  @include status-inline;
}

.patient-name {
  display: block;
  font-size: var(--tk-font-body);
  font-weight: 600;
  color: $tx;
  margin-bottom: 8px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.planned-date {
  font-size: var(--tk-font-cap);
  color: $tx3;
}

.no-more { @include flex-center; padding: 20px; }
.no-more-text { font-size: var(--tk-font-cap); color: $tx3; }
</style>
