<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { useVbenModal, useVbenDrawer } from '@vben/common-ui';

import {
  BookOutlined,
  ClearOutlined,
  DeleteTwoTone,
  FileTextOutlined,
  HistoryOutlined,
  MedicineBoxOutlined,
  MinusOutlined,
  PlusOutlined,
  RobotOutlined,
  SaveOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
import {
  Modal as AntModal,
  Button,
  Card,
  Col,
  Empty,
  Image,
  ImagePreviewGroup,
  Input,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Spin,
  Tag,
  Tabs,
  TabPane,
  Textarea,
} from 'ant-design-vue';

import {
  saveChineseCommonPrescriptionApi,
  saveWestCommonPrescriptionApi,
} from '#/views/business/chat/api';
import { usePrescriptionStore } from '#/store/prescription';
import {
  hasVipPermission,
  useVipPermission,
  VIP_FEATURE,
} from '#/utils/vip';
import MedicalRecordPanel from '#/views/doctor/medical-record/MedicalRecordPanel.vue';
import EntryKeywordBubble from '#/views/doctor/medical-record/components/EntryKeywordBubble.vue';
import CommonDxOrderChips from '#/views/doctor/medical-record/components/CommonDxOrderChips.vue';
import PatientMedicalRecordDrawer from '#/views/doctor/medical-record/components/PatientMedicalRecordDrawer.vue';
import { saveMedicalRecord } from '#/views/doctor/medical-record/api';
import {
  loadRxMrTab,
  saveRxMrTab,
} from '#/views/doctor/medical-record/utils/localDraft';
import PatientBriefBar from '#/views/doctor/doctor-reception/components/PatientBriefBar.vue';
import PatientInfoDrawer from '#/views/doctor/doctor-reception/components/PatientInfoDrawer.vue';
import PatientPrescriptionHistoryDrawer from '#/views/doctor/doctor-reception/components/PatientPrescriptionHistoryDrawer.vue';
import { getTraditionalChineseMedicineAllApi } from '#/views/doctor/doctor-reception/api';
// 导入子组件
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';
import WesternModal from '#/views/doctor/doctor-reception/components/WesternModal.vue';
import SimpleProductModal from '#/views/doctor/doctor-reception/components/SimpleProductModal.vue';
// 常用方选择弹窗组件
import CommonPrescriptionModal from '#/views/doctor/doctor-reception/components/CommonPrescriptionModal.vue';
import GoldenFormulaModal from '#/views/doctor/doctor-reception/components/GoldenFormulaModal.vue';
import AiPrescriptionDrawer from '#/views/doctor/doctor-reception/components/AiPrescriptionDrawer.vue';
// 信息提示模态框
import InfoModal from '#/components/modal/InfoModal.vue';
// 药品搜索选择组件
import { DrugSearchSelect } from '#/components/drug-search-select';
import { ChineseDrugNameBubble } from '#/components/chinese-drug-name-bubble';
import { formatPriceDisplay } from '#/utils/formatPrice';
import ChineseMedicineConfig from '#/views/doctor/doctor-reception/components/ChineseMedicineConfig.vue';
import { getDeliveryWarehouseOptionsByDrugs, getPrescriptionInfoApi } from '#/views/doctor/doctor-reception/api';
import WarehouseSelectModal from './WarehouseSelectModal.vue';
import { detailDoctorOrderToText } from '#/utils/prescriptionDoctorOrder';

const splitString = (input: string) => input.split(',');

const modalData = ref<any>();
const visible = ref(false);
const previewImage = ref([]);
const showNewDrugModal = ref(false);
const doctorSecondSignModal = ref(false);
/** 处方|病历 Tab（按挂号 + storagePrefix 落本地） */
const rxMrTab = ref<'rx' | 'mr'>('rx');
const medicalRecordPanelRef = ref<InstanceType<typeof MedicalRecordPanel> | null>(null);

// 使用 Pinia store（须在依赖它的 computed/watch 之前初始化）
const prescriptionStore = usePrescriptionStore();

/**
 * 在线复诊 VIP：优先挂号履约诊所返回的 vip，否则回落登录态
 */
const registerSideVip = computed(
  () => prescriptionStore.registerStoreInfo?.vip ?? null,
);

/** 履约诊所 VIP 能力（金方 / AI 等） */
const {
  canUseAiMedicalRecord,
  canUseAiPrescription,
  canUseGoldenFormula,
} = useVipPermission(registerSideVip);

/**
 * 病历 Tab：履约诊所 medical_record + 弹窗场景开关（诊所前缀默认关）
 */
const canUseMedicalRecord = computed(() => {
  if (!hasVipPermission(VIP_FEATURE.MEDICAL_RECORD, registerSideVip.value)) {
    return false;
  }
  if (modalData.value?.enableMedicalRecord === false) return false;
  if (modalData.value?.enableMedicalRecord === true) return true;
  const prefix = modalData.value?.storagePrefix || 'onlineConsultation-';
  return prefix !== 'onlineConsultationClinic-';
});

const medicalRecordStoragePrefix = computed(
  () => modalData.value?.storagePrefix || 'onlineConsultation-',
);

const diagnosisModel = computed({
  get: () => prescriptionStore.diagnosis,
  set: (v: string) => {
    prescriptionStore.diagnosis = v;
  },
});
const medicalAdviceModel = computed({
  get: () => prescriptionStore.medicalAdvice,
  set: (v: string) => {
    prescriptionStore.medicalAdvice = v;
  },
});

const medicalRecordRegisterId = computed(
  () =>
    Number(
      modalData.value?.registerId ||
        prescriptionStore.currentRegisterId ||
        0,
    ),
);
const medicalRecordStoreId = computed(
  () =>
    Number(
      prescriptionStore.registerStoreInfo?.store_id ||
        prescriptionStore.selectedStoreId ||
        prescriptionStore.myStoreId ||
        0,
    ),
);
/** activePatient 即为 user_patient，主键用 id */
const medicalRecordPatientId = computed(
  () => Number(prescriptionStore.activePatient?.id || 0),
);

watch(rxMrTab, (tab) => {
  const rid = medicalRecordRegisterId.value;
  if (rid) saveRxMrTab(rid, tab, medicalRecordStoragePrefix.value);
});

watch(
  () => [medicalRecordRegisterId.value, canUseMedicalRecord.value] as const,
  ([rid, can]) => {
    if (!can) {
      rxMrTab.value = 'rx';
      return;
    }
    if (!rid) return;
    rxMrTab.value = loadRxMrTab(rid, medicalRecordStoragePrefix.value) || 'rx';
  },
  { immediate: true },
);

// ==================== 保存常用方相关状态 ====================
/** 保存常用方弹窗是否显示 */
const showSaveCommonPrescriptionModal = ref(false);
/** 常用方名称输入 */
const commonPrescriptionName = ref('');
/** 是否正在保存常用方 */
const isSavingCommonPrescription = ref(false);

/** 处方类型来自后端下发（store.categories） */
const categories = computed(() => prescriptionStore.categories);


const allowInsuranceCategory = computed(
  () => Number(prescriptionStore.registerStoreInfo?.allow_insurance_category ?? 0) === 1,
);

/** 仅中药/西药支持常用方模板（保健食品等不提供常用方） */
const canUseCommonPrescription = computed(() =>
  [1, 2].includes(prescriptionStore.activeCategory),
);
const aiPrescriptionDrawerRef = ref<InstanceType<typeof AiPrescriptionDrawer> | null>(null);

/** 按字典 id 取展示名（提交仍存旧字段 id） */
function tcmLabelById(
  list: Array<{ id?: number | string; name?: string }> | undefined,
  id: number | string | null | undefined,
) {
  if (id == null || id === '') return '';
  const hit = (list || []).find((x) => Number(x.id) === Number(id));
  return hit?.name ? String(hit.name) : '';
}

const diseasesSelectedLabel = computed(() =>
  tcmLabelById(
    prescriptionStore.traditionalChineseMedicine?.diseases,
    prescriptionStore.diseasesSelected,
  ),
);
const methodSelectedLabel = computed(() =>
  tcmLabelById(
    prescriptionStore.traditionalChineseMedicine?.method,
    prescriptionStore.methodSelected,
  ),
);
const syndromeSelectedLabel = computed(() =>
  tcmLabelById(
    prescriptionStore.traditionalChineseMedicine?.syndrome,
    prescriptionStore.syndromeSelected,
  ),
);

watch(allowInsuranceCategory, (allow) => {
  if (!allow) {
    prescriptionStore.category = 1;
  }
}, { immediate: true });

const submittingType = ref(false);
/** 弹窗内容区 loading（先校验开方种类权限） */
const contentLoading = ref(false);
const [Modal, modalApi] = useVbenModal({
  draggable: true,
  confirmText: '发送处方',
  submitting: submittingType.value,
  // 增加 modal 宽度以适应左右布局
  class: 'w-[95%] max-w-[1400px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    submittingType.value = true;
    await handleCheckChineseMedicineConflict();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      modalData.value = modalApi.getData<Record<string, any>>();

      if (modalData.value?.registerId) {
        // 获取存储前缀，默认为在线复诊-药店
        const storagePrefix = modalData.value?.storagePrefix || 'onlineConsultation-';
        contentLoading.value = true;
        try {
          // 先校验开方种类权限，再加载完整开方数据
          const allowed = await prescriptionStore.loadPrescriptionTypeOptions(
            modalData.value.registerId,
          );
          if (!allowed) {
            message.error(
              prescriptionStore.prescriptionTypeDenyMessage ||
                '当前门店未开通开方权限',
            );
            modalApi.close();
            return;
          }
          await prescriptionStore.initializePrescription(
            modalData.value.registerId,
            true,
            storagePrefix,
          );
          prescriptionStore.loadFromLocalStorage();
          // 中医三典走接口全量，替换静态 json，保证搜索 id 与展示名一致
          try {
            const tcmRes = await getTraditionalChineseMedicineAllApi();
            const tcmData = tcmRes?.data || tcmRes || {};
            if (tcmData.diseases || tcmData.method || tcmData.syndrome) {
              prescriptionStore.traditionalChineseMedicine = {
                diseases: tcmData.diseases || [],
                method: tcmData.method || [],
                syndrome: tcmData.syndrome || [],
              };
            }
          } catch (e) {
            console.warn('加载中医字典失败，回落静态数据', e);
          }
          // 再拉一次类型，确保与门店一致并校正 Tab
          await prescriptionStore.loadPrescriptionTypeOptions(
            modalData.value.registerId,
          );
          if (!prescriptionStore.prescriptionTypeAllowed) {
            message.error(
              prescriptionStore.prescriptionTypeDenyMessage ||
                '当前门店未开通开方权限',
            );
            modalApi.close();
            return;
          }
          await prescriptionStore.fetchRegisterStoreInfo();
          if (prescriptionStore.activeCategory === 1) {
            await checkAndShowTransferTip();
          }
        } finally {
          contentLoading.value = false;
        }
      } else {
        console.warn('未提供registerId');
      }
    }
  },
});

