<script setup>
import { computed, ref } from 'vue';
import { Card, Button, Tag, message } from 'ant-design-vue';
import { usePrescriptionStore } from '#/store/prescription';

const props = defineProps({
  content: {
    type: Object,
    required: true,
  },
  registerId: {
    type: [Number, String],
    default: null,
  },
});

const emit = defineEmits(['view-detail', 'import-success']);

const prescriptionStore = usePrescriptionStore();
const importing = ref(false);

// 解析转接方数据
const transferInfo = computed(() => {
  if (typeof props.content === 'string') {
    try {
      return JSON.parse(props.content);
    } catch {
      return {};
    }
  }
  return props.content;
});

// 解析处方内容（从content字段，后端已解析为对象）
const prescriptionContent = computed(() => {
  if (!transferInfo.value) return null;

  // 如果已经有解析好的prescription字段，直接使用
  if (transferInfo.value.prescription && transferInfo.value.prescription.content) {
    return {
      clinical_diagnose: transferInfo.value.prescription.clinical_diagnose || '',
      doctor_order: transferInfo.value.prescription.doctor_order || '',
      content: transferInfo.value.prescription.content || [],
    };
  }

  // 从content字段获取（后端已解析为对象）
  const content = transferInfo.value.content;
  if (!content) return null;

  // 构建药品列表
  let drugList = [];

  // 如果content是对象，检查repice字段
  if (typeof content === 'object' && !Array.isArray(content)) {
    // 从repice数组中提取药品
    if (content.repice && Array.isArray(content.repice)) {
      for (const recipe of content.repice) {
        if (recipe.content) {
          // recipe.content可能是已解析的数组，也可能是JSON字符串
          let recipeContent = recipe.content;
          if (typeof recipeContent === 'string') {
            try {
              recipeContent = JSON.parse(recipeContent);
            } catch {
              recipeContent = [];
            }
          }

          // 如果recipeContent是数组，合并到drugList
          if (Array.isArray(recipeContent)) {
            drugList = drugList.concat(recipeContent);
          }
        }
      }
    }

    return {
      clinical_diagnose: content.clinical_diagnose || transferInfo.value.original_prescription?.clinical_diagnose || '',
      doctor_order: content.doctor_order || transferInfo.value.original_prescription?.doctor_order || '',
      content: drugList,
    };
  } else if (Array.isArray(content)) {
    // 如果content直接是数组，说明是药品列表
    return {
      clinical_diagnose: transferInfo.value.original_prescription?.clinical_diagnose || '',
      doctor_order: transferInfo.value.original_prescription?.doctor_order || '',
      content: content,
    };
  }

  return null;
});

// 转诊状态文本
const statusText = computed(() => {
  const status = transferInfo.value.status;
  const statusMap = {
    0: { text: '待确认', color: 'orange' },
    1: { text: '已确认', color: 'blue' },
    2: { text: '已导入', color: 'green' },
    3: { text: '已取消', color: 'red' },
  };
  return statusMap[status] || { text: '未知', color: 'default' };
});

// 查看详情
const handleViewDetail = () => {
  emit('view-detail', transferInfo.value);
};

// 获取答案的样式类：是=绿色，否=红色，其他=黄色
const getAnswerClass = (answer) => {
  if (answer === '是') {
    return 'answer-yes';
  } else if (answer === '否') {
    return 'answer-no';
  } else {
    return 'answer-other';
  }
};

// 获取答案的图标
const getAnswerIcon = (answer) => {
  if (answer === '是') {
    return 'fas fa-check-circle';
  } else if (answer === '否') {
    return 'fas fa-times-circle';
  } else {
    return 'fas fa-question-circle';
  }
};

// 将转接方药品数据转换成addProducts需要的格式
const convertDrugDataForImport = (drug) => {
  // addProducts期望的数据结构：
  // {
  //   id: ...,
  //   drug: {
  //     id: ...,
  //     drug_name: ...,
  //     number: ...,
  //     time_id: ...,
  //     type_id: ...,
  //     frequency_id: ...,
  //     unit_id: ...,
  //     way_id: ...,
  //     image: ...,
  //     instruction: ...,
  //     type: ...,
  //   },
  //   price: ...,
  // }

  // 转接方的药品数据结构：
  // {
  //   id: ...,
  //   drug_id: ...,
  //   name: ...,
  //   number: ...,
  //   price: ...,
  //   unit: {...},
  //   use_unit: {...},
  //   ...
  // }

  return {
    id: drug.id || drug.drug_id || 0,
    drug: {
      id: drug.drug_id || drug.id || 0,
      drug_name: drug.name || drug.drug_name || '',
      number: drug.number || 1,
      time_id: drug.time_id || drug.use_num?.id || 0,
      type_id: drug.type_id || drug.use_type?.id || 0,
      frequency_id: drug.frequency_id || drug.use_frequency?.id || 0,
      unit_id: drug.unit_id || drug.unit?.id || drug.use_unit?.id || 0,
      way_id: drug.way_id || drug.use_way?.id || 0,
      image: drug.image || '',
      instruction: drug.instruction || '',
      type: drug.type || transferInfo.value?.prescription_type || 1,
    },
    price: parseFloat(drug.price) || 0,
  };
};

