<script setup>
import { ref, watch, onMounted } from 'vue';
import { RadioButton, RadioGroup, Button, message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { getPatientList } from '../api/index.ts';
import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { useChatStore } from '#/views/business/chat/stores/chat';

const chatStore = useChatStore();

const props = defineProps({
  doctorId: {
    type: String,
    default: '32'
  }
});

const emit = defineEmits(['select-patient']);

const listType = ref(1); // 1=当前，2=历史
const patients = ref([]);
const selectedPatientId = ref(null);
const loading = ref(false);

// 获取患者列表
const fetchPatientList = async () => {
  loading.value = true;
  try {
    const res = await getPatientList(listType.value);
    // 确保正确解析返回数据：jok函数返回格式为 { code: 0, message: "...", result: [...] }
    const data = res?.result || res?.data || res || [];
    patients.value = Array.isArray(data) ? data : [];
  } catch (error) {
    console.error('获取患者列表失败:', error);
    patients.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取患者的唯一标识符
const getPatientUniqueId = (patient) => {
  if (!patient) return null;
  return patient.register_id || patient.room_id || patient.id || null;
};

// 切换列表类型
const handleTypeChange = () => {
  selectedPatientId.value = null;
  fetchPatientList();
};

// 选择患者
const selectPatient = (patient) => {
  selectedPatientId.value = getPatientUniqueId(patient);
  emit('select-patient', patient);
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待接诊',
    2: '接诊中',
    3: '已结束',
  };
  return statusMap[status] || '未知';
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    1: 'status-pending',
    2: 'status-consulting',
    3: 'status-ended',
  };
  return classMap[status] || '';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time * 1000 || time);
  const now = new Date();
  const diff = now - date;
  const minutes = Math.floor(diff / 60000);
  
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}小时前`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}天前`;
  return date.toLocaleDateString('zh-CN');
};

onMounted(() => {
  fetchPatientList();
  // 定时刷新列表（每10分钟）
  setInterval(fetchPatientList, 600000);
});

// 监听列表类型变化
watch(listType, handleTypeChange);

// 监听新挂号通知，自动刷新患者列表
watch(
  () => chatStore.newRegisterNotification,
  (newNotification) => {
    if (newNotification && listType.value === 1) {
      // 只在"当前"列表时自动刷新
      message.info('有新的挂号，正在刷新列表...');
      fetchPatientList();
    }
  },
  { deep: true }
);

// 暴露方法供父组件调用
defineExpose({
  fetchPatientList
});
</script>

<template>
  <div class="patient-list-container bg-white dark:bg-gray-900">
    <div class="list-header border-b border-gray-200 dark:border-gray-700">
      <div class="header-top">
        <RadioGroup v-model:value="listType" class="type-switch" @change="handleTypeChange">
          <RadioButton :value="1">当前</RadioButton>
          <RadioButton :value="2">历史</RadioButton>
        </RadioGroup>
        <Button 
          type="text" 
          :loading="loading"
          @click="fetchPatientList"
          class="refresh-btn"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </Button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <text>加载中...</text>
    </div>

    <div v-else-if="patients.length === 0" class="empty-state">
      <text>暂无患者</text>
    </div>

    <div v-else class="patient-list">
      <div
        v-for="(patient, index) in patients"
        :key="`patient-${getPatientUniqueId(patient) || index}`"
        :class="['patient-card', 'border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800', { 'active border-l-4 border-l-blue-600 bg-blue-50 dark:bg-blue-900/20': selectedPatientId === getPatientUniqueId(patient) }]"
        @click.stop="selectPatient(patient)"
      >
        <div class="patient-info">
          <h3 class="patient-name">
            {{ patient.user_patient?.name || patient.user?.nick_name || '未知患者' }}
          </h3>
          <p class="patient-phone">
            <SensitiveText
              :record="patient.user_patient"
              field="mobile"
              :fallback="{ record: patient.user, field: 'mobile' }"
              :show-eye="false"
            />
          </p>
          <p v-if="patient.order_no" class="order-no">订单号：{{ patient.order_no }}</p>
          <div class="patient-meta">
            <span :class="['status', getStatusClass(patient.status)]">
              {{ getStatusText(patient.status) }}
            </span>
            <span class="time text-gray-500 dark:text-gray-400">{{ formatTime(patient.last_message_time) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.patient-list-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 16px;
}

.header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.type-switch {
  flex: 1;
  display: flex;
}

.refresh-btn {
  flex-shrink: 0;
}

.type-switch :deep(.ant-radio-button-wrapper) {
  flex: 1;
  text-align: center;
}

.loading-state,
.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
}

.patient-list {
  flex: 1;
  overflow-y: auto;
}

.patient-card {
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.patient-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.patient-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.patient-phone {
  font-size: 14px;
  margin: 0;
}

.order-no {
  font-size: 12px;
  margin: 4px 0 0 0;
}

.patient-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.status {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fef0f0;
  color: #f56c6c;
}

.status-consulting {
  background: #f0f9eb;
  color: #67c23a;
}

.status-ended {
  background: #f4f4f5;
  color: #909399;
}

.time {
  font-size: 12px;
}

/* 暗色模式适配 */
.dark .patient-name {
  color: #e2e8f0;
}

.dark .patient-phone {
  color: #94a3b8;
}

.dark .order-no {
  color: #94a3b8;
}

.dark .status-pending {
  background: rgba(245, 108, 108, 0.2);
  color: #f87171;
}

.dark .status-consulting {
  background: rgba(103, 194, 58, 0.2);
  color: #4ade80;
}

.dark .status-ended {
  background: rgba(144, 147, 153, 0.2);
  color: #9ca3af;
}

.dark .loading-state,
.dark .empty-state {
  color: #94a3b8;
}
</style>
