<template>
  <div class="doctor-order-container">
    <el-card>
      <template #header>
        <div class="header-actions">
          <span class="title">门诊医嘱</span>
          <el-button type="primary" @click="handleAddOrder" data-cy="add-order-btn">新增医嘱</el-button>
        </div>
      </template>

      <el-table
        :data="orderList"
        border
        stripe
        style="width: 100%"
        data-cy="order-table"
      >
        <el-table-column prop="orderName" label="项目名称" width="200" />
        <el-table-column label="总量" width="150" align="center">
          <template #default="{ row }" data-cy="total-quantity-cell">
            <!-- 修复 Bug #561：前端展示增加空值防御，避免拼接出 "1 null" -->
            {{ row.totalQuantity }} {{ row.totalUnit || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <OrderDialog ref="orderDialogRef" @submit="fetchOrders" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import OrderDialog from './components/OrderDialog.vue'
import { getOrdersByPatient } from '@/api/order'

const orderList = ref<any[]>([])
const orderDialogRef = ref()

const fetchOrders = async () => {
  try {
    const res = await getOrdersByPatient(1001) // 示例患者ID
    orderList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取医嘱列表失败')
  }
}

const handleAddOrder = () => {
  orderDialogRef.value?.open()
}

const handleEdit = (row: any) => {
  ElMessage.info('编辑功能开发中')
}

const handleDelete = (row: any) => {
  ElMessage.info('删除功能开发中')
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.doctor-order-container {
  padding: 20px;
}
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
</style>