// 一键导入处方到在线问诊（从前端数据导入）
const handleImportToPrescription = async () => {
  if (!transferInfo.value?.id && !transferInfo.value?.transfer_id) {
    message.warning('转接方信息不完整');
    return;
  }

  // 优先使用props传入的registerId，如果没有则从transferInfo中获取
  const registerId = props.registerId || transferInfo.value.register_id;

  if (!registerId) {
    message.warning('挂号ID不能为空');
    return;
  }

  if (!prescriptionContent.value || !prescriptionContent.value.content || !Array.isArray(prescriptionContent.value.content)) {
    message.warning('处方内容格式错误，无法导入');
    return;
  }

  importing.value = true;
  try {
    // 确保处方store已初始化（使用正确的registerId）
    if (!prescriptionStore.currentRegisterId || prescriptionStore.currentRegisterId !== registerId) {
      prescriptionStore.initializePrescription(registerId, false);
    }

    // 先将处方类型设置为中药（1）
    prescriptionStore.changeCategory(1);

    // 直接使用前端已获取的数据进行导入
    const drugList = prescriptionContent.value.content;

    if (!drugList || drugList.length === 0) {
      message.warning('处方中没有药品信息');
      return;
    }

    // 导入药品（需要转换数据格式）
    let addedCount = 0;
    for (const drug of drugList) {
      // 转换数据格式
      const convertedDrugData = convertDrugDataForImport(drug);
      const success = prescriptionStore.addProducts(convertedDrugData);
      if (success) {
        addedCount++;
      }
    }

    // 导入诊断和医嘱
    if (prescriptionContent.value.clinical_diagnose) {
      prescriptionStore.diagnosis = prescriptionContent.value.clinical_diagnose;
    }
    if (prescriptionContent.value.doctor_order) {
      prescriptionStore.medicalAdvice = prescriptionContent.value.doctor_order;
    }

    if (addedCount > 0) {
      message.success(`已成功导入 ${addedCount} 个药品到处方单`);
      // 构建处方数据对象，用于触发事件
      const prescriptionData = {
        content: drugList,
        clinical_diagnose: prescriptionContent.value.clinical_diagnose,
        doctor_order: prescriptionContent.value.doctor_order,
        register_id: registerId,
      };
      // 触发事件，通知父组件打开处方模态框
      emit('import-success', prescriptionData);
    } else {
      message.warning('所有药品已在处方中');
    }
  } catch (error) {
    console.error('导入转接方处方失败:', error);
    message.error('导入转接方处方失败，请重试');
  } finally {
    importing.value = false;
  }
};
</script>

