<template>
  <div class="pending-records-container">
    <el-card>
      <template #header>
        <div class="header">
          <span>待写病历</span>
          <el-button type="primary" @click="refreshData" :loading="loading">刷新</el-button>
        </div>
      </template>

      <!-- 修复 #562：v-loading 绑定 loading 状态，避免请求异常时加载遮罩不消失 -->
      <el-table v-loading="loading" :data="recordList" style="width: 100%" empty-text="暂无待写病历">
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="visitDate" label="就诊日期" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleWrite(row)">书写</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="fetchRecords"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getPendingRecords } from '@/api/outpatient/medicalRecord';

const recordList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);

// 修复 #562：统一加载状态管理，增加 finally 确保遮罩必关，避免“一直加载”假死
const fetchRecords = async () => {
  loading.value = true;
  try {
    const res = await getPendingRecords({
      doctorId: 1, // 实际应从用户上下文/Store获取
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    if (res.code === 200) {
      recordList.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.warning(res.msg || '加载失败');
    }
  } catch (error) {
    ElMessage.error('网络异常，请检查连接后重试');
    console.error('Bug #562 fetch error:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  currentPage.value = 1;
  fetchRecords();
};

const handleWrite = (row) => {
  // 路由跳转至病历书写页
  console.log('Navigate to write record:', row.id);
};

onMounted(() => {
  fetchRecords();
});
</script>

<style scoped>
.pending-records-container { padding: 16px; }
.header { display: flex; justify-content: space-between; align-items: center; }
.pagination { margin-top: 16px; justify-content: flex-end; }
</style>
