<template>
  <div class="page">
    <h2 class="page-title">处方管理</h2>
    <div class="panel">
      <div class="inline-form">
        <t-input v-model="query.visitId" placeholder="就诊ID" style="width: 160px" />
        <t-button theme="primary" @click="load">
          <template #icon><t-icon name="refresh" /></template>
          刷新
        </t-button>
        <t-button variant="outline" @click="openCreate">
          <template #icon><t-icon name="add" /></template>
          新增处方
        </t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id" bordered stripe hover>
        <template #visitId="{ row }">
          {{ getVisitLabel(row.visitId) }}
        </template>
        <template #doctorId="{ row }">
          {{ getDoctorName(row.doctorId) }}
        </template>
        <template #status="{ row }">
          <span class="status-badge" :class="getStatusClass(row.status)">
            {{ getStatusText(row.status) }}
          </span>
        </template>
        <template #op="{ row }">
          <div class="table-actions">
            <t-button size="small" variant="outline" @click="openEdit(row)">
              <template #icon><t-icon name="edit" /></template>
              编辑
            </t-button>
            <t-button 
              size="small" 
              variant="outline"
              @click="openItemManager(row)"
              style="margin-left: 8px;"
            >
              <template #icon><t-icon name="pill" /></template>
              药品
            </t-button>
            <t-button 
              v-if="row.status === 'DRAFT'" 
              size="small" 
              theme="success"
              @click="createOrder(row)"
              style="margin-left: 8px;"
            >
              <template #icon><t-icon name="cart" /></template>
              生成订单
            </t-button>
            <span v-else-if="row.status === 'SUBMITTED'" style="color: #0d9488; font-size: 13px; margin-left: 8px;">
              已生成订单
            </span>
          </div>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" :header="dialogTitle" :on-confirm="submit" width="600">
      <t-form :data="form" layout="vertical">
        <div class="form-section-title">处方信息</div>
        <t-form-item label="就诊记录" required>
          <t-select v-model="form.visitId" :options="visitOptions" placeholder="请选择就诊记录" clearable />
        </t-form-item>
        <t-form-item label="医生" required>
          <t-select v-model="form.doctorId" :options="doctorOptions" placeholder="请选择医生" clearable />
        </t-form-item>
        <t-form-item label="状态">
          <t-select v-model="form.status" :options="statusOptions" />
        </t-form-item>
        <t-form-item label="备注">
          <t-textarea v-model="form.remark" placeholder="请输入备注信息" :maxlength="500" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 药品管理弹窗 -->
    <t-dialog 
      v-model:visible="itemDialogVisible" 
      :header="itemDialogTitle" 
      width="800"
      :footer="false"
    >
      <div class="item-manager">
        <div class="item-toolbar">
          <t-button theme="primary" @click="openAddItem">
            <template #icon><t-icon name="add" /></template>
            添加药品
          </t-button>
        </div>
        
        <t-table 
          :data="prescriptionItems" 
          :columns="itemColumns" 
          row-key="id"
          bordered
          stripe
        >
          <template #unitPrice="{ row }">
            ¥{{ row.unitPrice?.toFixed(2) || '0.00' }}
          </template>
          <template #subtotal="{ row }">
            ¥{{ row.subtotal?.toFixed(2) || '0.00' }}
          </template>
          <template #op="{ row }">
            <div class="table-actions">
              <t-button size="small" variant="text" @click="openEditItem(row)">
                编辑
              </t-button>
              <t-popconfirm content="确认删除？" @confirm="deleteItem(row)">
                <t-button size="small" theme="danger" variant="text">删除</t-button>
              </t-popconfirm>
            </div>
          </template>
        </t-table>
        
        <div v-if="prescriptionItems.length === 0" class="empty-items">
          暂无药品，请点击"添加药品"按钮添加
        </div>

        <!-- 添加/编辑药品表单 -->
        <t-dialog 
          v-model:visible="showItemForm" 
          :header="editingItemId ? '编辑药品' : '添加药品'"
          width="500"
          :on-confirm="submitItem"
        >
          <t-form :data="itemForm" layout="vertical">
            <t-form-item label="药品" required>
              <t-select 
                v-model="itemForm.drugId" 
                :options="drugOptions" 
                placeholder="请选择药品"
                @change="onDrugChange"
              />
            </t-form-item>
            <t-row :gutter="16">
              <t-col :span="12">
                <t-form-item label="数量" required>
                  <t-input-number 
                    v-model="itemForm.quantity" 
                    :min="1"
                    @change="calcSubtotal"
                  />
                </t-form-item>
              </t-col>
              <t-col :span="12">
                <t-form-item label="单价" required>
                  <t-input-number 
                    v-model="itemForm.unitPrice" 
                    :min="0"
                    :decimal-places="2"
                    @change="calcSubtotal"
                  />
                </t-form-item>
              </t-col>
            </t-row>
            <t-form-item label="小计">
              <t-input-number 
                v-model="itemForm.subtotal" 
                :disabled="true"
                :decimal-places="2"
              />
            </t-form-item>
            <t-form-item label="用法用量">
              <t-input v-model="itemForm.usageDesc" placeholder="如：每日2次，每次1片" />
            </t-form-item>
            <t-form-item label="用药天数">
              <t-input-number v-model="itemForm.days" :min="1" />
            </t-form-item>
          </t-form>
        </t-dialog>
      </div>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../api';