<template>
  <Card class="transfer-prescription-message-card" :bordered="true" style="max-width: 400px">
    <!-- 卡片头部 -->
    <div class="card-header">
      <div class="header-icon">
        <i class="fas fa-exchange-alt"></i>
      </div>
      <div class="header-title">转接方</div>
      <Tag :color="statusText.color" class="status-tag">
        {{ statusText.text }}
      </Tag>
    </div>

    <!-- 卡片内容 -->
    <div class="card-body">
      <!-- 转诊诊所信息 -->
      <div v-if="transferInfo.transfer_store" class="info-row">
        <div class="info-label">转诊诊所：</div>
        <div class="info-value">{{ transferInfo.transfer_store.name || '未知诊所' }}</div>
      </div>

      <!-- 委托诊所信息 -->
      <div v-if="transferInfo.delegate_store" class="info-row">
        <div class="info-label">委托诊所：</div>
        <div class="info-value">{{ transferInfo.delegate_store.name || '未知诊所' }}</div>
      </div>

      <!-- 处方编号 -->
      <div v-if="transferInfo.prescription_no" class="info-row">
        <div class="info-label">处方编号：</div>
        <div class="info-value">{{ transferInfo.prescription_no }}</div>
      </div>

      <!-- 转诊时间 -->
      <div v-if="transferInfo.transfer_time" class="info-row">
        <div class="info-label">转诊时间：</div>
        <div class="info-value">{{ transferInfo.transfer_time }}</div>
      </div>

      <!-- 咨询问题和答案 -->
      <div v-if="transferInfo.questions && transferInfo.questions.length > 0" class="questions-section">
        <div class="section-title">
          <i class="fas fa-question-circle"></i>
          <span>咨询问题</span>
        </div>
        <div v-for="(qa, index) in transferInfo.questions" :key="index" class="question-item">
          <div class="question-text">
            <span class="question-number">{{ index + 1 }}.</span>
            <span>{{ qa.question }}</span>
          </div>
          <div class="answer-text" :class="getAnswerClass(qa.answer)">
            <i :class="getAnswerIcon(qa.answer)"></i>
            <span>{{ qa.answer }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 卡片底部操作 -->
    <div class="card-footer">
      <Button
        type="primary"
        @click="handleViewDetail"
        class="view-btn"
      >
        查看详情
      </Button>
<!--      <Button-->
<!--        v-if="transferInfo.status !== 3 && transferInfo.status !== 2"-->
<!--        type="primary"-->
<!--        size="small"-->
<!--        :loading="importing"-->
<!--        @click="handleImportToPrescription"-->
<!--        class="import-btn"-->
<!--      >-->
<!--        <i class="fas fa-download mr-1"></i>-->
<!--        导入处方-->
<!--      </Button>-->
<!--      <Button-->
<!--        v-else-if="transferInfo.status === 2"-->
<!--        type="default"-->
<!--        size="small"-->
<!--        disabled-->
<!--        class="import-btn"-->
<!--      >-->
<!--        已导入-->
<!--      </Button>-->
    </div>
  </Card>
</template>

<style scoped>
.transfer-prescription-message-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  overflow: hidden;
}

.transfer-prescription-message-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
  color: white;
}

.header-icon {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.header-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.status-tag {
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* 卡片内容 */
.card-body {
  padding: 16px;
}

.info-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.6;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #666;
  font-weight: 500;
  min-width: 80px;
  flex-shrink: 0;
}

.dark .info-label {
  color: #94a3b8;
}

.info-value {
  color: #1e293b;
  flex: 1;
  word-break: break-word;
}

.dark .info-value {
  color: #e2e8f0;
}

/* 卡片底部 */
.card-footer {
  padding: 12px 16px;
  background: #f5f5f5;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.dark .card-footer {
  background: #1e293b;
  border-top-color: #374151;
}

.view-btn,
.import-btn {
  width: 100%;
  font-size: 13px;
  padding: 4px 12px;
  height: auto;
}

.import-btn {
  background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
  border: none;
  color: white;
}

.import-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #ea580c 0%, #dc2626 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(249, 115, 22, 0.3);
}

/* 暗黑模式适配 */
.dark .transfer-prescription-message-card {
  background: #1e293b;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dark .transfer-prescription-message-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

/* 咨询问题区域 */
.questions-section {
  margin-top: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 10px;
}

.section-title i {
  color: #0A84FF;
  font-size: 14px;
}

.question-item {
  background: white;
  padding: 10px 12px;
  border-radius: 6px;
  margin-bottom: 8px;
  border: 1px solid #e2e8f0;
}

.question-item:last-child {
  margin-bottom: 0;
}

.question-text {
  font-size: 13px;
  color: #334155;
  line-height: 1.5;
  margin-bottom: 6px;
}

.question-number {
  font-weight: 600;
  color: #0A84FF;
  margin-right: 4px;
}

.answer-text {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 10px;
  border-radius: 4px;
  width: fit-content;
}

.answer-yes {
  background: #dcfce7;
  color: #16a34a;
}

.answer-yes i {
  color: #16a34a;
}

.answer-no {
  background: #fee2e2;
  color: #dc2626;
}

.answer-no i {
  color: #dc2626;
}

.answer-other {
  background: #fef3c7;
  color: #d97706;
}

.answer-other i {
  color: #d97706;
}

.dark .questions-section {
  background: #1e293b;
  border-color: #334155;
}

.dark .question-item {
  background: #0f172a;
  border-color: #334155;
}

.dark .section-title {
  color: #e2e8f0;
}
</style>