watch(
  () => prescriptionStore.currentDrugs,
  (newValue) => {
    // currentDrugs 更新
  },
  { deep: true },
);

// 创建子模态框
const [WesternDrugModal, WesternDrugModalApi] = useVbenModal({
  connectedComponent: WesternModal,
});

const [SimpleProductModalComponent, SimpleProductModalApi] = useVbenModal({
  connectedComponent: SimpleProductModal,
});

const [PrescriptionDetailModal, PrescriptionDetailModalApi] = useVbenModal({
  connectedComponent: PrescriptionDetail,
});

/**
 * 诊断/医嘱追加（中文逗号拼接，与病历面板一致）
 */
function appendCommaText(base: string, add: string) {
  if (!add) return base || '';
  const parts = (base || '').split('，').map((s) => s.trim()).filter(Boolean);
  if (parts.includes(add)) return parts.join('，');
  parts.push(add);
  return parts.join('，');
}

/** 气泡/常用标签选中诊断（在线复诊诊断框只读，只能通过选择写入） */
function onPickDiagnosis(text: string) {
  const t = String(text || '').trim();
  if (!t) return;
  prescriptionStore.diagnosis = appendCommaText(prescriptionStore.diagnosis, t);
}

/**
 * 按名称在中医字典中匹配 id（精确 → 别名 → 包含）
 * 在线复诊提交仍写旧字段 diseasesSelected / methodSelected / syndromeSelected
 */
function matchTcmDictId(
  list: Array<{ id?: number | string; name?: string; alias?: string }> | undefined,
  name: string,
): number | null {
  const raw = String(name || '').trim();
  if (!raw || !Array.isArray(list) || !list.length) return null;
  const first =
    raw
      .split(/[，,]/)
      .map((s) => s.trim())
      .filter(Boolean)[0] || '';
  if (!first) return null;
  let hit = list.find((it) => String(it.name || '').trim() === first);
  if (hit?.id != null) return Number(hit.id);
  hit = list.find((it) => {
    const alias = String(it.alias || '');
    return (
      alias &&
      (alias === first ||
        alias
          .split(/[，,]/)
          .map((s) => s.trim())
          .includes(first))
    );
  });
  if (hit?.id != null) return Number(hit.id);
  hit = list.find((it) => {
    const n = String(it.name || '');
    return n && (n.includes(first) || first.includes(n));
  });
  return hit?.id != null ? Number(hit.id) : null;
}

/**
 * 病历侧变更后同步到处方：诊断已双向绑定；主诉进 AI 出方；中医三典名称→旧字段 id
 */
function onMrSyncToPrescription(payload: Record<string, any>) {
  const data = payload || {};
  // 诊断/医嘱已由 v-model 同步；此处专补在线复诊中医三项 ID
  void syncOnlineTcmIdsFromMrNames({
    tcm_syndrome: data.tcm_syndrome,
    tcm_disease: data.tcm_disease,
    tcm_method: data.tcm_method,
  });
}

/**
 * 病历中医三字段名称 → diseasesSelected / methodSelected / syndromeSelected
 * 与 UI 交叉绑定一致：证候→diseases；疾病→syndrome；治法→method
 */
function syncOnlineTcmIdsFromMrNames(names: {
  tcm_syndrome?: string;
  tcm_disease?: string;
  tcm_method?: string;
}) {
  if (prescriptionStore.activeCategory !== 1) return;
  const n = names || {};
  const dict = prescriptionStore.traditionalChineseMedicine || {};
  const diseases = dict.diseases || [];
  const method = dict.method || [];
  const syndrome = dict.syndrome || [];
  if (n.tcm_syndrome) {
    const id = matchTcmDictId(diseases, n.tcm_syndrome);
    if (id != null) prescriptionStore.diseasesSelected = id;
  }
  if (n.tcm_method) {
    const id = matchTcmDictId(method, n.tcm_method);
    if (id != null) prescriptionStore.methodSelected = id;
  }
  if (n.tcm_disease) {
    const id = matchTcmDictId(syndrome, n.tcm_disease);
    if (id != null) prescriptionStore.syndromeSelected = id;
  }
}

/** AI 写病历返回的字典 id 直接落到开方旧字段 */
function onApplyAiTcmIds(tcmIds: {
  diseases_id?: number | null;
  method_id?: number | null;
  syndrome_id?: number | null;
} | null) {
  if (!tcmIds || typeof tcmIds !== 'object') return;
  if (tcmIds.diseases_id != null && Number(tcmIds.diseases_id) > 0) {
    prescriptionStore.diseasesSelected = Number(tcmIds.diseases_id);
  }
  if (tcmIds.method_id != null && Number(tcmIds.method_id) > 0) {
    prescriptionStore.methodSelected = Number(tcmIds.method_id);
  }
  if (tcmIds.syndrome_id != null && Number(tcmIds.syndrome_id) > 0) {
    prescriptionStore.syndromeSelected = Number(tcmIds.syndrome_id);
  }
}

/** 气泡/常用标签选中医嘱 */
function onPickDoctorOrder(text: string) {
  const t = String(text || '').trim();
  if (!t) return;
  prescriptionStore.medicalAdvice = appendCommaText(
    prescriptionStore.medicalAdvice,
    t,
  );
}

/**
 * 中医三项：用新搜索气泡选中后写入旧字段 id（diseasesSelected / methodSelected / syndromeSelected）
 * source 与开方 UI 交叉绑定一致：证候搜 diseases；疾病搜 syndrome；治法搜 method
 */
function onPickOnlineTcm(
  field: 'diseases' | 'method' | 'syndrome',
  item: { id?: number | string; title?: string; content?: string; name?: string },
) {
  const id = Number(item?.id || 0);
  if (!id) return;
  if (field === 'diseases') prescriptionStore.diseasesSelected = id;
  else if (field === 'method') prescriptionStore.methodSelected = id;
  else prescriptionStore.syndromeSelected = id;
  // 若字典尚未含该行，补一条便于展示名
  const name = String(item?.content || item?.title || item?.name || '').trim();
  if (name) {
    const dict = prescriptionStore.traditionalChineseMedicine || {};
    const key =
      field === 'diseases' ? 'diseases' : field === 'method' ? 'method' : 'syndrome';
    const list = Array.isArray((dict as any)[key]) ? [...(dict as any)[key]] : [];
    if (!list.some((x: any) => Number(x.id) === id)) {
      list.push({ id, name });
      prescriptionStore.traditionalChineseMedicine = { ...dict, [key]: list };
    }
  }
}

/** 打开 AI 写病历（复用病历面板 expose） */
function openAiMedicalRecord() {
  if (!canUseAiMedicalRecord.value) {
    message.warning('当前门店未开通AI写病历VIP功能');
    return;
  }
  medicalRecordPanelRef.value?.aiGenerate?.();
}

/** 打开 AI 辅助出方 */
function openAiPrescriptionDrawer() {
  if (!canUseAiPrescription.value) {
    message.warning('当前门店未开通AI辅助出方VIP功能');
    return;
  }
  const registerId = Number(prescriptionStore.currentRegisterId || 0);
  if (!registerId) {
    message.warning('挂号无效');
    return;
  }
  let payload: Record<string, any> =
    medicalRecordPanelRef.value?.getPayload?.() || {};
  if (prescriptionStore.diagnosis) payload.diagnosis = prescriptionStore.diagnosis;
  if (prescriptionStore.medicalAdvice) {
    payload.doctor_order = prescriptionStore.medicalAdvice;
  }
  aiPrescriptionDrawerRef.value?.open({
    registerId,
    storeId: Number(medicalRecordStoreId.value || 0) || undefined,
    prescriptionType: Number(prescriptionStore.activeCategory),
    patientName: String(prescriptionStore.activePatient?.name || ''),
    patientSex: Number(prescriptionStore.activePatient?.sex || 0),
    patientAge: Number(prescriptionStore.activePatient?.age || 0),
    chiefComplaint: String(payload.chief_complaint || ''),
    medicalRecord: { ...payload },
  });
}

function handleSyncAiMedicalRecord(partial: Record<string, any>) {
  medicalRecordPanelRef.value?.patchFields?.(partial || {});
}

/** AI/金方导入药品：覆盖写入当前处方清单 */
async function handleImportAiPrescription(payload: {
  rows?: any[];
  dosage?: number;
  day_dosage?: number;
  rule_type?: number;
  process_rule_id?: number;
  child_process_rule_id?: number;
  process_rule_note_id?: number;
}) {
  const list = Array.isArray(payload?.rows) ? payload.rows : [];
  if (!list.length) {
    message.warning('没有可导入的药品');
    return;
  }
  // 复用金方导入逻辑（整表覆盖）
  handleImportGoldenFormula({
    rows: list,
    formulaName: 'AI出方',
  });
  // 中药剂数/每日次数：有值用返回值，否则用处方默认 7/2
  if (Number(payload?.dosage) > 0) {
    prescriptionStore.dosage = Number(payload.dosage);
  } else {
    prescriptionStore.dosage = prescriptionStore.dosage || 7;
  }
  if (Number(payload?.day_dosage) > 0) {
    prescriptionStore.dayDosage = Number(payload.day_dosage);
  } else {
    prescriptionStore.dayDosage = prescriptionStore.dayDosage || 2;
  }
  // 委托调剂：同步制剂要求 / 二级煎法 / 备注（与接诊端 AI 导入、常用方一致）
  const prId = Number(payload?.process_rule_id || 0);
  const isEntrusted = payload?.rule_type === 2 || prId > 0;
  if (isEntrusted && Number(prescriptionStore.activeCategory) === 1) {
    prescriptionStore.ruleType = 2;
    // 先清下级，避免沿用上一次处方的煎法/备注
    prescriptionStore.childProcessRuleId = undefined;
    prescriptionStore.processRuleNoteId = undefined;
    prescriptionStore.childProcessRuleList = [];
    prescriptionStore.processRuleNoteList = [];
    if (!prescriptionStore.processRuleList?.length) {
      await prescriptionStore.getProcessRuleListData(0, 0);
    }
    if (prId > 0) {
      prescriptionStore.processRuleId = prId;
      await prescriptionStore.getProcessRuleListData(prId, 0);
    }
    const childId = Number(payload?.child_process_rule_id || 0);
    if (childId > 0) {
      prescriptionStore.childProcessRuleId = childId;
      await prescriptionStore.getProcessRuleListData(0, childId);
    }
    const noteId = Number(payload?.process_rule_note_id || 0);
    if (noteId > 0) {
      prescriptionStore.processRuleNoteId = noteId;
    }
    prescriptionStore.syncToLocalStorage();
  }
}

