<script setup>
import { ref, computed, watch } from 'vue';
import { Drawer, Descriptions, Button, Tag, message, Empty } from 'ant-design-vue';
import { usePrescriptionStore } from '#/store/prescription';
import { getTransferPrescriptionByRegisterApi } from '#/views/business/chat/api/transferPrescription';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  registerId: {
    type: [Number, String],
    default: null,
  },
});

const emit = defineEmits(['update:visible', 'import-success']);

const prescriptionStore = usePrescriptionStore();
const transferData = ref(null);
const loading = ref(false);
const importing = ref(false);

// 解析转诊数据
const transferInfo = computed(() => {
  if (!transferData.value) return null;
  if (typeof transferData.value === 'string') {
    try {
      return JSON.parse(transferData.value);
    } catch {
      return null;
    }
  }
  return transferData.value;
});

// 解析处方内容（从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(() => {
  if (!transferInfo.value) return { text: '未知', color: 'default' };
  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 fetchTransferPrescription = async () => {
  if (!props.registerId) {
    message.warning('挂号ID不能为空');
    return;
  }

  loading.value = true;
  try {
    const res = await getTransferPrescriptionByRegisterApi(props.registerId);
    const data = res?.result || res?.data || res;
    if (data && data.id) {
      transferData.value = data;
    } else {
      transferData.value = null;
      message.warning('未找到转接方信息');
    }
  } catch (error) {
    console.error('获取转接方信息失败:', error);
    message.error('获取转接方信息失败，请重试');
    transferData.value = null;
  } finally {
    loading.value = false;
  }
};

// 将转接方药品数据转换成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) {
    message.warning('转接方信息不完整');
    return;
  }

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

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

  importing.value = true;
  try {
    // 先将处方类型设置为中药（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: props.registerId,
      };
      // 触发事件，通知父组件打开处方模态框
      emit('import-success', prescriptionData);
      // 关闭抽屉
      emit('update:visible', false);
    } else {
      message.warning('所有药品已在处方中');
    }
  } catch (error) {
    console.error('导入转接方处方失败:', error);
    message.error('导入转接方处方失败，请重试');
  } finally {
    importing.value = false;
  }
};

// 关闭抽屉
const handleClose = () => {
  emit('update:visible', false);
};

// 监听visible变化，打开时获取数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal && props.registerId) {
      fetchTransferPrescription();
    } else {
      transferData.value = null;
    }
  },
  { immediate: true }
);
</script>

<template>
  <Drawer
    :open="visible"
    title="转接方查看"
    :width="600"
    @close="handleClose"
  >
    <div v-if="loading" class="loading-container">
      <text>加载中...</text>
    </div>

    <div v-else-if="!transferInfo" class="empty-container">
      <Empty description="未找到转接方信息" />
    </div>

    <div v-else class="transfer-prescription-drawer">
      <!-- 状态标签 -->
      <div class="status-section">
        <Tag :color="statusText.color" class="status-tag">
          {{ statusText.text }}
        </Tag>
      </div>

      <!-- 基本信息 -->
      <Descriptions
        :column="1"
        bordered
        class="info-descriptions"
        title="基本信息"
      >
        <Descriptions.Item v-if="transferInfo.transfer_store" label="转诊诊所">
          {{ transferInfo.transfer_store.name || '未知诊所' }}
        </Descriptions.Item>
        <Descriptions.Item v-if="transferInfo.delegate_store" label="委托诊所">
          {{ transferInfo.delegate_store.name || '未知诊所' }}
        </Descriptions.Item>
        <Descriptions.Item v-if="transferInfo.prescription_no" label="处方编号">
          {{ transferInfo.prescription_no }}
        </Descriptions.Item>
        <Descriptions.Item v-if="transferInfo.transfer_time" label="转诊时间">
          {{ transferInfo.transfer_time }}
        </Descriptions.Item>
        <Descriptions.Item v-if="transferInfo.transfer_reason" label="转诊原因">
          {{ transferInfo.transfer_reason }}
        </Descriptions.Item>
      </Descriptions>

      <!-- 处方内容 -->
      <div v-if="prescriptionContent" class="prescription-section">
        <h3 class="section-title">处方内容</h3>
        <div v-if="prescriptionContent.clinical_diagnose" class="prescription-item">
          <strong>临床诊断：</strong>
          <span>{{ prescriptionContent.clinical_diagnose }}</span>
        </div>
        <div v-if="prescriptionContent.doctor_order" class="prescription-item">
          <strong>医嘱：</strong>
          <span>{{ prescriptionContent.doctor_order }}</span>
        </div>
        <div v-if="prescriptionContent.content && prescriptionContent.content.length > 0" class="prescription-content">
          <strong>药品列表：</strong>
          <div class="drug-list">
            <div
              v-for="(drug, index) in prescriptionContent.content"
              :key="index"
              class="drug-item"
            >
              <span>{{ drug.drug_name || drug.name || '未知药品' }}</span>
              <span v-if="drug.number"> × {{ drug.number }}</span>
              <span v-if="drug.unit?.name || drug.unit"> {{ drug.unit?.name || drug.unit }}</span>
              <span v-if="drug.use_type?.name || drug.use_frequency?.name" class="drug-usage">
                （{{ [drug.use_type?.name, drug.use_frequency?.name, drug.use_num?.name].filter(Boolean).join('，') }}）
              </span>
            </div>
          </div>
        </div>
        <div v-else-if="prescriptionContent.content && prescriptionContent.content.length === 0" class="prescription-item">
          <span class="text-gray-400">暂无药品信息</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div v-if="transferInfo.status !== 3" class="action-section">
        <Button
          v-if="transferInfo.status !== 2"
          type="primary"
          :loading="importing"
          block
          size="large"
          @click="handleImportToPrescription"
        >
          <i class="fas fa-download mr-1"></i>
          导入到处方单
        </Button>
        <Button v-else type="default" block disabled>
          已导入
        </Button>
      </div>
    </div>
  </Drawer>
</template>

<style scoped>
.loading-container,
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.transfer-prescription-drawer {
  padding: 16px 0;
}

.status-section {
  margin-bottom: 24px;
  text-align: center;
}

.status-tag {
  font-size: 14px;
  font-weight: 500;
  padding: 6px 16px;
}

.info-descriptions {
  margin-bottom: 24px;
}

.prescription-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.dark .prescription-section {
  background: #1e293b;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.dark .section-title {
  color: #e2e8f0;
}

.prescription-item {
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.6;
}

.prescription-item strong {
  color: #666;
  margin-right: 8px;
}

.dark .prescription-item strong {
  color: #94a3b8;
}

.prescription-content {
  margin-top: 16px;
}

.drug-list {
  margin-top: 12px;
  padding-left: 20px;
}

.drug-item {
  padding: 8px 0;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
}

.dark .drug-item {
  border-bottom-color: #374151;
}

.drug-item:last-child {
  border-bottom: none;
}

.drug-usage {
  color: #666;
  font-size: 12px;
  margin-left: 8px;
}

.dark .drug-usage {
  color: #94a3b8;
}

.action-section {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.dark .action-section {
  border-top-color: #374151;
}
</style>
