<template>
  <div class="p-6 bg-grey-50 min-h-screen">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>处方管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="mt-4">
      <template #header>处方管理</template>
      <!-- 操作按钮 -->
      <div class="flex justify-end mb-4">
        <el-button type="primary" @click="showForm = true">新建处方</el-button>
      </div>
      <!-- 处方列表 -->
      <el-table :data="prescriptions" style="width: 100%" row-key="id">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="date" label="开具日期" />
        <el-table-column label="药品数量">
          <template #default="{ row }">
            {{ row.medications.length }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-space>
              <el-button size="small" @click="onEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="onDelete(row.id)">删除</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新建/编辑 弹窗 -->
      <el-dialog v-model="showForm" :title="editMode ? '编辑处方' : '新建处方'" width="600px" @close="onClose">
        <el-form ref="formRef" :model="form" label-position="top" :rules="rules">
          <el-form-item label="患者姓名" prop="patientName" required>
            <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
          </el-form-item>
          <el-form-item label="开具日期" prop="date" required>
            <el-date-picker v-model="form.date" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="药品列表" prop="medications" required>
            <div>
              <div v-for="(item, idx) in form.medications" :key="idx" class="flex items-center mb-2">
                <el-input v-model="item.name" placeholder="药品名称" style="width: 120px; margin-right: 8px;" />
                <el-input v-model="item.dosage" placeholder="用量" style="width: 80px; margin-right: 8px;" />
                <el-input v-model="item.frequency" placeholder="频次" style="width: 80px; margin-right: 8px;" />
                <el-input-number v-model="item.quantity" :min="1" style="width: 80px; margin-right: 8px;" />
                <el-button size="small" type="danger" @click="removeMedication(idx)">删除</el-button>
              </div>
              <el-button size="small" type="primary" link @click="addMedication">+ 添加药品</el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-space class="justify-end">
            <el-button @click="onClose">取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-space>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

interface Medication {
  name: string;
  dosage: string;
  frequency: string;
  quantity: number;
}
interface Prescription {
  id: number;
  patientName: string;
  date: string;
  medications: Medication[];
}

const prescriptions = ref<Prescription[]>([]);
const showForm = ref(false);
const editMode = ref(false);
const formRef = ref<any>(null);

const form = reactive<Prescription>({
  id: 0,
  patientName: '',
  date: '',
  medications: []
});

const rules = {
  patientName: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  medications: [
    {
      required: true,
      validator: (_: any, value: Medication[]) => value && value.length > 0,
      message: '请至少添加一种药品',
      trigger: 'change'
    }
  ]
};

onMounted(() => {
  prescriptions.value = [];
});

const addMedication = () => {
  form.medications.push({ name: '', dosage: '', frequency: '', quantity: 1 });
};

const removeMedication = (idx: number) => {
  form.medications.splice(idx, 1);
};

const onEdit = (row: Prescription) => {
  editMode.value = true;
  Object.assign(form, { ...row, medications: JSON.parse(JSON.stringify(row.medications)) });
  showForm.value = true;
};

const onDelete = (id: number) => {
  prescriptions.value = prescriptions.value.filter(p => p.id !== id);
  ElMessage.success('处方已删除');
};

const onClose = () => {
  showForm.value = false;
  formRef.value?.resetFields();
  editMode.value = false;
  Object.assign(form, { id: 0, patientName: '', date: '', medications: [] });
};

const onSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (editMode.value) {
        const idx = prescriptions.value.findIndex(p => p.id === form.id);
        prescriptions.value[idx] = JSON.parse(JSON.stringify(form));
        ElMessage.success('处方已更新');
      } else {
        form.id = Date.now();
        prescriptions.value.push(JSON.parse(JSON.stringify(form)));
        ElMessage.success('处方已创建');
      }
      onClose();
    }
  });
};
</script>

<style scoped>
.bg-grey-50 { background-color: #F9FAFB; }
.mb-4 { margin-bottom: 16px; }
.mt-4 { margin-top: 16px; }
.p-6 { padding: 24px; }
.min-h-screen { min-height: 100vh; }
.justify-end { justify-content: flex-end; }
.flex { display: flex; }
.items-center { align-items: center; }
</style>