// 信息提示模态框
const [InfoModalComponent, infoModalApi] = useVbenModal({
  connectedComponent: InfoModal,
});

// ==================== 常用方选择弹窗 ====================
const [CommonPrescriptionModals, CommonPrescriptionModalApi] = useVbenModal({
  connectedComponent: CommonPrescriptionModal,
});

/** 金方导入弹窗 */
const [GoldenFormulaModals, GoldenFormulaModalApi] = useVbenModal({
  connectedComponent: GoldenFormulaModal,
});

const setVisible = (value: boolean, instruction = ''): void => {
  previewImage.value = [];
  if (instruction === '') {
    message.error('该产品没有说明书！');
    return;
  }

  if (typeof instruction === 'string') {
    if (instruction.includes(',')) {
      previewImage.value = instruction.split(',');
    } else {
      previewImage.value.push(instruction);
    }
  }
  visible.value = value;
};

const handleCheckChineseMedicineConflict = async () => {
  const result = await prescriptionStore.checkChineseMedicineConflict();
  if (result.hasConflict) {
    doctorSecondSignModal.value = true;
  } else {
    await handleSendPrescription();
  }
};

// 药店开方待选仓时暂存发送参数
const pendingSendParams = ref<{
  doctorSecondSignValue: number;
  sendMode: number;
  customStoreId: number | null;
} | null>(null);

const [WarehouseSelectModals, warehouseSelectModalApi] = useVbenModal({
  connectedComponent: WarehouseSelectModal,
});

/**
 * 在线复诊发送前：有仓药绑定时弹卡片选仓（默认最低价）
 * @returns true=已拦截发送等待选仓；false=无需选仓可继续发送
 */
const tryPharmacyWarehouseSelect = async (
  doctorSecondSignValue: number,
  sendMode: number,
  customStoreId: number | null,
): Promise<boolean> => {
  const drugs = prescriptionStore.currentDrugs || [];
  const drugIds: number[] = [];
  const needQtyMap: Record<number, number> = {};
  for (const d of drugs) {
    const id = Number(d?.id ?? 0);
    const qty = Number(d?.select_number ?? d?.number ?? 0);
    if (id <= 0 || qty <= 0) {
      continue;
    }
    drugIds.push(id);
    needQtyMap[id] = (needQtyMap[id] || 0) + qty;
  }
  if (drugIds.length === 0) {
    return false;
  }
  try {
    const res = await getDeliveryWarehouseOptionsByDrugs({
      drug_ids: drugIds,
      need_qty_map: needQtyMap,
    });
    const map = (res?.result ?? res ?? {}) as Record<string, any[]>;
    const rows: Array<{
      drug_id: number;
      drug_name: string;
      options: Array<{
        warehouse_id: number;
        warehouse_name: string;
        quote: string;
        available_stock: number;
      }>;
    }> = [];
    for (const d of drugs) {
      const id = Number(d?.id ?? 0);
      if (id <= 0) {
        continue;
      }
      const options = map[String(id)] || map[id] || [];
      if (!Array.isArray(options) || options.length === 0) {
        continue;
      }
      rows.push({
        drug_id: id,
        // 优先用仓选项接口带回的药品信息，避免处方草稿未存规格/图
        drug_name: String(
          options[0]?.drug_name ||
            d?.drug_name ||
            d?.name ||
            `药品#${id}`,
        ),
        image: String(
          options[0]?.image ||
            d?.image ||
            d?._image ||
            d?.drug?.image ||
            '',
        ),
        specification: String(
          options[0]?.specification ||
            d?.specification ||
            d?.drug?.specification ||
            '',
        ),
        options: options.map((o) => ({
          warehouse_id: Number(o.warehouse_id),
          warehouse_name: String(o.warehouse_name || ''),
          quote: String(o.quote ?? '0'),
          available_stock: Number(o.available_stock ?? 0),
          // 保留药品展示字段，供弹窗从 options[0] 回退读取
          drug_name: String(o.drug_name || ''),
          image: String(o.image || ''),
          specification: String(o.specification || ''),
        })),
      });
    }
    if (rows.length === 0) {
      return false;
    }
    pendingSendParams.value = {
      doctorSecondSignValue,
      sendMode,
      customStoreId,
    };
    warehouseSelectModalApi.setData({ rows });
    warehouseSelectModalApi.open();
    return true;
  } catch (error: any) {
    message.error(error?.message || '加载配送仓库失败');
    return true;
  }
};

const onWarehouseSelected = async (warehouseMap: Record<number, number>) => {
  if (!pendingSendParams.value) return;
  const { doctorSecondSignValue, sendMode, customStoreId } =
    pendingSendParams.value;
  pendingSendParams.value = null;
  await executeSendPrescription(
    doctorSecondSignValue,
    sendMode,
    customStoreId,
    warehouseMap,
  );
};

// 处方发送前的确认流程
const handleSendPrescription = async (doctorSecondSignValue = 0) => {
  // 确保基础数据已初始化（包括当前诊所列表）
  await prescriptionStore.initializeBasicData();

  // 获取挂号诊所信息
  await prescriptionStore.fetchRegisterStoreInfo();

  const storeInfo = prescriptionStore.registerStoreInfo;
  let sendMode = 0;
  let customStoreId: number | null = null;
  if (storeInfo?.is_from_transfer === 1 && storeInfo?.delegate_store_id) {
    sendMode = 1;
    customStoreId = storeInfo.delegate_store_id;
  } else if (storeInfo?.store_id) {
    sendMode = 1;
    customStoreId = storeInfo.store_id;
  }
  // 有绑仓药品时先卡片选仓，再发送
  const needSelect = await tryPharmacyWarehouseSelect(
    doctorSecondSignValue,
    sendMode,
    customStoreId,
  );
  if (needSelect) {
    return;
  }
  await executeSendPrescription(doctorSecondSignValue, sendMode, customStoreId);
};

// 执行发送处方
const executeSendPrescription = async (
  doctorSecondSignValue: number,
  sendMode: number,
  customStoreId: number | null,
  warehouseMap: Record<number, number> | null = null,
) => {
  const result = await prescriptionStore.sendPrescription(
    doctorSecondSignValue,
    sendMode,
    customStoreId,
    warehouseMap,
  );

  // 检查返回结果，可能是boolean或包含转诊信息的对象
  const success = typeof result === 'boolean' ? result : result?.success !== false;
  const prescriptionResult = typeof result === 'object' ? result : null;

  if (success) {
    // VIP 病历：发送成功后同步保存（诊断/医嘱与处方同源）
    if (canUseMedicalRecord.value) {
      try {
        const payload = medicalRecordPanelRef.value?.getPayload?.() || {};
        await saveMedicalRecord({
          ...payload,
          register_id: medicalRecordRegisterId.value,
          store_id: medicalRecordStoreId.value,
          user_patient_id: medicalRecordPatientId.value,
          diagnosis: prescriptionStore.diagnosis,
          doctor_order: prescriptionStore.medicalAdvice,
          medicalAdvice: prescriptionStore.medicalAdvice,
        });
      } catch (e) {
        console.error('同步保存病历失败', e);
      }
    }
    // 检查是否需要转诊（西医诊所开中药处方）
    if (prescriptionResult?.need_transfer || prescriptionResult?.result?.need_transfer) {
      const transferId = prescriptionResult?.transfer_prescription_id || prescriptionResult?.result?.transfer_prescription_id;
      if (transferId) {
        // 显示转诊确认提示
        AntModal.info({
          title: '转诊提示',
          content: '该处方已触发转诊流程，转诊消息已发送给委托诊所的在线问诊医生。',
          okText: '确定',
          onOk: () => {
            if (modalData.value?.onPrescriptionSent) {
              modalData.value.onPrescriptionSent();
            }
            submittingType.value = false;
            modalApi.close();
          },
        });
        return;
      }
    }

    if (modalData.value?.onPrescriptionSent) {
      modalData.value.onPrescriptionSent();
    }
    submittingType.value = false;
    modalApi.close();
  }
};

const newDrugBlur = () => {
  if (
    prescriptionStore.newDrugInfo.id > 0 &&
    prescriptionStore.newDrugInfo.number > 0
  ) {
    showNewDrugModal.value = true;
  }
};

const newDrugModalOk = () => {
  prescriptionStore.addDrugByChinese();
  showNewDrugModal.value = false;
};

const doctorSecondSignModalOk = () => {
  doctorSecondSignModal.value = false;
  handleSendPrescription(1);
};

const searchOption = (inputValue: string) => {
  prescriptionStore.getDrugList(inputValue);
};

const tabChange = async (id: number) => {
  prescriptionStore.changeCategory(id);

  // 如果切换到中药（id === 1），检测当前诊所是否为西医诊所
  if (id === 1) {
    await checkAndShowTransferTip();
  }
};

/**
 * 检测并显示转诊提示
 * @description 当切换到中药处方时，如果当前诊所为西医诊所，显示转诊提示
 */
const checkAndShowTransferTip = async () => {
  try {
    // 重新获取挂号诊所信息，确保包含最新的诊所类型和委托诊所信息
    await prescriptionStore.fetchRegisterStoreInfo();

    const storeInfo = prescriptionStore.registerStoreInfo;
    if (!storeInfo) {
      return;
    }

    // 检测是否为西医诊所（current_store_clinic_type === 1）
    if (storeInfo.current_store_clinic_type === 1 && storeInfo.delegate_store) {
      const delegateStore = storeInfo.delegate_store;
      const doctorName = delegateStore.doctor?.name || '委托医生';
      const storeName = delegateStore.name || '委托诊所';

      infoModalApi
        .setState({ title: '转诊提示', width: 500 })
        .setData({
          content: `检测到当前诊所为西医诊所，本次处方开具后自动转接到【${storeName}】的【${doctorName}】的在线复诊中`,
        })
        .open();
    }
  } catch (error) {
    console.error('获取诊所信息失败:', error);
  }
};