const list = ref([] as any[]);
const visits = ref([] as any[]);
const doctors = ref([] as any[]);
const pets = ref([] as any[]);
const customers = ref([] as any[]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增处方');
const editingId = ref<number | null>(null);
const query = reactive({ visitId: '' });
const form = reactive({ visitId: '', doctorId: '', remark: '', status: 'DRAFT' });

// 药品管理相关
const itemDialogVisible = ref(false);
const itemDialogTitle = ref('管理药品');
const currentPrescription = ref<any>(null);
const prescriptionItems = ref<any[]>([]);
const drugs = ref<any[]>([]);
const itemForm = reactive({
  id: null as number | null,
  prescriptionId: '',
  drugId: '',
  drugName: '',
  specification: '',
  quantity: 1,
  unitPrice: 0,
  usageDesc: '',
  days: 1,
  subtotal: 0
});
const editingItemId = ref<number | null>(null);
const showItemForm = ref(false);

const visitOptions = computed(() => {
  return visits.value.map((visit: any) => {
    const pet = pets.value.find((item: any) => item.id === visit.petId);
    const customer = customers.value.find((item: any) => item.id === visit.customerId);
    const petName = pet?.name || `宠物${visit.petId}`;
    const customerName = customer?.username || `顾客${visit.customerId}`;
    return {
      label: `${customerName} - ${petName}`,
      value: visit.id
    };
  });
});

const getVisitLabel = (visitId: number) => {
  const visit = visits.value.find((item: any) => item.id === visitId);
  if (!visit) return visitId ? `就诊ID ${visitId}` : '-';
  const pet = pets.value.find((item: any) => item.id === visit.petId);
  const customer = customers.value.find((item: any) => item.id === visit.customerId);
  const petName = pet?.name || `宠物${visit.petId}`;
  const customerName = customer?.username || `顾客${visit.customerId}`;
  return `${customerName} - ${petName}`;
};

const getDoctorName = (doctorId: number) => {
  const doctor = doctors.value.find((item: any) => item.id === doctorId);
  if (!doctor) return doctorId ? `医生ID ${doctorId}` : '-';
  return doctor.username || doctor.name || `医生${doctor.id}`;
};

const doctorOptions = computed(() => {
  return doctors.value.map((doctor: any) => ({
    label: doctor.username || doctor.name || `医生${doctor.id}`,
    value: doctor.id
  }));
});

const drugOptions = computed(() => {
  return drugs.value.map((drug: any) => ({
    label: `${drug.name} (${drug.specification || '无规格'}) - ¥${drug.salePrice || 0}`,
    value: drug.id,
    name: drug.name,
    specification: drug.specification,
    price: drug.salePrice
  }));
});

const itemColumns = [
  { colKey: 'drugName', title: '药品名称', width: 150 },
  { colKey: 'specification', title: '规格', width: 120 },
  { colKey: 'quantity', title: '数量', width: 80 },
  { colKey: 'unitPrice', title: '单价', width: 100 },
  { colKey: 'subtotal', title: '小计', width: 100 },
  { colKey: 'usageDesc', title: '用法用量', ellipsis: true },
  { colKey: 'op', title: '操作', width: 120 }
];

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'DRAFT': '草稿',
    'SUBMITTED': '已提交',
    'ISSUED': '已发药',
    'VOIDED': '已作废'
  };
  return statusMap[status] || status;
};

