<script setup>
import { ref, watch } from 'vue';
import { Descriptions, Button, Empty } from 'ant-design-vue';
import { getPatientDetail, reception } from '../api/index.ts';
import { message } from 'ant-design-vue';
import { sendMessage } from '#/views/business/chat/utils/request';
import { useUserStore } from '#/views/business/chat/stores/user';
import { getTransferPrescriptionByRegisterApi } from '#/views/business/chat/api/transferPrescription';
import TransferPrescriptionCard from '#/views/doctor/online-consultation/components/TransferPrescriptionCard.vue';
import { usePrescriptionStore } from '#/store/prescription';

const userStore = useUserStore();
const prescriptionStore = usePrescriptionStore();

const props = defineProps({
  patient: {
    type: Object,
    default: null
  },
  doctorId: {
    type: String,
    default: '39' // 改为39，与后端保持一致（虽然不再使用，但保持一致性）
  }
});

const emit = defineEmits(['reception-success', 'enter-chat', 'refresh-list', 'transfer-import-success']);

const patientDetail = ref(null);
const loading = ref(false);
const receptionLoading = ref(false);
const transferPrescription = ref(null);
const loadingTransfer = ref(false);

// 获取患者详情
const fetchPatientDetail = async () => {
  // 至少需要 room_id 或 register_id 其中之一
  if (!props.patient || (!props.patient.room_id && !props.patient.register_id)) {
    patientDetail.value = null;
    return;
  }

  loading.value = true;
  try {
    // 如果患者数据中有register_id，传递它来查询对应的就诊记录
    let registerId;
    if (props.patient.register_id) {
      const id = Number(props.patient.register_id);
      if (!isNaN(id) && id > 0) {
        registerId = id;
      }
    }
    
    // 支持只有 register_id 没有 room_id 的情况
    const res = await getPatientDetail(props.patient.room_id || '', registerId);
    // 确保正确解析返回数据
    const data = res?.result || res?.data || res || null;
    patientDetail.value = data;
    
    // 检查是否有转诊挂号
    if (data?.register_order?.is_from_transfer === 1 && registerId) {
      await fetchTransferPrescription(registerId);
    } else {
      transferPrescription.value = null;
    }
  } catch (error) {
    console.error('获取患者详情失败:', error);
    message.error('获取患者详情失败，请重试');
    patientDetail.value = null;
  } finally {
    loading.value = false;
  }
};

// 接诊
const handleReception = async () => {
  if (!props.patient) {
    message.error('患者信息不存在');
    return;
  }
  if (!props.patient.register_id) {
    message.error('缺少挂号ID');
    return;
  }

  receptionLoading.value = true;
  try {
    // 传递挂号ID
    const res = await reception(props.patient.register_id);
    
    // res 已经是 data.result 的内容，无需判断 code（请求封装会自动判断，失败会抛出异常）
    message.success('接诊成功');
    const receptionResult = {
      ...props.patient,
      register_id: res.register_id || props.patient.register_id,
      status: 2, // 接诊中
    };
    emit('reception-success', receptionResult);
    emit('refresh-list'); // 通知父组件刷新列表
    await fetchPatientDetail();
  } catch (error) {
    console.error('接诊失败:', error);
    message.error('接诊失败，请重试');
  } finally {
    receptionLoading.value = false;
  }
};

// 获取转诊信息
const fetchTransferPrescription = async (registerId) => {
  if (!registerId) return;
  
  loadingTransfer.value = true;
  try {
    const res = await getTransferPrescriptionByRegisterApi(registerId);
    const data = res?.result || res?.data || res;
    if (data && data.id) {
      transferPrescription.value = data;
    } else {
      transferPrescription.value = null;
    }
  } catch (error) {
    console.error('获取转诊信息失败:', error);
    transferPrescription.value = null;
  } finally {
    loadingTransfer.value = false;
  }
};

// 处理转诊导入成功
const handleTransferImportSuccess = (prescriptionData) => {
  // 触发打开处方模态框的事件
  emit('transfer-import-success', prescriptionData);
};

// 获取性别文本
const getSexText = (sex) => {
  if (sex === 1) return '男';
  if (sex === 2) return '女';
  return '未填写';
};

// 进入聊天
const handleEnterChat = () => {
  if (!props.patient) {
    message.warning('患者信息不存在');
    return;
  }
  if (!props.patient.room_id) {
    message.warning('患者尚未创建聊天房间，请先接诊');
    return;
  }
  emit('enter-chat', props.patient);
};