const [PatientInfoDrawerComp, patientInfoDrawerApi] = useVbenDrawer({
  connectedComponent: PatientInfoDrawer,
});
const [PatientMrDrawerComp, patientMrDrawerApi] = useVbenDrawer({
  connectedComponent: PatientMedicalRecordDrawer,
});
const [PatientRxHistoryDrawerComp, patientRxHistoryDrawerApi] = useVbenDrawer({
  connectedComponent: PatientPrescriptionHistoryDrawer,
});

/** 健康档案史写入病历草稿并切到病历 Tab */
function importHealthHistoryToMedicalRecord(fields: Record<string, string>) {
  if (!canUseMedicalRecord.value) {
    message.warning('未开通病历功能');
    return;
  }
  rxMrTab.value = 'mr';
  medicalRecordPanelRef.value?.patchFields?.(fields || {});
}

function openPatientInfoDrawer() {
  patientInfoDrawerApi.setData({
    patient: prescriptionStore.activePatient,
    register: prescriptionStore.patientInfo,
    healthInquiry: prescriptionStore.userPatientHealthInquiry,
    patientName: prescriptionStore.activePatient?.name,
    canImportMedicalRecord: canUseMedicalRecord.value,
    onImportHistory: importHealthHistoryToMedicalRecord,
  });
  patientInfoDrawerApi.open();
}

function openPatientMrCiteDrawer() {
  const patientId = medicalRecordPatientId.value;
  if (!patientId) {
    message.warning('无就诊人信息');
    return;
  }
  if (canUseMedicalRecord.value) {
    rxMrTab.value = 'mr';
  }
  const panel = medicalRecordPanelRef.value as any;
  if (panel?.openCiteHistory) {
    panel.openCiteHistory();
    return;
  }
  patientMrDrawerApi.setData({
    mode: 'cite',
    userPatientId: patientId,
    storeId: medicalRecordStoreId.value || undefined,
    patientName: prescriptionStore.activePatient?.name,
    excludeRegisterId: medicalRecordRegisterId.value,
    onCite: (record: Record<string, any>) => {
      panel?.applyCitedRecord?.(record);
      if (record?.diagnosis) prescriptionStore.diagnosis = String(record.diagnosis);
      if (record?.doctor_order) prescriptionStore.medicalAdvice = String(record.doctor_order);
    },
  });
  patientMrDrawerApi.open();
}

/**
 * 在线开方复用历史处方：拉取详情写入 store 草稿
 */
async function reusePrescriptionFromList(prescriptionId: number) {
  const go = async () => {
    try {
      const detail = await getPrescriptionInfoApi(prescriptionId);
      const content =
        typeof detail?.content === 'string'
          ? JSON.parse(detail.content || '{}')
          : detail?.content || detail || {};
      const pt = Number(detail.prescription_type);
      if (![1, 2, 3, 5, 6, 7].includes(pt)) {
        message.warning('该处方类型暂不支持复用');
        return;
      }
      prescriptionStore.activeCategory = pt;
      const repiceList = Array.isArray(content.repice) ? content.repice : [];
      if (pt === 1) {
        const rep0 = repiceList[0];
        let rows: any[] = [];
        try {
          const raw = rep0?.content;
          rows = typeof raw === 'string' ? JSON.parse(raw) : raw || [];
        } catch {
          message.error('解析中药处方失败');
          return;
        }
        prescriptionStore.updateCurrentDrugs(
          (rows || []).map((d: any) => {
            const drugId = Number(d.drug_id ?? d.id);
            return {
              index_id: d.id ?? drugId,
              id: drugId,
              drug_name: d.name || d.drug_name || '',
              number: Number(d.number ?? d.amount ?? 0),
              way_id: d.way_id ?? d.use_way?.id ?? d.order,
              price: Number(d.price ?? d.sell_price ?? 0),
              unit: d.unit,
            };
          }),
        );
        if (rep0?.dosage != null) prescriptionStore.dosage = Number(rep0.dosage) || prescriptionStore.dosage;
        if (rep0?.day_dosage != null) {
          prescriptionStore.dayDosage = Number(rep0.day_dosage) || prescriptionStore.dayDosage;
        }
      } else {
        const mapped: any[] = [];
        for (const rep of repiceList) {
          let drugs: any[] = [];
          try {
            const raw = rep?.content;
            drugs = typeof raw === 'string' ? JSON.parse(raw) : raw || [];
          } catch {
            continue;
          }
          for (const d of drugs) {
            mapped.push({
              index_id: d.id ?? d.drug_id,
              id: Number(d.drug_id ?? d.id),
              drug_name: d.name || d.drug_name || '',
              number: Number(d.number ?? 1),
              price: Number(d.price ?? d.sell_price ?? 0),
              unit: d.unit,
              use_num: d.use_num,
              use_type: d.use_type,
              use_frequency: d.use_frequency,
              time_id: d.time_id,
              type_id: d.type_id,
              frequency_id: d.frequency_id,
              unit_id: d.unit_id,
              select_number: d.select_number ?? 1,
            });
          }
        }
        prescriptionStore.updateCurrentDrugs(mapped);
      }
      prescriptionStore.diagnosis =
        detail.clinical_diagnose ?? content.clinical_diagnose ?? '';
      prescriptionStore.medicalAdvice =
        content.doctor_order ?? detailDoctorOrderToText(detail.doctor_order) ?? '';
      prescriptionStore.category =
        detail.category === 2 || detail.category === '2' || content.category === '医保'
          ? 2
          : 1;
      message.success('已复用到开方区，请核对后发送');
    } catch (e) {
      console.error(e);
      message.error('加载处方详情失败');
    }
  };
  if (prescriptionStore.currentDrugs.length > 0) {
    AntModal.confirm({
      title: '覆盖当前草稿？',
      content: '当前处方清单中有药品，复用将替换为所选历史处方内容。',
      onOk: go,
    });
  } else {
    await go();
  }
}

function openPatientRxHistoryDrawer() {
  patientRxHistoryDrawerApi.setData({
    registerId: medicalRecordRegisterId.value,
    userPatientId: medicalRecordPatientId.value,
    patientName: prescriptionStore.activePatient?.name,
    allowWithdraw: false,
    onReuse: reusePrescriptionFromList,
  });
  patientRxHistoryDrawerApi.open();
}

// 打开西药模态框
const openWesternModal = () => {
  // 获取存储前缀，从modalData或使用默认值
  const storagePrefix = modalData.value?.storagePrefix || 'onlineConsultation-';

  // 判断是否为简单产品类型（3,5,6,7）
  const simpleProductTypes = [3, 5, 6, 7];
  if (simpleProductTypes.includes(prescriptionStore.activeCategory)) {
    // 使用简单产品模态框
    SimpleProductModalApi.setData({
      values: prescriptionStore.activeCategory,
      isChat: 'chat',
      activePatient_id: prescriptionStore.currentRegisterId,
      getCurrentDrugs: () => {
        // 这里可以添加获取当前药品的逻辑
      },
      storagePrefix: storagePrefix, // 使用动态前缀
    });
    SimpleProductModalApi.open();
  } else {
    // 使用原有的西药/中药模态框
    WesternDrugModalApi.setData({
      values: prescriptionStore.activeCategory,
      isChat: 'chat',
      activePatient_id: prescriptionStore.currentRegisterId,
      getCurrentDrugs: () => {
        // 这里可以添加获取当前药品的逻辑
      },
      storagePrefix: storagePrefix, // 使用动态前缀
    });
    WesternDrugModalApi.open();
  }
};

// 打开处方详情模态框
const openPrescriptionDetail = (prescription: any) => {
  PrescriptionDetailModalApi.setData({
    values: prescription.id,
  });
  PrescriptionDetailModalApi.open();
};

/**
 * 拆选
 * @param input
 * @param option
 */
const filterOption = (input: string, option: any) => {
  return (
    option.initials_of_pinyin.includes(input) ||
    option.name.includes(input) ||
    option.alias.includes(input) ||
    option.code.includes(input)
  );
};

// ==================== 选择常用方相关方法 ====================

/**
 * 打开常用方选择弹窗
 * @description 打开常用方弹窗，选择后自动填充药品到处方中
 */
function openCommonPrescriptionModal() {
  if (!canUseCommonPrescription.value) {
    message.warning('当前分类不支持选择常用方');
    return;
  }
  CommonPrescriptionModalApi.setData({
    type: prescriptionStore.activeCategory,
    onSelect: handleSelectCommonPrescription,
  });
  CommonPrescriptionModalApi.open();
}

/**
 * 打开金方导入（VIP：golden_formula）；仅中药处方可用
 */
function openGoldenFormulaModal() {
  if (Number(prescriptionStore.activeCategory) !== 1) {
    message.warning('金方仅支持中药处方');
    return;
  }
  if (!canUseGoldenFormula.value) {
    message.warning('当前门店未开通金方 VIP 功能');
    return;
  }
  GoldenFormulaModalApi.setData({
    storeId: medicalRecordStoreId.value,
    registerId: medicalRecordRegisterId.value,
    category: prescriptionStore.activeCategory,
  });
  GoldenFormulaModalApi.open();
}

/**
 * 金方确认导入：整表覆盖当前处方药品（与 PC 接诊 AI/金方一致）
 */