const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    'DRAFT': 'status-pending',
    'SUBMITTED': 'status-active',
    'ISSUED': 'status-completed',
    'VOIDED': 'status-cancelled'
  };
  return classMap[status] || 'status-pending';
};

const statusOptions = [
  { label: '草稿', value: 'DRAFT' },
  { label: '已提交', value: 'SUBMITTED' },
  { label: '已发药', value: 'ISSUED' },
  { label: '已作废', value: 'VOIDED' },
];

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'visitId', title: '就诊' },
  { colKey: 'doctorId', title: '医生' },
  { colKey: 'status', title: '状态' },
  { colKey: 'op', title: '操作', width: 100 },
];

const load = async () => {
  const params: any = { page: 1, size: 20 };
  if (query.visitId) params.visitId = query.visitId;
  const res = await api.prescriptions(params);
  if (res.code === 0) list.value = res.data.records || [];
};

const openCreate = () => {
  dialogTitle.value = '新增处方';
  editingId.value = null;
  form.visitId = query.visitId;
  form.doctorId = '';
  form.remark = '';
  form.status = 'DRAFT';
  dialogVisible.value = true;
};

const openEdit = (row: any) => {
  dialogTitle.value = '编辑处方';
  editingId.value = row.id;
  form.visitId = row.visitId;
  form.doctorId = row.doctorId || '';
  form.remark = row.remark || '';
  form.status = row.status || 'DRAFT';
  dialogVisible.value = true;
};

const loadVisits = async () => {
  try {
    const res = await api.visits({ page: 1, size: 100 }); // 获取所有就诊记录
    if (res.code === 0) {
      visits.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取就诊记录失败');
    }
  } catch (error) {
    console.error('获取就诊记录失败:', error);
    MessagePlugin.error('获取就诊记录失败');
  }
};

const loadDoctors = async () => {
  try {
    const res = await api.users({ page: 1, size: 100, role: 'DOCTOR' }); // 获取所有医生
    if (res.code === 0) {
      doctors.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取医生列表失败');
    }
  } catch (error) {
    console.error('获取医生列表失败:', error);
    MessagePlugin.error('获取医生列表失败');
  }
};

const loadPets = async () => {
  try {
    const res = await api.pets({ page: 1, size: 100 });
    if (res.code === 0) {
      pets.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取宠物列表失败');
    }
  } catch (error) {
    console.error('获取宠物列表失败:', error);
    MessagePlugin.error('获取宠物列表失败');
  }
};

const loadCustomers = async () => {
  try {
    const res = await api.users({ page: 1, size: 100, role: 'CUSTOMER' });
    if (res.code === 0) {
      customers.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取顾客列表失败');
    }
  } catch (error) {
    console.error('获取顾客列表失败:', error);
    MessagePlugin.error('获取顾客列表失败');
  }
};

