<template>
  <div class="report-container">
    <div class="report-section">
      <div class="report-title">
        <span>检查报告</span>
        <el-icon
          class="report-refresh-icon"
          :class="{ 'is-loading': loadingCheck }"
          @click="handleRefreshCheck"
        >
          <Refresh />
        </el-icon>
      </div>
      <div class="report-table-wrapper">
        <el-table
          v-loading="loadingCheck"
          :data="checkReportList"
          border
          size="small"
          height="100%"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="adviceName" label="报告名称" width="140" />
          <el-table-column prop="reportNo" label="报告号" width="140" />
          <el-table-column label="链接" min-width="140">
            <template #default="scope">
              <a
                v-if="scope.row.requestUrl"
                class="report-link"
                :href="scope.row.requestUrl"
                target="_blank"
                rel="noopener noreferrer"
              >
                查看报告
              </a>
              <span v-else class="report-link-disabled">暂无链接</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="report-section">
      <div class="report-title">
        <span>检验报告</span>
        <el-icon
          class="report-refresh-icon"
          :class="{ 'is-loading': loadingInspection }"
          @click="handleRefreshInspection"
        >
          <Refresh />
        </el-icon>
      </div>
      <div class="report-table-wrapper">
        <el-table
          v-loading="loadingInspection"
          :data="inspectionReportList"
          border
          size="small"
          height="100%"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="adviceName" label="报告名称" width="140" />
          <el-table-column prop="reportNo" label="报告号" width="140" />
          <el-table-column label="链接" min-width="140">
            <template #default="scope">
              <a
                v-if="scope.row.requestUrl"
                class="report-link"
                :href="scope.row.requestUrl"
                target="_blank"
                rel="noopener noreferrer"
              >
                查看报告
              </a>
              <span v-else class="report-link-disabled">暂无链接</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import {getCurrentInstance, ref, watch} from 'vue';
import {Refresh} from '@element-plus/icons-vue';
import {getProofResult, getTestResult} from './api';

const { proxy } = getCurrentInstance();
const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
  },
});

const checkReportList = ref([]);
const inspectionReportList = ref([]);
const loadingCheck = ref(false);
const loadingInspection = ref(false);

const fetchCheckReport = async () => {
  if (!props.patientInfo?.encounterId) return;
  const res = await getTestResult({ encounterId: props.patientInfo.encounterId });
  if (res.code === 200 && res.data) {
    const raw = res.data?.records || res.data;
    const list = Array.isArray(raw) ? raw : [raw];
    checkReportList.value = list.filter(Boolean).map((item) => ({
      reportNo: item.busNo,
      requestUrl: item.requestUrl,
      adviceName: item.adviceName,
      _raw: item,
    }));
  } else {
    checkReportList.value = [];
  }
};

const fetchInspectionReport = async () => {
  if (!props.patientInfo?.encounterId) return;
  const res = await getProofResult({ encounterId: props.patientInfo.encounterId });
  if (res.code === 200 && res.data) {
    const raw = res.data?.records || res.data;
    const list = Array.isArray(raw) ? raw : [raw];
    inspectionReportList.value = list.filter(Boolean).map((item) => ({
      reportNo: item.busNo,
      requestUrl: item.requestUrl,
      adviceName: item.adviceName,
      _raw: item,
    }));
  } else {
    inspectionReportList.value = [];
  }
};

const fetchAll = async () => {
  if (!props.patientInfo?.encounterId) {
    checkReportList.value = [];
    inspectionReportList.value = [];
    loadingCheck.value = false;
    loadingInspection.value = false;
    return;
  }
  loadingCheck.value = true;
  loadingInspection.value = true;
  
  // 独立处理，互不影响
  const runFetch = async (fn, loadingRef, name) => {
    try {
      await fn();
    } catch (e) {
      proxy.$modal?.msgError?.(`${name}查询失败: ${e.message || '未知错误'}`);
    } finally {
      loadingRef.value = false;
    }
  };

  runFetch(fetchCheckReport, loadingCheck, '检查报告');
  runFetch(fetchInspectionReport, loadingInspection, '检验报告');
};

const handleRefreshCheck = async () => {
  if (loadingCheck.value || !props.patientInfo?.encounterId) return;
  loadingCheck.value = true;
  try {
    await fetchCheckReport();
  } finally {
    loadingCheck.value = false;
  }
};

const handleRefreshInspection = async () => {
  if (loadingInspection.value || !props.patientInfo?.encounterId) return;
  loadingInspection.value = true;
  try {
    await fetchInspectionReport();
  } finally {
    loadingInspection.value = false;
  }
};

watch(
  () => props.patientInfo?.encounterId,
  (val) => {
    if (val) {
      fetchAll();
    } else {
      checkReportList.value = [];
      inspectionReportList.value = [];
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.report-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
  height: 100%;
}

.report-section {
  background: #fff;
  flex: 1;
  max-height: 55%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.report-title {
  font-weight: 600;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.report-table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;
}

.report-refresh-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.report-refresh-icon:hover {
  color: #409eff;
}

.report-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.report-link-disabled {
  color: #c0c4cc;
}
</style>