function handleImportGoldenFormula(payload: { rows?: any[]; formulaName?: string }) {
  const list = Array.isArray(payload?.rows) ? payload.rows : [];
  if (!list.length) {
    message.warning('没有可导入的药品');
    return;
  }
  const resolveWayId = (usage: string) => {
    const u = String(usage || '').trim();
    if (!u) return 0;
    const found = (prescriptionStore.drugUseWay || []).find(
      (w: any) =>
        String(w.name || '') === u || String(w.name || '').includes(u),
    );
    return found ? Number(found.id || 0) : 0;
  };
  const next: any[] = [];
  for (const row of list) {
    const c = row?.candidate || {};
    const drugId = Number(c.drug_id || 0);
    if (!drugId) continue;
    if (next.find((item: any) => Number(item.id) === drugId)) continue;
    const doseNum = parseFloat(row.dose);
    const qty = !Number.isNaN(doseNum) && doseNum > 0 ? doseNum : 1;
    const drug = c.drug || {};
    if (prescriptionStore.activeCategory === 1) {
      const wayId = resolveWayId(row.usage || '');
      next.push({
        index_id: c.id || drugId,
        id: drugId,
        drug_name: c.drug_name || row.ai_name,
        number: qty,
        price: parseFloat(c.price) || 0,
        way_id: wayId,
        use_ways: (prescriptionStore.drugUseWay || []).find(
          (item: any) => item.id === wayId,
        ),
        select_number: 1,
        unit: c.unit || { id: 0, name: row.unit || 'g' },
      });
      continue;
    }
    next.push({
      index_id: c.id || drugId,
      id: drugId,
      drug_name: c.drug_name || drug.drug_name || row.ai_name,
      number: qty,
      select_number: qty,
      price: parseFloat(c.price) || 0,
      image: c.image || drug.image || '',
      instruction: drug.instruction || '',
      time_id: c.time_id || drug.time_id || 0,
      type_id: c.type_id || drug.type_id || 0,
      frequency_id: c.frequency_id || drug.frequency_id || 0,
      unit_id: c.unit_id || drug.unit_id || 0,
      type: 2,
    });
  }
  if (!next.length) {
    message.warning('没有可写入的已匹配药品');
    return;
  }
  prescriptionStore.currentDrugs = next;
}

/**
 * 处理选择常用方
 * @param data 常用方数据，包含prescription和recipes
 * @param type 类型：1-西药，2-中药，3-颗粒药
 * @description 选择常用方后，将药品列表填充到当前处方中
 */
async function handleSelectCommonPrescription(data: any, type: number) {
  const { prescription, recipes } = data;

  // 根据类型处理不同的药品数据
  if (type === 1) {
    // 西药处方
    recipes.forEach((recipe: any) => {
      const newProduct = {
        index_id: recipe.drug_id || recipe.id,
        id: recipe.drug_id || recipe.id,
        drug_name: recipe.drug_name,
        number: recipe.number || 1,
        use_num: recipe.use_time,
        use_type: recipe.use_type,
        use_frequency: recipe.use_frequency,
        unit: recipe.west_unit,
        price: recipe.price || 0,
        time_id: recipe.time_id,
        type_id: recipe.type_id,
        frequency_id: recipe.frequency_id,
        unit_id: recipe.unit_id,
        image: recipe.image,
        specification: recipe.specification || recipe.drug?.specification || '',
        instruction: recipe.instruction,
        type: recipe.type,
        select_number: recipe.select_number || 1,
      };
      // 检查是否已存在
      const existItem = prescriptionStore.currentDrugs.find(
        (item: any) => item.id === newProduct.id,
      );
      if (!existItem) {
        prescriptionStore.currentDrugs.push(newProduct);
      }
    });
  } else {
    // 中药/颗粒药处方
    recipes.forEach((recipe: any) => {
      const newProduct = {
        index_id: recipe.drug_id || recipe.id,
        id: recipe.drug_id || recipe.id,
        drug_name: recipe.drug_name || recipe.name,
        number: recipe.number || 1,
        price: recipe.price || 0,
        buy_price: recipe.buy_price,
        way_id: recipe.way_id || 0,
        specification: recipe.specification || recipe.drug?.specification || '',
        select_number: 1,
      };
      // 检查是否已存在
      const existItem = prescriptionStore.currentDrugs.find(
        (item: any) => item.id === newProduct.id,
      );
      if (!existItem) {
        prescriptionStore.currentDrugs.push(newProduct);
      }
    });

    // 写入规则类型和剂量信息（中药）- 使用 ?? 运算符提供默认值
    prescriptionStore.ruleType = prescription.rule_type ?? 1;
    prescriptionStore.dosage = prescription.dosage ?? 7;
    prescriptionStore.dayDosage = prescription.day_dosage ?? 2;
    prescriptionStore.packageMethodId = prescription.package_method_id ?? 2;

    // 如果是委托调剂，写入完整加工规则配置 - 只有有效值才写入（大于0），级联加载
    if (prescription.process_rule_id && prescription.process_rule_id > 0) {
      prescriptionStore.processRuleId = prescription.process_rule_id;
      // 加载煎法选项
      await prescriptionStore.getProcessRuleListData(prescription.process_rule_id, 0);
    }
    if (prescription.child_process_rule_id && prescription.child_process_rule_id > 0) {
      prescriptionStore.childProcessRuleId = prescription.child_process_rule_id;
      // 加载备注选项
      await prescriptionStore.getProcessRuleListData(0, prescription.child_process_rule_id);
    }
    if (prescription.process_rule_note_id && prescription.process_rule_note_id > 0) {
      prescriptionStore.processRuleNoteId = prescription.process_rule_note_id;
    }
  }

  // 更新诊断和医嘱 - 允许空字符串覆盖
  if (prescription.clinical_diagnose !== undefined && prescription.clinical_diagnose !== null) {
    prescriptionStore.diagnosis = prescription.clinical_diagnose;
  }
  if (prescription.doctor_order !== undefined && prescription.doctor_order !== null) {
    prescriptionStore.medicalAdvice = prescription.doctor_order;
  }

  // 保存到本地存储
  prescriptionStore.syncToLocalStorage();
  message.success('已选择常用方，药品已填充到处方中');
}

// ==================== 保存常用方相关方法 ====================

/**
 * 打开保存常用方弹窗
 * @description 检查是否有药品可保存，然后打开弹窗
 */
const openSaveCommonPrescriptionModal = () => {
  if (!canUseCommonPrescription.value) {
    message.warning('当前分类不支持保存为常用方');
    return;
  }
  // 检查是否有药品
  if (prescriptionStore.currentDrugs.length === 0) {
    message.warning('请先添加药品后再保存为常用方');
    return;
  }
  // 清空输入框
  commonPrescriptionName.value = '';
  // 打开弹窗
  showSaveCommonPrescriptionModal.value = true;
};

/**
 * 处理DrugSearchSelect组件的select事件（用于新类型：3,5,6,7）
 * @param drug 选中的药品数据
 */
function handleSimpleProductSelect(drug: any) {
  // 检查是否已存在
  const existItem = prescriptionStore.currentDrugs.find(
    (item: any) => item.id === (drug._drugId || drug.drug_id || drug.drug?.id),
  );

  if (existItem) {
    message.warning('该商品已在列表中');
    return;
  }

  // 创建新的商品对象（简化版，不需要用法用量字段）
  const newProduct = {
    index_id: drug._id || drug.id,
    id: drug._drugId || drug.drug_id || drug.drug?.id,
    drug_name: drug._drugName || drug.drug?.drug_name || drug.drug_name,
    number: 1,
    price: drug._price || drug.price,
    image: drug._image || drug.drug?.image || drug.image,
    // 规格（选仓弹窗等处展示）
    specification:
      drug._specification ||
      drug.drug?.specification ||
      drug.specification ||
      '',
    instruction: drug.drug?.instruction || drug.instruction || '',
    type: drug.drug?.type || drug.type || prescriptionStore.activeCategory,
    select_number: 1,
  };

  // 添加到选中列表
  prescriptionStore.currentDrugs.push(newProduct);

  // 更新本地存储
  prescriptionStore.syncToLocalStorage();

  // 提示成功
  message.success(`已将${newProduct.drug_name}添加到清单中！`);
}

/**
 * 保存当前处方为常用方
 * @description 根据当前药品类型（中药/西药）调用不同的保存接口
 * 后端会自动根据药品详细信息创建 recipe 记录
 */
const saveAsCommonPrescription = async () => {
  // 验证名称
  if (!commonPrescriptionName.value.trim()) {
    message.warning('请输入常用方名称');
    return;
  }

  // 验证是否有药品
  if (prescriptionStore.currentDrugs.length === 0) {
    message.warning('没有可保存的药品');
    return;
  }

  if (!canUseCommonPrescription.value) {
    message.warning('当前分类不支持保存为常用方');
    return;
  }

  isSavingCommonPrescription.value = true;

  try {
    // 根据处方类型选择不同的保存接口
    if (prescriptionStore.activeCategory === 1) {
      // 中药处方 - 构建药品详细信息数组
      const drugs = prescriptionStore.currentDrugs.map((drug) => ({
        drug_id: drug.id,
        drug_name: drug.drug_name,
        number: drug.number || 1,
        price: drug.price || 0,
        way_id: drug.way_id || 0,
      }));

      await saveChineseCommonPrescriptionApi({
        name: commonPrescriptionName.value.trim(),
        drugs,
        store_id: prescriptionStore.myStoreId,
        clinical_diagnose: prescriptionStore.diagnosis || '',
        doctor_order: prescriptionStore.medicalAdvice || '',
        category: String(prescriptionStore.category),
        dosage: prescriptionStore.dosage || 7,
        day_dosage: prescriptionStore.dayDosage || 2,
      });
    } else {
      // 西药（中成药）处方 - 构建药品详细信息数组
      const drugs = prescriptionStore.currentDrugs.map((drug) => ({
        drug_id: drug.id,
        drug_name: drug.drug_name,
        number: drug.number || 1,
        select_number: drug.select_number || 1,
        price: drug.price || 0,
        time_id: drug.time_id || 0,
        type_id: drug.type_id || 0,
        frequency_id: drug.frequency_id || 0,
        unit_id: drug.unit_id || 0,
        image: drug.image || '',
        instruction: drug.instruction || '',
        use_num: drug.use_num,
        use_type: drug.use_type,
        use_frequency: drug.use_frequency,
        unit: drug.unit,
      }));

      await saveWestCommonPrescriptionApi({
        name: commonPrescriptionName.value.trim(),
        drugs,
        store_id: prescriptionStore.myStoreId,
        clinical_diagnose: prescriptionStore.diagnosis || '',
        doctor_order: prescriptionStore.medicalAdvice || '',
        category: String(prescriptionStore.category),
      });
    }

    message.success('常用方保存成功');
    showSaveCommonPrescriptionModal.value = false;
    commonPrescriptionName.value = '';
  } catch (error) {
    console.error('保存常用方失败:', error);
    message.error('保存常用方失败，请稍后重试');
  } finally {
    isSavingCommonPrescription.value = false;
  }
};

/**
 * 取消保存常用方
 */