// 监听患者变化
watch(
  () => props.patient,
  (newPatient) => {
    if (newPatient) {
      fetchPatientDetail();
    } else {
      patientDetail.value = null;
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="patient-info-panel bg-white dark:bg-gray-900">
    <div v-if="loading" class="loading-state">
      <text>加载中...</text>
    </div>

    <div v-else-if="!patientDetail && !patient" class="empty-state">
      <Empty description="请选择患者" />
    </div>

    <div v-else-if="patientDetail" class="patient-content">
      <!-- 患者信息头部：标题和进入聊天按钮 -->
      <div class="patient-header">
        <h2 class="patient-title">患者信息</h2>
        <Button
          v-if="patient && patient.room_id"
          type="primary"
          @click="handleEnterChat"
          class="enter-chat-btn"
        >
          进入聊天
        </Button>
      </div>
      
      <!-- 患者基本信息 -->
      <Descriptions
        :column="{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }"
        bordered
        class="patient-descriptions"
      >
        <Descriptions.Item label="患者姓名">
          {{ patientDetail.user_patient?.name || patientDetail.user?.nick_name || '未知' }}
        </Descriptions.Item>
        <Descriptions.Item label="患者年龄">
          {{ patientDetail.user_patient?.age || 0 }}岁
        </Descriptions.Item>
        <Descriptions.Item label="患者性别">
          {{ getSexText(patientDetail.user_patient?.sex) }}
        </Descriptions.Item>
        <Descriptions.Item label="手机号">
          {{ patientDetail.user_patient?.mobile || patientDetail.user?.mobile || '未填写' }}
        </Descriptions.Item>
        <Descriptions.Item v-if="patientDetail.register_order?.order_no" label="订单号">
          {{ patientDetail.register_order.order_no }}
        </Descriptions.Item>
      </Descriptions>

      <!-- 转诊处方卡片 -->
      <div v-if="transferPrescription" class="transfer-section">
        <TransferPrescriptionCard
          :transfer-data="transferPrescription"
          :register-id="patient?.register_id || patientDetail?.register_order?.id"
          @import-success="handleTransferImportSuccess"
        />
      </div>

      <!-- 就诊记录 -->
      <div v-if="patientDetail.register_infos && patientDetail.register_infos.length > 0" class="register-info-section">
        <h3 class="section-title text-gray-900 dark:text-gray-100 border-b-2 border-blue-600 dark:border-blue-400">就诊记录</h3>
        <div class="register-info-list">
          <div
            v-for="info in patientDetail.register_infos"
            :key="info.id"
            class="register-info-item bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-600"
          >
            <div v-if="info.illnessInfo" class="illness-info">
              <strong>症状：</strong>{{ info.illnessInfo }}
            </div>
            <div v-if="info.drug" class="drug-info">
              <strong>药品：</strong>{{ info.drug.name }}
            </div>
            <div class="meta-info">
              <span>就诊过：{{ info.has_visited ? '是' : '否' }}</span>
              <span style="margin-left: 16px;">使用过药品：{{ info.has_used_drug ? '是' : '否' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 接诊按钮 -->
      <div v-if="!patientDetail.is_recepted" class="action-section border-t border-gray-200 dark:border-gray-700">
        <Button
          type="primary"
          :loading="receptionLoading"
          size="large"
          block
          @click="handleReception"
        >
          接诊
        </Button>
      </div>

      <div v-else class="recepted-info bg-green-50 dark:bg-green-900/20">
        <text class="recepted-text text-green-600 dark:text-green-400">已接诊</text>
      </div>
    </div>
  </div>
</template>

<style scoped>
.patient-info-panel {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.loading-state,
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.patient-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

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

.patient-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.enter-chat-btn {
  flex-shrink: 0;
}

.patient-descriptions {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-bottom: 8px;
}

.transfer-section {
  margin-top: 24px;
}

.register-info-section {
  margin-top: 24px;
}

.register-info-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.register-info-item {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid;
}

.illness-info,
.drug-info {
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.6;
}

.illness-info strong,
.drug-info strong {
  margin-right: 8px;
}

.meta-info {
  margin-top: 8px;
  font-size: 12px;
}

.action-section {
  margin-top: 24px;
  padding-top: 24px;
}

.recepted-info {
  margin-top: 24px;
  padding: 16px;
  text-align: center;
  border-radius: 8px;
}

.recepted-text {
  font-size: 16px;
  font-weight: 500;
}

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

.dark .illness-info,
.dark .drug-info {
  color: #cbd5e1;
}

.dark .illness-info strong,
.dark .drug-info strong {
  color: #e2e8f0;
}

.dark .meta-info {
  color: #94a3b8;
}
</style>
