<template>
  <div class="order-verification-container">
    <el-card shadow="never">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="待校对" name="pending" />
        <el-tab-pane label="已校对" name="verified" />
        <el-tab-pane label="已退回" name="returned" />
      </el-tabs>

      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%; margin-top: 16px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="patientName" label="患者姓名" width="120" />
        <el-table-column prop="drugName" label="药品/项目名称" min-width="180" />
        <el-table-column prop="dosage" label="剂量" width="100" />
        <el-table-column prop="executeStatus" label="执行状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.executeStatus === '已执行' ? 'success' : 'info'">
              {{ row.executeStatus || '未执行' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dispenseStatus" label="发药状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.dispenseStatus === '已发药' ? 'warning' : 'info'">
              {{ row.dispenseStatus || '未发药' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="医嘱状态" width="100" />
      </el-table>

      <div class="toolbar" style="margin-top: 16px; display: flex; justify-content: flex-end; gap: 12px;">
        <el-button
          type="primary"
          :disabled="isReturnDisabled"
          @click="handleReturn"
        >
          退回
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrders, returnOrder } from '@/api/nurse/order'

const activeTab = ref('verified')
const loading = ref(false)
const orderList = ref([])
const selectedOrders = ref([])

onMounted(() => {
  fetchOrders()
})

const handleTabChange = () => {
  fetchOrders()
}

const fetchOrders = async () => {
  loading.value = true
  try {
    const res = await getOrders({ status: activeTab.value })
    orderList.value = res.data || []
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (val) => {
  selectedOrders.value = val
}

// Bug #505 修复：计算退回按钮是否禁用
// 核心约束：已执行或已发药的药品医嘱不可直接退回
const isReturnDisabled = computed(() => {
  if (selectedOrders.value.length === 0) return true
  return selectedOrders.value.some(order => {
    return order.executeStatus === '已执行' || order.dispenseStatus === '已发药'
  })
})

const handleReturn = async () => {
  if (isReturnDisabled.value) return

  try {
    await ElMessageBox.confirm('确认退回选中的医嘱吗？', '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const ids = selectedOrders.value.map(o => o.id)
    await returnOrder(ids)
    ElMessage.success('退回成功')
    fetchOrders()
  } catch (err) {
    if (err !== 'cancel') {
      // 兜底拦截后端返回的业务异常提示
      ElMessage.error(err.message || '退回失败')
    }
  }
}
</script>

<style scoped>
.order-verification-container {
  padding: 16px;
}
</style>