const cancelSaveCommonPrescription = () => {
  showSaveCommonPrescriptionModal.value = false;
  commonPrescriptionName.value = '';
};
</script>

<template>
  <Modal class="w-[90%]" title="电子处方">
    <Spin :spinning="contentLoading || prescriptionStore.prescriptionTypeLoading">
    <!-- 主容器：左右布局 -->
    <div class="prescription-module flex h-[calc(80vh-60px)] gap-4 overflow-hidden">
      <!-- 说明书预览 (保持隐藏逻辑) -->
      <div style="width: 0; height: 0; overflow: hidden">
        <ImagePreviewGroup
          :preview="{ visible, onVisibleChange: setVisible }"
          :style="{ display: 'none' }"
        >
          <Image
            v-for="image in previewImage"
            v-if="visible === true"
            :key="image"
            :src="image"
            :width="200"
          />
        </ImagePreviewGroup>
      </div>

      <!-- 开方工作台：顶栏固定，下方内容独立滚动 -->
      <div class="right-panel rx-workspace flex-1 h-full px-2">
        <div class="rx-workspace-sticky">
        <PatientBriefBar
          :register="prescriptionStore.patientInfo"
          :patient="prescriptionStore.activePatient"
          :category="prescriptionStore.category"
          :store-name="prescriptionStore.targetStoreName || prescriptionStore.currentStoreName"
          :is-online="true"
        />
        <Tabs
          v-model:active-key="rxMrTab"
          class="mb-0 rx-primary-tabs"
        >
          <TabPane key="rx" tab="处方" />
          <TabPane v-if="canUseMedicalRecord" key="mr" tab="病历" />
          <template #rightExtra>
            <div class="rx-tab-extra-actions">
              <Button type="link" size="small" @click="openPatientInfoDrawer">
                <UserOutlined />
                患者信息
              </Button>
              <Button type="link" size="small" @click="openPatientMrCiteDrawer">
                <FileTextOutlined />
                患者病历
              </Button>
              <Button type="link" size="small" @click="openPatientRxHistoryDrawer">
                <MedicineBoxOutlined />
                处方记录
              </Button>
            </div>
          </template>
        </Tabs>

        <!-- 处方工具栏：仅处方态吸顶 -->
        <div
          v-if="!canUseMedicalRecord || rxMrTab === 'rx'"
          class="mb-1 flex flex-wrap items-center gap-1"
        >
          <RadioGroup
            v-if="allowInsuranceCategory"
            v-model:value="prescriptionStore.category"
            size="small"
          >
            <RadioButton :value="1">自费</RadioButton>
            <RadioButton :value="2">医保</RadioButton>
          </RadioGroup>
          <Button
            v-if="canUseCommonPrescription"
            type="link"
            size="small"
            @click="openCommonPrescriptionModal"
          >
            <BookOutlined />
            选择常用方
          </Button>
          <Button
            v-if="prescriptionStore.activeCategory === 1 && canUseGoldenFormula"
            type="link"
            size="small"
            @click="openGoldenFormulaModal"
          >
            <MedicineBoxOutlined />
            导入金方
          </Button>
          <Button
            v-if="canUseAiPrescription"
            type="link"
            size="small"
            @click="openAiPrescriptionDrawer"
          >
            <RobotOutlined />
            AI辅助出方
          </Button>
          <Button
            v-if="canUseCommonPrescription"
            type="link"
            size="small"
            @click="openSaveCommonPrescriptionModal"
          >
            <SaveOutlined />
            保存常用方
          </Button>
          <Button
            v-if="prescriptionStore.activeCategory === 2"
            type="link"
            size="small"
            @click="openWesternModal"
          >
            <PlusOutlined />
            添加商品
          </Button>
        </div>

        <!-- 病历工具栏：仅病历态吸顶 -->
        <div
          v-if="canUseMedicalRecord && rxMrTab === 'mr'"
          class="mb-1 flex flex-wrap items-center gap-1"
        >
          <Button
            type="link"
            size="small"
            danger
            @click="medicalRecordPanelRef?.clear?.()"
          >
            <ClearOutlined />
            清空病历
          </Button>
          <Button
            type="link"
            size="small"
            @click="medicalRecordPanelRef?.openCiteHistory?.()"
          >
            <HistoryOutlined />
            引用历史病历
          </Button>
          <Button
            v-if="canUseAiMedicalRecord"
            type="link"
            size="small"
            @click="openAiMedicalRecord"
          >
            <RobotOutlined />
            AI写病历
          </Button>
          <Button
            type="link"
            size="small"
            @click="medicalRecordPanelRef?.save?.()"
          >
            <SaveOutlined />
            保存病历
          </Button>
        </div>
        </div>
        <!-- /rx-workspace-sticky -->

        <div class="rx-workspace-scroll">
        <div v-show="!canUseMedicalRecord || rxMrTab === 'rx'">
        <!-- 二级 Tab：处方类型，随内容滚动，病历不展示 -->
        <Tabs
          :active-key="String(prescriptionStore.activeCategory)"
          class="rx-secondary-tabs mb-2"
          size="small"
          @change="(key) => tabChange(Number(key))"
        >
          <TabPane
            v-for="categoryItem in categories"
            :key="String(categoryItem.value)"
          >
            <template #tab>
              <span
                :id="`rx-modal-tab-${categoryItem.value}`"
                class="rx-secondary-tab-label"
              >
                <img
                  v-if="categoryItem.icon"
                  class="tab-type-icon"
                  :src="categoryItem.icon"
                  alt=""
                />
                <span>{{ categoryItem.label }}</span>
                <span
                  v-if="categoryItem.icon_text"
                  class="tab-type-badge"
                >{{ categoryItem.icon_text }}</span>
              </span>
            </template>
          </TabPane>
        </Tabs>
        <div class="rx-swipe-panel">

        <!-- 中药：顶部固定展示已选种数 -->
        <div
          v-if="prescriptionStore.activeCategory === 1"
          class="mb-3 mt-2 text-base font-medium text-gray-700"
        >
          已选 {{ prescriptionStore.currentDrugs.length }} 种药
        </div>
        <!-- 中药药品列表 -->
        <div
          v-if="prescriptionStore.activeCategory === 1"
          class="mb-5 mt-3 flex"
          style="flex-wrap: wrap; width: 100%"
        >
          <Row :gutter="[16, 16]" class="w-full">
            <Col
              v-for="(drug, index) in prescriptionStore.currentDrugs"
              :key="drug.id"
              :span="12"
              :xl="8"
              :xxl="6"
            >
              <Card class="prescription-card mt-0" title="">
                <div>
                  <span class="card-index">{{ index + 1 }}、</span>
                  <p>
                    <ChineseDrugNameBubble
                      :display-name="drug.drug_name"
                      :store-id="prescriptionStore.myStoreId"
                      :register-id="Number(prescriptionStore.currentRegisterId || 0)"
                      :type="1"
                      compact
                      input-class="old-select-drug-name"
                      placeholder="药名"
                      @select="
                        (item) =>
                          prescriptionStore.onSelectOldChineseDrug(index, item)
                      "
                    />
                    ,
                    <InputNumber
                      v-model:value="drug.number"
                      :class="`old-number-input-${index}`"
                      :controls="false"
                      style="width: 80px; min-width: 80px"
                      @blur="prescriptionStore.updateChineseNumber"
                      @keydown="
                          prescriptionStore.updateChineseNumberGoNewDrug($event)
                        "
                    >
                      <template #addonAfter>{{ drug.unit?.name || 'g' }}</template>
                    </InputNumber>
                    ,
                    <Select
                      :value="drug?.way_id"
                      placeholder="用法"
                      style="width: 88px; min-width: 72px"
                      @change="prescriptionStore.selectDrugUseWayChange"
                      @dropdown-visible-change="
                          prescriptionStore.selectProductChange(drug.index_id)
                        "
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(
                            value, wayIndex
                          ) in prescriptionStore.drugUseWay"
                        :key="wayIndex"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>
                  </p>
                  <p class="card-price">
                    ￥<span>{{ (drug.price * drug.number).toFixed(2) }}</span>
                    <span
                      v-if="prescriptionStore.getChineseItemMargin(drug) && prescriptionStore.getChineseItemMargin(drug) !== '--'"
                      class="ml-2 text-gray-500 text-sm"
                    >
                      毛利率 {{ prescriptionStore.getChineseItemMargin(drug) }}%
                    </span>
                  </p>
                  <Button
                    class="card-delete"
                    type="link"
                    @click="prescriptionStore.removeDrug(index)"
                  >
                    <DeleteTwoTone />
                  </Button>
                </div>
              </Card>
            </Col>

            <!-- 新增药品卡片 -->
            <Col :span="12" :xl="8" :xxl="6">
              <Card class="prescription-card" title="">
                <div>
                  <span class="card-index">{{ prescriptionStore.currentDrugs.length + 1 }}、</span>
                  <div>
                    <ChineseDrugNameBubble
                      :display-name="prescriptionStore.newDrugInfo.name || ''"
                      :store-id="prescriptionStore.myStoreId"
                      :register-id="Number(prescriptionStore.currentRegisterId || 0)"
                      :type="1"
                      compact
                      input-class="new-select-drug-name"
                      placeholder="药名"
                      @select="prescriptionStore.onSelectNewChineseDrug"
                    />
                    ,
                    <InputNumber
                      v-model:value="prescriptionStore.newDrugInfo.number"
                      class="new-number-input"
                      style="width: 80px; min-width: 80px"
                      @blur="newDrugBlur"
                      @keydown="
                          prescriptionStore.selectDrugByNewDrugInfo($event, true)
                        "
                    >
                      <template #addonAfter>{{ prescriptionStore.newDrugInfo.unit?.name || 'g' }}</template>
                    </InputNumber>
                    ,
                    <Select
                      v-model:value="prescriptionStore.newDrugInfo.way_id"
                      placeholder="用法"
                      style="width: 88px; min-width: 72px"
                      @keydown="
                          prescriptionStore.selectDrugByNewDrugInfo($event, true)
                        "
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(
                            value, wayIndex
                          ) in prescriptionStore.drugUseWay"
                        :key="wayIndex"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>

                    <p class="card-price">
                      ￥<span>{{
                        (
                          (prescriptionStore.newDrugInfo.price || 0) *
                          (prescriptionStore.newDrugInfo.number || 1)
                        ).toFixed(2)
                      }}元</span>
                    </p>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>
        </div>

        <!-- 西（中成）药列表（type=2） -->
        <div v-else-if="prescriptionStore.activeCategory === 2" class="selected-drugs">
          <div class="drug-table">
            <div class="table-header">
              <span>商品图片</span>
              <span>商品名称</span>
              <span>数量</span>
              <span>单价</span>
              <span>操作</span>
            </div>
            <div class="table-body">
              <div
                v-for="(drug, index) in prescriptionStore.currentDrugs"
                :key="drug.id"
                class="table-row"
              >
                <div style="width: 120px; margin: 0 auto">
                  <Image :src="drug.image" />
                </div>
                <div>
                  <p>
                    <span>药品名称：{{ drug.drug_name }}</span>
                  </p>
                  <!-- 西药用法显示/编辑模式 -->
                  <p v-if="prescriptionStore.activeCategory !== 1 && !drug.isEditing">
                    <span>用法：{{
                        `${drug.use_type?.name}，${drug.use_frequency?.name}，${drug.use_num?.name}，每次${drug.number}${drug.unit?.name}`
                      }}</span>
                  </p>
                  <div v-else-if="prescriptionStore.activeCategory !== 1 && drug.isEditing" class="edit-usage-form flex flex-wrap gap-2">
                    <span class="w-full text-left">用法：</span>
                    <Select
                      :value="drug.use_type?.id"
                      size="small"
                      style="width: 80px"
                      @change="(val) => prescriptionStore.updateDrugUsage(index, 'use_type', prescriptionStore.drugUseType.find(item => item.id === val))"
                    >
                      <SelectOption v-for="item in prescriptionStore.drugUseType" :key="item.id" :value="item.id">
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                    <Select
                      :value="drug.use_frequency?.id"
                      size="small"
                      style="width: 100px;"
                      @change="(val) => prescriptionStore.updateDrugUsage(index, 'use_frequency', prescriptionStore.drugUseFrequency.find(item => item.id === val))"
                    >
                      <SelectOption v-for="item in prescriptionStore.drugUseFrequency" :key="item.id" :value="item.id">
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                    <Select
                      :value="drug.use_num?.id"
                      size="small"
                      style="width: 80px;"
                      @change="(val) => prescriptionStore.updateDrugUsage(index, 'use_num', prescriptionStore.drugTime.find(item => item.id === val))"
                    >
                      <SelectOption v-for="item in prescriptionStore.drugTime" :key="item.id" :value="item.id">
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                    <span>每次</span>
                    <InputNumber
                      :value="drug.number"
                      :min="1"
                      size="small"
                      style="width: 60px;"
                      @change="(val) => prescriptionStore.updateDrugUsage(index, 'number', val)"
                    />
                    <Select
                      :value="drug.unit?.id"
                      size="small"
                      style="width: 60px;"
                      @change="(val) => prescriptionStore.updateDrugUsage(index, 'unit', prescriptionStore.drugUnit.find(item => item.id === val))"
                    >
                      <SelectOption v-for="item in prescriptionStore.drugUnit" :key="item.id" :value="item.id">
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                  </div>
                </div>
                <div>
                  <div class="quantity-control">
                    <Button
                      type="primary"
                      @click="prescriptionStore.decrement(index)"
                    >
                      <MinusOutlined />
                    </Button>
                    <span style="margin: 0 10px">{{ drug.select_number }}</span>
                    <Button
                      type="primary"
                      @click="prescriptionStore.increment(index)"
                    >
                      <PlusOutlined />
                    </Button>
                  </div>
                </div>
                <span>{{ drug.price }}</span>
                <div class="flex flex-col items-center">
                  <!-- 西药编辑/保存按钮 -->
                  <Button
                    v-if="prescriptionStore.activeCategory !== 1 && !drug.isEditing"
                    type="link"
                    @click="prescriptionStore.toggleEditDrug(index)"
                  >
                    编辑
                  </Button>
                  <Button
                    v-if="prescriptionStore.activeCategory !== 1 && drug.isEditing"
                    type="link"
                    @click="prescriptionStore.saveEditDrug(index)"
                  >
                    保存
                  </Button>
                  <Button
                    type="link"
                    danger
                    @click="prescriptionStore.removeDrug(index)"
                  >
                    删除
                  </Button>
                  <Button
                    v-if="drug.instruction !== ''"
                    type="link"
                    @click="setVisible(true, drug.instruction)"
                  >
                    查看说明书
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 简单产品列表（type=3,5,6,7：保健食品、产品服务包、非药品、医疗器械） -->
        <div v-else-if="[3, 5, 6, 7].includes(prescriptionStore.activeCategory)" class="selected-drugs">
          <!-- 搜索组件 -->
          <div class="mb-5">
            <DrugSearchSelect
              :type="prescriptionStore.activeCategory"
              :store-id="prescriptionStore.myStoreId"
              :register-id="Number(prescriptionStore.currentRegisterId) || undefined"
              :placeholder="`输入${categories.find(c => c.value === prescriptionStore.activeCategory)?.label || '商品'}名称搜索`"
              @select="handleSimpleProductSelect"
            />
          </div>
          <!-- 已选商品列表（表格形式，与西药一致） -->
          <div class="drug-table">
            <div class="table-header">
              <span>商品图片</span>
              <span>商品名称</span>
              <span>数量</span>
              <span>单价</span>
              <span>操作</span>
            </div>
            <div class="table-body">
              <div
                v-for="(drug, index) in prescriptionStore.currentDrugs"
                :key="drug.id"
                class="table-row"
              >
                <div style="width: 120px; margin: 0 auto">
                  <Image :src="drug.image"/>
                </div>
                <div>
                  <p>
                    <span>药品名称：{{ drug.drug_name }}</span>
                  </p>
                </div>
                <div>
                  <div class="quantity-control">
                    <Button type="primary" @click="prescriptionStore.decrement(index)">-</Button>
                    <span style="margin: 0 20px">{{ drug.select_number }}</span>
                    <Button type="primary" @click="prescriptionStore.increment(index)">+</Button>
                  </div>
                </div>
                <span>{{ drug.price }}</span>
                <div>
                  <Button type="link" danger @click="prescriptionStore.removeDrug(index)">删除</Button>
                  <Button
                    v-if="drug.instruction !== ''"
                    type="link"
                    @click="setVisible(true, drug.instruction)"
                  >
                    查看说明书
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 诊断和医嘱区域 -->
        <div class="diagnosis-area bg-gray-50 dark:bg-[#1f1f1f] p-4 rounded-lg">
          <!-- 中医证候：新搜索气泡，写入旧字段 diseasesSelected(id) -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mr-field-head mb-2">
              <label class="mr-field-label font-medium">中医证候</label>
              <div class="mr-field-search">
                <EntryKeywordBubble
                  source="tcm_disease"
                  placeholder="证候关键字/首拼"
                  compact
                  @select="(item) => onPickOnlineTcm('diseases', item)"
                />
              </div>
            </div>
            <div class="text-sm text-gray-700">
              {{ diseasesSelectedLabel || '请通过搜索选择中医证候' }}
            </div>
          </div>
          <!-- 中医治法：写入 methodSelected(id) -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mr-field-head mb-2">
              <label class="mr-field-label font-medium">中医治法</label>
              <div class="mr-field-search">
                <EntryKeywordBubble
                  source="tcm_method"
                  placeholder="治法关键字/首拼"
                  compact
                  @select="(item) => onPickOnlineTcm('method', item)"
                />
              </div>
            </div>
            <div class="text-sm text-gray-700">
              {{ methodSelectedLabel || '请通过搜索选择中医治法' }}
            </div>
          </div>
          <!-- 中医疾病：写入 syndromeSelected(id) -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mr-field-head mb-2">
              <label class="mr-field-label font-medium">中医疾病</label>
              <div class="mr-field-search">
                <EntryKeywordBubble
                  source="tcm_syndrome"
                  placeholder="疾病关键字/首拼"
                  compact
                  @select="(item) => onPickOnlineTcm('syndrome', item)"
                />
              </div>
            </div>
            <div class="text-sm text-gray-700">
              {{ syndromeSelectedLabel || '请通过搜索选择中医疾病' }}
            </div>
          </div>
          <!-- 诊断输入：搜索贴 label 后，与病历同源 -->
          <div class="mb-3">
            <div class="mr-field-head mb-2">
              <label class="mr-field-label font-medium">诊断</label>
              <div class="mr-field-search">
                <EntryKeywordBubble
                  source="diagnosis"
                  placeholder="诊断关键字"
                  compact
                  @select="(item) => onPickDiagnosis(item.content || item.title)"
                />
              </div>
            </div>
            <Textarea
              v-model:value="prescriptionStore.diagnosis"
              disabled
              placeholder="请通过搜索或下方常用诊断选择..."
              :rows="2"
            />
            <CommonDxOrderChips
              source="diagnosis"
              @select="onPickDiagnosis"
            />
          </div>

          <!-- 医嘱输入 -->
          <div class="mb-3">
            <div class="mr-field-head mb-2">
              <label class="mr-field-label font-medium">医嘱</label>
              <div class="mr-field-search">
                <EntryKeywordBubble
                  source="doctor_order"
                  placeholder="医嘱关键字"
                  compact
                  @select="(item) => onPickDoctorOrder(item.content || item.title)"
                />
              </div>
            </div>
            <Textarea
              v-model:value="prescriptionStore.medicalAdvice"
              placeholder="输入医嘱..."
              :rows="2"
            />
            <CommonDxOrderChips
              source="doctor_order"
              @select="onPickDoctorOrder"
            />
          </div>

          <ChineseMedicineConfig
            v-if="prescriptionStore.activeCategory === 1"
            :rule-type="prescriptionStore.ruleType"
            :package-method-id="prescriptionStore.packageMethodId"
            :process-rule-id="prescriptionStore.processRuleId"
            :child-process-rule-id="prescriptionStore.childProcessRuleId"
            :process-rule-note-id="prescriptionStore.processRuleNoteId"
            :dosage="prescriptionStore.dosage"
            :day-dosage="prescriptionStore.dayDosage"
            :process-rule-list="prescriptionStore.processRuleList"
            :child-process-rule-list="prescriptionStore.childProcessRuleList"
            :process-rule-note-list="prescriptionStore.processRuleNoteList"
            class="mb-5 border-t pt-4"
            @change="prescriptionStore.handleChineseConfigChange"
          />

          <!-- 诊疗费用 -->
          <div class="mt-3 flex items-center">
            <span class="mr-2">诊疗费用：</span>
            <InputNumber
              v-model:value="prescriptionStore.treatmentPrice"
              placeholder="请输入诊疗价格"
              style="width: 200px"
            >
              <template #addonAfter> /元</template>
            </InputNumber>
          </div>

        </div>

        <!-- 费用总计 -->
        <div class="price-box mb-10">
          <div class="flex justify-end gap-4 font-bold text-base mt-4">
            <div v-if="prescriptionStore.processingFee > 0">
              加工费：¥{{ formatPriceDisplay(prescriptionStore.processingFee) }}
            </div>
            <div>
              商品价格：¥{{ formatPriceDisplay(prescriptionStore.totalProductCost) }}
              <span
                v-if="prescriptionStore.chineseGrossMarginPercent !== null"
                class="ml-3 text-orange-600"
              >
                毛利率 {{ prescriptionStore.chineseGrossMarginPercent }}%
              </span>
            </div>
            <div class="text-red-500">
              总计：¥{{ formatPriceDisplay(prescriptionStore.totalCost) }}
            </div>
          </div>
        </div>
        </div>
        </div>

        <div
          v-if="canUseMedicalRecord"
          v-show="rxMrTab === 'mr'"
          class="medical-record-wrap py-2"
        >
          <MedicalRecordPanel
            ref="medicalRecordPanelRef"
            v-model:diagnosis="diagnosisModel"
            v-model:medical-advice="medicalAdviceModel"
            :register-id="medicalRecordRegisterId"
            :store-id="medicalRecordStoreId"
            :user-patient-id="medicalRecordPatientId"
            :patient-sex="Number(prescriptionStore.activePatient?.sex || 0)"
            :patient-age="Number(prescriptionStore.activePatient?.age || 0)"
            :storage-prefix="medicalRecordStoragePrefix"
            :store-vip="registerSideVip"
            :show-toolbar="false"
            @sync-to-prescription="onMrSyncToPrescription"
            @apply-tcm-ids="onApplyAiTcmIds"
          />
        </div>
        </div>
        <!-- /rx-workspace-scroll -->
      </div>

      <!-- 以下是各种弹窗组件，位置不动 -->
      <!-- 新药品确认模态框 -->
      <AntModal v-model:open="showNewDrugModal" @ok="newDrugModalOk">
        要把【{{ prescriptionStore.newDrugInfo.name }}】添加到清单吗？
      </AntModal>

      <!-- 保存常用方确认模态框 -->
      <AntModal
        v-model:open="showSaveCommonPrescriptionModal"
        title="保存为常用方"
        :confirm-loading="isSavingCommonPrescription"
        @ok="saveAsCommonPrescription"
        @cancel="cancelSaveCommonPrescription"
      >
        <div class="py-4">
          <p class="mb-4 text-gray-600">
            将当前处方（{{ prescriptionStore.currentDrugs.length }}种药品）保存为常用方模板
          </p>
          <div class="flex items-center">
            <span class="mr-2 whitespace-nowrap">常用方名称：</span>
            <Input
              v-model:value="commonPrescriptionName"
              placeholder="请输入常用方名称"
              :maxlength="50"
              allow-clear
            />
          </div>
          <p class="mt-2 text-xs text-gray-400">
            类型：{{ prescriptionStore.activeCategory === 1 ? '中药' : '西药（中成药）' }}
          </p>
        </div>
      </AntModal>

      <!-- 二次签名确认模态框 -->
      <AntModal
        v-model:open="doctorSecondSignModal"
        title="二次签名"
        @ok="doctorSecondSignModalOk"
      >
        <div class="doctor-second-sign-title">有毒：</div>
        <p
          v-for="item in prescriptionStore.checkData.message?.poisonous || []"
          :key="item"
        >
          【{{ item }}】
        </p>
        <div class="doctor-second-sign-title">十八反：</div>
        <p
          v-for="item in prescriptionStore.checkData.message?.opposition || []"
          :key="item"
        >
          【{{ item }}】
        </p>
        <div class="doctor-second-sign-title">十九畏：</div>
        <p
          v-for="item in prescriptionStore.checkData.message?.conflict || []"
          :key="item"
        >
          【{{ item }}】
        </p>
        <p class="mt-5" style="color: red">
          如需继续开方需要二次签名，确认要二次签名吗？
        </p>
      </AntModal>
    </div>
    </Spin>

    <!-- 子模态框组件 - 按照VbenAdmin的方式声明 -->
    <WesternDrugModal />
    <SimpleProductModalComponent />
    <InfoModalComponent />
    <PrescriptionDetailModal />
    <!-- 常用方选择弹窗 -->
    <CommonPrescriptionModals />
    <GoldenFormulaModals @import="handleImportGoldenFormula" />
    <AiPrescriptionDrawer
      ref="aiPrescriptionDrawerRef"
      @import="handleImportAiPrescription"
      @sync-medical-record="handleSyncAiMedicalRecord"
    />
    <!-- 药店开方选配送仓库 -->
    <WarehouseSelectModals @confirm="onWarehouseSelected" />
    <PatientInfoDrawerComp />
    <PatientMrDrawerComp />
    <PatientRxHistoryDrawerComp />
  </Modal>