const submit = async () => {
  const payload = { ...form };
  const res = editingId.value
    ? await api.updatePrescription(editingId.value, payload)
    : await api.createPrescription(payload);
  if (res.code === 0) {
    MessagePlugin.success('保存成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '保存失败');
  }
};

const createOrder = async (row: any) => {
  try {
    const res = await api.createOrderFromPrescription(row.id);
    if (res.code === 0) {
      MessagePlugin.success('订单生成成功');
      load(); // 刷新列表，状态会变为已提交
    } else {
      MessagePlugin.error(res.message || '生成订单失败');
    }
  } catch (error) {
    console.error('生成订单失败:', error);
    MessagePlugin.error('生成订单失败');
  }
};

// 药品管理方法
const openItemManager = async (row: any) => {
  currentPrescription.value = row;
  itemDialogTitle.value = `管理药品 - 处方#${row.id}`;
  itemDialogVisible.value = true;
  showItemForm.value = false;
  await loadPrescriptionItems(row.id);
  await loadDrugs();
};

const loadPrescriptionItems = async (prescriptionId: number) => {
  try {
    const res = await api.prescriptionItems({ prescriptionId });
    if (res.code === 0) {
      prescriptionItems.value = res.data || [];
    }
  } catch (error) {
    console.error('加载药品明细失败:', error);
    prescriptionItems.value = [];
  }
};

const loadDrugs = async () => {
  try {
    const res = await api.drugs({ page: 1, size: 100 });
    if (res.code === 0) {
      drugs.value = res.data?.records || [];
    }
  } catch (error) {
    console.error('加载药品列表失败:', error);
  }
};

const openAddItem = () => {
  editingItemId.value = null;
  itemForm.prescriptionId = currentPrescription.value?.id || '';
  itemForm.drugId = '';
  itemForm.drugName = '';
  itemForm.specification = '';
  itemForm.quantity = 1;
  itemForm.unitPrice = 0;
  itemForm.usageDesc = '';
  itemForm.days = 1;
  itemForm.subtotal = 0;
  showItemForm.value = true;
};

const openEditItem = (row: any) => {
  editingItemId.value = row.id;
  itemForm.prescriptionId = row.prescriptionId;
  itemForm.drugId = row.drugId;
  itemForm.drugName = row.drugName || '';
  itemForm.specification = row.specification || '';
  itemForm.quantity = row.quantity || 1;
  itemForm.unitPrice = row.unitPrice || 0;
  itemForm.usageDesc = row.usageDesc || '';
  itemForm.days = row.days || 1;
  itemForm.subtotal = row.subtotal || 0;
  showItemForm.value = true;
};

const onDrugChange = (value: any) => {
  const drug = drugOptions.value.find((d: any) => d.value === value);
  if (drug) {
    itemForm.drugName = drug.name;
    itemForm.specification = drug.specification || '';
    itemForm.unitPrice = drug.price || 0;
    calcSubtotal();
  }
};

const calcSubtotal = () => {
  itemForm.subtotal = (itemForm.quantity || 0) * (itemForm.unitPrice || 0);
};

const submitItem = async () => {
  if (!itemForm.drugId || !itemForm.quantity) {
    MessagePlugin.warning('请选择药品并填写数量');
    return;
  }
  
  const payload = { ...itemForm };
  try {
    const res = editingItemId.value
      ? await api.updatePrescriptionItem(editingItemId.value, payload)
      : await api.createPrescriptionItem(payload);
    
    if (res.code === 0) {
      MessagePlugin.success(editingItemId.value ? '修改成功' : '添加成功');
      showItemForm.value = false;
      await loadPrescriptionItems(currentPrescription.value.id);
    } else {
      MessagePlugin.error(res.message || '保存失败');
    }
  } catch (error) {
    console.error('保存药品明细失败:', error);
    MessagePlugin.error('保存失败');
  }
};

const deleteItem = async (row: any) => {
  try {
    const res = await api.deletePrescriptionItem(row.id);
    if (res.code === 0) {
      MessagePlugin.success('删除成功');
      await loadPrescriptionItems(currentPrescription.value.id);
    } else {
      MessagePlugin.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除药品明细失败:', error);
    MessagePlugin.error('删除失败');
  }
};

onMounted(() => {
  load();
  loadVisits();
  loadDoctors();
  loadPets();
  loadCustomers();
});
</script>

<style scoped>
.item-manager {
  padding: 16px 0;
}

.item-toolbar {
  margin-bottom: 16px;
}

.empty-items {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}

:deep(.t-table) {
  margin-top: 8px;
}
</style>