</template>

<style scoped>
/* 保持原有样式，新增一些布局微调 */
.mr-field-head {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 12px;
  align-items: center;
}
.mr-field-label {
  flex-shrink: 0;
  line-height: 24px;
}
.mr-field-search {
  min-width: 0;
  flex: 1 1 180px;
  max-width: 280px;
}
.rx-tab-extra-actions {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 0 2px;
  align-items: center;
}
.rx-tab-extra-actions :deep(.ant-btn) {
  padding-inline: 6px;
  height: 28px;
}
.rx-primary-tabs :deep(.ant-tabs-nav) {
  margin-bottom: 8px;
}
.rx-workspace {
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  padding: 8px;
}
.rx-workspace-sticky {
  flex-shrink: 0;
  z-index: 12;
  background: hsl(var(--background));
  padding-bottom: 4px;
  border-bottom: 1px solid hsl(var(--border) / 0.6);
}
/* 二级处方类型 Tab：仅作切换导航，内容仍由下方业务区渲染 */
.rx-secondary-tabs :deep(.ant-tabs-nav) {
  margin-bottom: 0;
}
.rx-secondary-tabs :deep(.ant-tabs-content-holder) {
  display: none;
}
.rx-secondary-tab-label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.rx-workspace-scroll {
  flex: 1;
  min-height: 0;
  overflow-x: hidden;
  overflow-y: auto;
  padding-top: 8px;
  padding-bottom: 12px;
}
.doctor-second-sign-title {
  font-size: 16px;
  margin: 10px 0;
  font-weight: bold;
  border-left: 5px solid rgb(55, 71, 162);
  padding-left: 10px;
}

.card-index {
  font-size: 20px;
  font-weight: bold;
  position: absolute;
  left: 10px;
  top: 0;
}

.card-price {
  position: absolute;
  bottom: 10px;
  right: 8px;
  color: red;
}

.card-delete {
  position: absolute;
  top: 3px;
  right: 0;
}

.prescription-card {
  position: relative;
  min-height: 120px;
}
/* 中药卡片：药名/克数/用法同一行，药名气泡锁宽 */
.prescription-card :deep(.chinese-drug-name-bubble) {
  width: 100px !important;
  min-width: 88px !important;
  max-width: 110px !important;
  flex: 0 0 100px !important;
  vertical-align: middle;
}
.prescription-card > div > p,
.prescription-card > div > div {
  white-space: nowrap;
}

.drug-categories {
  display: flex;
  gap: 1rem;
  /* margin: 1rem 0; 已在类中通过 sticky 处理 */
  overflow-x: auto;
  flex-wrap: nowrap;
}

.drug-categories button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 10px;
  cursor: pointer;
  background: transparent;
  color: inherit;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
  white-space: nowrap;
}

.dark .drug-categories button {
  border: 1px solid #333;
}

.drug-categories button.active {
  color: #fff;
  border-color: transparent;
  /* animation: pulse 0.5s; 移除动画，改为简单的激活态，看起来更专业 */
  background: #455cda;
}

.tab-type-icon {
  width: 16px;
  height: 16px;
  object-fit: contain;
}

.tab-type-badge {
  font-size: 11px;
  color: #e6a23c;
  background: #fdf6ec;
  padding: 0 6px;
  border-radius: 4px;
  line-height: 1.4;
}

.rx-swipe-panel {
  touch-action: pan-y;
}

.selected-drugs {
  margin: 1rem 0;
  border: 1px solid #eee;
  border-radius: 8px;
}

.dark .selected-drugs {
  border: 1px solid #333;
}

.table-body {
  max-height: 40vh; /* 增加高度 */
  overflow-y: auto;
}

.table-header {
  display: grid;
  grid-template-columns: 0.5fr 1fr 1fr 1fr 1fr;
  padding: 12px;
  font-weight: bold;
  text-align: center;
  background-color: #fafafa;
}
.dark .table-header {
  background-color: #262626;
}

.table-row {
  display: grid;
  grid-template-columns: 0.5fr 1fr 1fr 1fr 1fr;
  padding: 12px;
  border-bottom: 1px solid #eee;
  text-align: center;
  height: auto;
  align-items: center;
}

.dark .table-row {
  border-bottom: 1px solid #333;
}

.diagnosis-area textarea {
  width: 100%;
  /* height: 100px; 由rows控制 */
  padding: 8px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: transparent;
  color: inherit;
}

.dark .diagnosis-area textarea {
  border: 1px solid #333;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 垂直文字样式 */
.vertical-text {
  writing-mode: vertical-lr;
  letter-spacing: 4px;
}

@media (max-width: 768px) {
  /* 移动端适配 */
  .prescription-module {
    flex-direction: column;
    overflow-y: auto;
    height: auto;
  }

  .left-panel {
    width: 100% !important;
    height: auto;
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .right-panel {
    overflow: hidden;
  }

  .rx-workspace-scroll {
    overflow: visible;
  }

  .drug-categories {
    flex-wrap: wrap;
  }

  .table-header,
  .table-row {
    grid-template-columns: 1fr 1fr 1fr;
  }

  .table-header span:nth-child(4),
  .table-header span:nth-child(5),
  .table-row > span:nth-child(4),
  .table-row > div:nth-child(5) {
    display: none;
  }
}
</style>
