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

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

import {
  DeleteTwoTone,
  MinusOutlined,
  PlusOutlined,
  SaveOutlined,
} from '@ant-design/icons-vue';
import {
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Image,
  ImagePreviewGroup,
  Input,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Modal as AntModal,
  Tag,
  Textarea,
  Timeline,
  TimelineItem, notification,
} from 'ant-design-vue';
import {debounce} from 'lodash-es'; // 或者使用自定义防抖函数

import {getRegisterStatus} from '#/util/tool';
import {
  addWestPrescription, checkChineseMedicineConflictApi,
  endOfDiagnosisApi,
  getDrugUseList,
  getMyStoreListApi,
  getCurrentStoreTypeApi,
  getPatientItem,
  getPatientList,
  getPrescriptionInfoApi,
  getProcessRuleList,
  getProductListDoctorReception,
  receptionApi,
  applySpecialPrescriptionApi,
  switchStoreApi,
  withdrawPrescriptionApi,
} from '#/views/doctor/doctor-reception/api';

import SpecialPrescriptionImportCard from './components/SpecialPrescriptionImportCard.vue';
import DiagnosisModal from './components/DiagnosisModal.vue';
import DoctorOrderModal from './components/DoctorOrderModal.vue';
import PrescriptionDetail from './components/PrescriptionDetail.vue';
import WesternModal from './components/WesternModal.vue';
import SimpleProductModal from './components/SimpleProductModal.vue';
import RefusalOfTreatmentModal
  from "#/views/doctor/doctor-reception/components/RefusalOfTreatmentModal.vue";
// 常用方选择弹窗组件
import CommonPrescriptionModal from './components/CommonPrescriptionModal.vue';
// 确认模态框组件
import ConfirmModal from './components/ConfirmModal.vue';
// 信息提示模态框组件
import InfoModal from '#/components/modal/InfoModal.vue';
// 药品搜索选择组件
import { DrugSearchSelect } from '#/components/drug-search-select';
// 保存常用方API
import {
  saveChineseCommonPrescriptionApi,
  saveWestCommonPrescriptionApi,
} from '#/views/doctor/settings/api';
// 转诊相关
import TransferPrescriptionCard from '#/views/doctor/online-consultation/components/TransferPrescriptionCard.vue';
import SalespersonTransferDrawer from '#/views/doctor/doctor-reception/components/SalespersonTransferDrawer.vue';
import { getTransferPrescriptionByRegisterApi } from '#/views/business/chat/api/transferPrescription';
import { getSalespersonTransferByRegisterApi } from '#/views/business/salesperson-transfer-prescription/api';
import {
  calcItemMarginPercent,
  calcTotalMarginPercent,
  isSeeRateEnabled,
} from '#/utils/chinesePrescriptionMargin';
import OrderPricePercentAdjustDrawer from '#/views/business/order/components/OrderPricePercentAdjustDrawer.vue';
import { useOrderPriceAdjust } from '#/composables/useOrderPriceAdjust';
import {
  applyRatioToDrugs,
  formatPriceDiscountLabel,
  normalizeQuickOptions,
} from '#/utils/pricePercentAdjust';
import { calculateChineseProductPriceLikeBackend } from '#/utils/formatPrice';

interface Patient {
  id: number;
  name: string;
  mobile: string;
  status: number;
  user_patient?: {
    id: number;
    name: string;
    age?: number;
    sex?: number;
    mobile?: string;
  };
  special_prescription_patient_record?: {
    id: number;
    status: number;
    special_prescription_id: number;
    dose_count: number;
    sku_id?: number;
    sku_name?: string;
    special_prescription?: {
      id: number;
      name: string;
      cover_image?: string;
    };
  };
}

interface UserPatientHealthInquiry {
  id: number;
  user_patient_id: number;
  liver_function: number;
  renal_function: number;
  liver_index: string;
  renal_index: string;
  person_history: string;
  allergic_history: string;
  person_status: number;
  allergic_status: number;
  family_status: number;
  family_history: number;
  is_delete: number;
}

const tabType = ref(0);
const category = ref(1);
const listType = ref(1);
const receptionStatus = ref(0);
const updateTabType = ref(false);
// 患者数据
const patients = ref<Patient[]>([]);

// 药品使用相关数据
const drugUseNum = ref([]);
const drugUseFrequency = ref([]);
const drugUseType = ref([]);
const drugUnit = ref([]);
const drugTime = ref([]);
const drugUseWay = ref([]);
const myStoreList = ref([]);

/**
 * 获取我的诊所列表
 */
function getMyStoreList() {
  getMyStoreListApi().then((res) => {
    myStoreList.value = res;
  });
}

getMyStoreList();

const userStore = useUserStore();
const myStoreId = ref(userStore.userInfo.store_id);
/** 当前取价门店是否允许查看毛利率（0/1） */
const seeRate = ref(0);
/** 开方是否可选医保（0=仅自费） */
const allowInsuranceCategory = ref(0);
/** 是否开启订单百分比调价 */
const priceAdjustEnabled = ref(false);
/** 开方购物车整单价格比例，100=原价 */
const priceDiscount = ref(100);
const { config: priceAdjustConfig, loadByStoreId, applyRatioToDrugs: applyRatioDrugs } = useOrderPriceAdjust();
const [PriceAdjustDrawer, priceAdjustDrawerApi] = useVbenDrawer({
  connectedComponent: OrderPricePercentAdjustDrawer,
});
/** 推广员传方导入关联ID */
const salespersonTransferPrescriptionId = ref(0);
const salespersonTransferDrawerOpen = ref(false);
const hasSalespersonTransfer = ref(false);

/** 当前接诊挂号 ID（模板中不可直接使用 localStorage） */
const doctorReceptionRegisterId = computed(() => {
  if (typeof window === 'undefined' || !window.localStorage) {
    return 0;
  }
  return Number.parseInt(
    window.localStorage.getItem('doctorReception-id') || '0',
    10,
  );
});

async function fetchStoreSeeRate() {
  try {
    const registerId = Number.parseInt(
      localStorage.getItem('doctorReception-id') || '0',
      10,
    );
    const params: { register_id?: number; store_id?: number } = {
      store_id: myStoreId.value,
    };
    if (registerId > 0) {
      params.register_id = registerId;
    }
    const res = await getCurrentStoreTypeApi(params);
    seeRate.value = Number(res?.see_rate ?? 0);
    allowInsuranceCategory.value = Number(res?.allow_insurance_category ?? 0);
    priceAdjustEnabled.value = Number(res?.enable_order_price_percent_adjust ?? 0) === 1;
    await loadByStoreId(myStoreId.value);
    if (allowInsuranceCategory.value !== 1) {
      category.value = 1;
    }
  } catch (error) {
    console.error('获取毛利率权限失败:', error);
  }
}

async function checkSalespersonTransfer() {
  const registerId = Number.parseInt(
    localStorage.getItem('doctorReception-id') || '0',
    10,
  );
  if (!registerId || activeCategory.value !== 1) {
    hasSalespersonTransfer.value = false;
    return;
  }
  try {
    const res = await getSalespersonTransferByRegisterApi(registerId);
    hasSalespersonTransfer.value = Array.isArray(res) && res.length > 0;
  } catch {
    hasSalespersonTransfer.value = false;
  }
}

function handleSalespersonTransferImport(payload: {
  transferId: number;
  clinical_diagnose: string;
  doctor_order: string;
  drugList: any[];
}) {
  salespersonTransferPrescriptionId.value = payload.transferId;
  diagnosis.value = payload.clinical_diagnose || '';
  medicalAdvice.value = payload.doctor_order || '';
  activeCategory.value = 1;
  tabType.value = 2;
  currentDrugs.value = payload.drugList.map((drug: any) => ({
    index_id: drug.index_id ?? drug.drug_id ?? drug.id,
    id: drug.drug_id || drug.id,
    drug_id: drug.drug_id || drug.id,
    drug_name: drug.drug_name || drug.name,
    name: drug.drug_name || drug.name,
    number: drug.number || 1,
    way_id: drug.way_id || 0,
    price: drug.price ?? 0,
    buy_price: drug.buy_price,
  }));
  updateLocalStorage();
  message.success('传方已导入，请确认后发送处方');
}

watch(myStoreId, () => {
  fetchStoreSeeRate();
});

const chineseGrossMarginPercent = computed(() => {
  if (!isSeeRateEnabled(seeRate.value) || activeCategory.value !== 1) {
    return null;
  }
  return calcTotalMarginPercent(currentDrugs.value, dosage.value);
});

function getChineseItemMargin(drug: {
  price?: number | string;
  buy_price?: number | string;
}) {
  if (!isSeeRateEnabled(seeRate.value)) {
    return null;
  }
  return calcItemMarginPercent(drug.price, drug.buy_price);
}

fetchStoreSeeRate();
// userStore.userInfo?.nick_name

/**
 * 获取患者列表
 */
function getPatientListByReception() {
  getPatientList({
    type: listType.value,
  }).then((res) => {
    patients.value = res;

    if (updateTabType.value === false) {
      const activePatientId = localStorage.getItem(`doctorReception-id`);

      if (activePatientId !== null) {
        activeCategory.value =
          Number.parseInt(
            localStorage.getItem(`activeCategory${activePatientId}`),
          ) || 1;
        // 从patients.value中找到当前选中的id并且触发selectPatient方法
        patients.value.forEach((patient) => {
          if (patient.id === Number.parseInt(activePatientId)) {
            selectPatient(patient, false);
            updateTabType.value = true;
          }
        });
      }
    }
  });
}

function updatePatientList() {
  updateTabType.value = true;
  getPatientListByReception();
}

getPatientListByReception();
// 每5秒更新数据
setInterval(getPatientListByReception, 30_000);

// 药品分类
const categories = [
  {label: '中药', value: 1},
  {label: '中成(西)药', value: 2},
  {label: '保健食品', value: 3},
  {label: '产品服务包', value: 5},
  {label: '非药品', value: 6},
  {label: '医疗器械', value: 7},
];

// 当前状态
const activePatient = ref<null | Patient>(null);
const patientInfo = ref<null | Patient>(null);
const userPatientHealthInquiry = ref<null | UserPatientHealthInquiry>(null);
const activeCategory = ref(2);
/** 仅中药/西药支持常用方模板（保健食品不提供常用方） */
const canUseCommonPrescription = computed(() =>
  [1, 2].includes(activeCategory.value),
);
/** 当前挂号是否有关联的特色方选方记录（可重复导入） */
const hasSpecialPrescriptionRecord = computed(
  () => !!patientInfo.value?.special_prescription_patient_record,
);
const specialPrescriptionRecord = computed(
  () => patientInfo.value?.special_prescription_patient_record ?? null,
);
/** 导入卡片规格：SKU 名或单剂 */
function resolveSpecialPrescriptionPurchaseLabel(
  record?: { sku_id?: number; sku_name?: string } | null,
) {
  if (!record) return '';
  return Number(record.sku_id) > 0
    ? (record.sku_name || 'SKU套餐')
    : '单剂';
}
const specialPrescriptionPurchaseLabel = computed(() =>
  resolveSpecialPrescriptionPurchaseLabel(specialPrescriptionRecord.value),
);
const applyingSpecialPrescription = ref(false);
/** 医生已导入的特色方 ID，仅 >0 时提交走特色方计价 */
const appliedSpecialPrescriptionId = ref(0);
/** apply 返回的 SKU/贴数套餐总价，用于底部合计 */
const appliedSpecialPrescriptionExpectedTotal = ref<number | null>(null);
function clearAppliedSpecialPrescription() {
  appliedSpecialPrescriptionId.value = 0;
  appliedSpecialPrescriptionExpectedTotal.value = null;
}
/** 已应用特色方时锁定药方（不可改删增） */
const isSpecialPrescriptionCartLocked = computed(
  () => appliedSpecialPrescriptionId.value > 0,
);
const SP_CART_LOCK_MSG = '特色方药方不可修改，请先清空药方';
/** 特色方锁定中则提示并返回 true */
function guardSpecialPrescriptionCartEdit(): boolean {
  if (isSpecialPrescriptionCartLocked.value) {
    message.warning(SP_CART_LOCK_MSG);
    return true;
  }
  return false;
}
const diagnosis = ref('');
const medicalAdvice = ref('');
const treatmentPrice = ref(0);
const selectPatientId = ref(0);
const ruleType = ref(1);
const prescriptionList = ref([]);
const drugList = ref([]);

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

// ==================== 转诊相关状态 ====================
/** 转诊处方信息 */
const transferPrescription = ref(null);
/** 是否正在加载转诊信息 */
const loadingTransfer = ref(false);

/**
 * 获取药品使用方式列表
 */
function getDrugUseListByWesternModal() {
  getDrugUseList().then((res) => {
    // 更新各种药品使用相关数据
    drugUseNum.value = res.drug_use_num;
    drugUseFrequency.value = res.drug_use_frequency;
    drugUseType.value = res.drug_use_type;
    drugUnit.value = res.drug_unit;
    drugTime.value = res.drug_time;
    drugUseWay.value = res.drug_use_way;
    // drugProcessRule.value = res.drug_process_rule;
  });
}

getDrugUseListByWesternModal();

const selectProductIndex = ref(-1);

function selectProductChange(id) {
  selectProductIndex.value = id;
}

/**
 * 选择中药用法
 * @param id
 */
function selectDrugUseWayChange(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  if (
    selectProductIndex.value < 0 ||
    selectProductIndex.value >= currentDrugs.value.length
  ) {
    return;
  }
  const targetDrug = currentDrugs.value[selectProductIndex.value];
  if (!targetDrug) {
    return;
  }
  targetDrug.way_id = id;
  targetDrug.use_ways = drugUseWay.value.find((value) => value.id === id);
  updateLocalStorage();
}

/**
 * 计算商品总价
 */
const totalProductCost = computed(() => {
  const expected = appliedSpecialPrescriptionExpectedTotal.value;
  if (
    expected != null
    && !Number.isNaN(Number(expected))
    && Number(expected) > 0
  ) {
    return Number(expected);
  }
  if (currentDrugs.value.length === 0) {
    return 0;
  }
  // 中药：与后端 PrescriptionService / format_price 口径一致
  if (activeCategory.value === 1) {
    return calculateChineseProductPriceLikeBackend(
      currentDrugs.value,
      dosage.value,
    );
  }
  return currentDrugs.value.reduce(
    (sum, drug) => sum + drug.price * (drug.select_number || 1),
    0,
  );
});
/**
 * 计算总价
 */
const totalCost = computed(() => {
  return totalProductCost.value + processingFee.value;
});

const processRulePrice = ref(0);
const calcMethod = ref(0);
/**
 * 计算加工费
 */
const processingFee = computed(() => {
  if (ruleType.value === 1) {
    return 0;
  }
  // 已选择药品为空的时候是0
  if (currentDrugs.value.length === 0) {
    return 0;
  }
  // 获取本次选择的加工规则
  childProcessRuleList.value.find((item) => {
    if (item.id === childProcessRuleId.value) {
      calcMethod.value = item.calc_method;
      processRulePrice.value = item.price;
    }
  });
  // 模式1：固定价格模式
  if (calcMethod.value === 1) {
    return processRulePrice.value;
  }
  // 模式2：单价*用量
  if (calcMethod.value === 2) {
    return processRulePrice.value * dosage.value;
  }
  // 模式2：单价*用量
  if (calcMethod.value === 3) {
    const number = currentDrugs.value.reduce(
      (sum, drug) => sum + drug.number,
      0,
    );
    return processRulePrice.value * dosage.value * number;
  }
  return 0;
});

const visible = ref<boolean>(false);
const previewImage = ref([]);
/**
 * 说明书预览
 * @param value
 * @param instruction
 */
const setVisible = (value, instruction = ''): void => {
  previewImage.value = [];
  if (instruction == '') {
    message.error('该产品没有说明书！');
  } else {
    if (typeof instruction === 'string') {
      // 如果有逗号，则进行分割 没有则追加到previewImage
      if (instruction.includes(',')) {
        instruction = instruction.split(',');
        previewImage.value = instruction;
      } else {
        previewImage.value.push(instruction);
      }
    }
    visible.value = value;
  }
};

/**
 * 选择华女这操作
 * @param patient
 * @param isUpdateTabType
 */
const selectPatient = (patient: Patient, isUpdateTabType = true) => {
  clearAppliedSpecialPrescription();
  selectPatientId.value = patient.id;
  receptionStatus.value = patient.status;
  if (isUpdateTabType === true) {
    tabType.value = 1;
  } else {
    // 获取doctorReception-type并赋值
    if (localStorage.getItem(`doctorReception-type`) !== null) {
      tabType.value = Number.parseInt(
        localStorage.getItem(`doctorReception-type`),
      );
    }
  }
  activePatient.value = patient.user_patient;

  // 恢复之前保存的 activeCategory
  const savedCategory = localStorage.getItem(`activeCategory${patient.user_patient?.id}`);
  if (savedCategory) {
    activeCategory.value = Number.parseInt(savedCategory);
  } else {
    // 如果没有保存的值，检查两个存储键哪个有数据
    const chineseData = localStorage.getItem(`prescriptionData_1_${patient.user_patient?.id}`);
    const westData = localStorage.getItem(`prescriptionData_2_${patient.user_patient?.id}`);
    if (chineseData && JSON.parse(chineseData).length > 0) {
      activeCategory.value = 1;
    } else if (westData && JSON.parse(westData).length > 0) {
      activeCategory.value = 2;
    }
    // 否则保持默认值
  }

  // 如果恢复的处方类型是中药，检测并显示转诊提示
  if (activeCategory.value === 1) {
    checkAndShowTransferTip();
    checkSalespersonTransfer();
  }

  getPatientItem(patient.id).then((value) => {
    patientInfo.value = value;
    userPatientHealthInquiry.value = value.user_patient_health_inquiry;
    prescriptionList.value = value.prescription;
  });

  localStorage.setItem(
    `doctorReception-id`,
    // JSON.stringify(selectData),
    JSON.stringify(patient.id),
  );
  getCurrentDrugs();
};

// 数量增加
const increment = (index: number) => {
  if (guardSpecialPrescriptionCartEdit()) return;
  currentDrugs.value[index].select_number++;
  saveToLocalStorage();
};

// 数量减少
const decrement = (index: number) => {
  if (guardSpecialPrescriptionCartEdit()) return;
  if (currentDrugs.value[index].select_number > 1) {
    currentDrugs.value[index].select_number--;
    saveToLocalStorage();
  }
};

// 切换药品用法编辑状态
const toggleEditDrug = (index: number) => {
  if (guardSpecialPrescriptionCartEdit()) return;
  currentDrugs.value[index].isEditing = !currentDrugs.value[index].isEditing;
};

// 保存药品用法编辑
const saveEditDrug = (index: number) => {
  const drug = currentDrugs.value[index];
  // 更新 ID 字段
  drug.type_id = drug.use_type?.id;
  drug.frequency_id = drug.use_frequency?.id;
  drug.time_id = drug.use_num?.id;
  drug.unit_id = drug.unit?.id;
  drug.isEditing = false;
  updateLocalStorage();
};

// 更新药品用法字段
const updateDrugUsage = (index: number, field: string, value: any) => {
  currentDrugs.value[index][field] = value;
};

/**
 * 获取药品数据的存储key（按类型分开存储）
 * @param patientId 患者ID
 * @param category 类型：1-中药，2-西药
 */
const getStorageKey = (patientId: number | string | undefined, category: number) => {
  return `prescriptionData_${category}_${patientId}`;
};

// 保存到本地存储（按类型分开存储）
const saveToLocalStorage = () => {
  localStorage.setItem(
    getStorageKey(activePatient.value?.id, activeCategory.value),
    JSON.stringify(currentDrugs.value),
  );
};

function snapshotDrugOrigins(drugs: any[]) {
  return drugs.map((drug) => ({
    ...drug,
    origin_price: drug.origin_price ?? drug.price,
    origin_buy_price: drug.origin_buy_price ?? drug.buy_price,
  }));
}

function applyCartPriceDiscount(discount: number) {
  priceDiscount.value = discount;
  const scope = priceAdjustConfig.value.order_price_adjust_scope;
  currentDrugs.value = applyRatioDrugs(snapshotDrugOrigins(currentDrugs.value), discount, scope);
  saveToLocalStorage();
  message.success(discount === 100 ? '已清除价格浮动' : '价格已更新');
}

function clearCartPriceDiscount() {
  applyCartPriceDiscount(100);
}

const priceDiscountLabel = computed(() => formatPriceDiscountLabel(priceDiscount.value));

function openOrderPriceAdjust() {
  if (guardSpecialPrescriptionCartEdit()) return;
  if (!priceAdjustEnabled.value || !currentDrugs.value.length) return;
  currentDrugs.value = snapshotDrugOrigins(currentDrugs.value);
  const discount = Number(priceDiscount.value);
  priceAdjustDrawerApi.setData({
    stage: 'pre_send',
    priceDiscount: discount,
    price_discount: discount,
    previewOriginPrice: 100,
    quickOptions: normalizeQuickOptions(priceAdjustConfig.value.order_discount_quick_options),
    onApplyPreSend: (payload: { priceDiscount: number }) => applyCartPriceDiscount(payload.priceDiscount),
  });
  priceAdjustDrawerApi.open();
}

/**
 * 删除药品（本地）
 * @param index
 */
const removeDrug = (index: number) => {
  if (guardSpecialPrescriptionCartEdit()) return;
  currentDrugs.value.splice(index, 1);
  updateLocalStorage();
};
/**
 * 修改缓存的处方信息（按类型分开存储）
 */
const updateLocalStorage = () => {
  localStorage.setItem(
    getStorageKey(activePatient.value?.id, activeCategory.value),
    JSON.stringify(currentDrugs.value),
  );
  getCurrentDrugs();
};

const currentDrugs = ref([]);
/**
 * 获取缓存的处方信息（按类型分开存储）
 */
const getCurrentDrugs = () => {
  currentDrugs.value = JSON.parse(
    localStorage.getItem(getStorageKey(activePatient.value?.id, activeCategory.value)) || '[]',
  );
};
getCurrentDrugs();

const doctorSecondSign = ref(0);
const checkData = ref([]);
/**
 * 检查中药的相冲
 */
const checkChineseMedicineConflict = () => {
  if (activeCategory.value === 2) {
    // eslint-disable-next-line no-use-before-define
    sendPrescription();
    return;
  }
  notification.info({
    message: '正在检查药物相冲',
    duration: 1,
    description: '正在检查药物相冲，请稍等...',
  })
  const names = currentDrugs.value.map((item) => item.drug_name);
  checkChineseMedicineConflictApi({names: names}).then((res) => {
    if (res.is_exist === true) {
      checkData.value.message = res.message;
      doctorSecondSignModal.value = true;
    } else {
      notification.success({
        message: '检查成功',
        duration: 3,
        description: '暂无相冲药品',
      })
      // eslint-disable-next-line no-use-before-define
      sendPrescription();
    }
  })
  return;
}
/**
 * 发送处方
 */
const sendPrescription = () => {
  if (currentDrugs.value.length === 0) {
    message.error('请选择药品');
    return;
  }
  if (activeCategory.value === 1) {
    if (ruleType.value === 1) {
      if (packageMethodId.value == null) {
        message.error('请选择包法');
        return;
      }
    } else {
      if (processRuleId.value == null) {
        message.error('请选择制剂');
        return;
      }
      if (processRuleNoteId.value == null) {
        message.error('请选择规格');
        return;
      }
      if (childProcessRuleId.value == null) {
        message.error('请选择备注');
      }
    }
  }
  if (diagnosis.value === '') {
    message.error('诊断结果不能为空');
    return;
  }
  if (medicalAdvice.value === '') {
    message.error('医嘱不能为空');
    return;
  }
  // 发送处方逻辑
  addWestPrescription({
    // 当前活动患者的个人信息
    patient: activePatient.value,
    // 当前处方中的药品列表
    drugs: currentDrugs.value,
    // 诊断信息
    diagnosis: diagnosis.value,
    // 医嘱信息
    medicalAdvice: medicalAdvice.value,
    // 总费用
    total: totalCost.value,
    // 费用类别
    category: category.value,
    // 药品类型
    drug_type: tabType.value,
    // 从本地存储获取的挂号ID
    register_id: Number.parseInt(localStorage.getItem(`doctorReception-id`)),
    // 治疗费用
    treatment_price: treatmentPrice.value,
    // 包装方式ID
    package_method_id: packageMethodId.value,
    // 加工规则ID
    process_rule_id: processRuleId.value,
    // 加工规则备注ID
    process_rule_note_id: processRuleNoteId.value,
    // 子加工规则ID
    child_process_rule_id: childProcessRuleId.value,
    // 加工规则类型
    process_rule_type: ruleType.value,
    // 处方类型
    prescription_type: activeCategory.value,
    // 加工费
    processing_fee: processRulePrice.value,
    // 用药剂量
    dosage: dosage.value,
    // 每日用药次数
    day_dosage: dayDosage.value,
    // 是否二次签名
    doctor_second_sign: doctorSecondSign.value,
    salesperson_transfer_prescription_id: salespersonTransferPrescriptionId.value || undefined,
    price_discount: priceDiscount.value,
    special_prescription_id: appliedSpecialPrescriptionId.value || 0,
  }).then((res) => {
    message.success('处方已发送');

    // 检查是否需要转诊
    const needTransfer = res?.result?.need_transfer || res?.data?.need_transfer || res?.need_transfer;
    const transferPrescriptionId = res?.result?.transfer_prescription_id || res?.data?.transfer_prescription_id || res?.transfer_prescription_id;

    if (needTransfer && transferPrescriptionId) {
      // 如果需要转诊，获取转诊信息
      fetchTransferPrescription(transferPrescriptionId);
      message.info('该处方需要转诊，请等待中医诊所确认');
    } else {
      // 不需要转诊，清空转诊信息
      transferPrescription.value = null;
    }

    // 清空当前数据
    clearPrescriptionCart(false);
    tabType.value = 1;
    salespersonTransferPrescriptionId.value = 0;
    processRulePrice.value = 0;
    checkSalespersonTransfer();

    // 刷新患者信息
    if (selectPatientId.value) {
      getPatientItem(selectPatientId.value).then((value) => {
        patientInfo.value = value;
        userPatientHealthInquiry.value = value.user_patient_health_inquiry;
        prescriptionList.value = value.prescription;
      });
    }
  }).catch((error) => {
    console.error('发送处方失败:', error);
    message.error('发送处方失败，请重试');
  });
};

// 进入处方界面
const showPrescription = () => {
  // 打开处方模态框逻辑
  tabType.value = 2;
};

// 监听tabType.value变化
watch(
  () => tabType.value,
  (newValue) => {
    if (newValue === 1) {
      getPatientItem(selectPatientId.value).then((value) => {
        patientInfo.value = value;
        userPatientHealthInquiry.value = value.user_patient_health_inquiry;
        prescriptionList.value = value.prescription;
      });
    }
    newDrugInfo.value = {};
    localStorage.setItem(
      `doctorReception-type`,
      // JSON.stringify(selectData),
      JSON.stringify(newValue),
    );
  },
);


const [WesternDrugModal, WesternDrugModalApi] = useVbenModal({
  connectedComponent: WesternModal,
});

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

const [DiagnosisModals, DiagnosisModalApi] = useVbenModal({
  connectedComponent: DiagnosisModal,
});

const openDiagnosisModal = () => {
  // 打开常用诊断模态框逻辑
  DiagnosisModalApi.setData({
    values: diagnosis.value,
    updateDiagnosis,
  });
  DiagnosisModalApi.open();
};

/**
 * 更新诊断结果
 * @param values
 */
function updateDiagnosis(values) {
  diagnosis.value = values;
}

/**
 * 常用医嘱
 */
const [DoctorOrderModals, DoctorOrderModalApi] = useVbenModal({
  connectedComponent: DoctorOrderModal,
});

const openDoctorOrderModal = () => {
  // 打开常用医嘱模态框逻辑
  DoctorOrderModalApi.setData({
    values: medicalAdvice.value,
    updateDoctorOrder,
  });
  DoctorOrderModalApi.open();
};

function updateDoctorOrder(values) {
  medicalAdvice.value = values;
}

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


const [RefusalOfTreatmentModals, RefusalOfTreatmentModalApi] = useVbenModal({
  connectedComponent: RefusalOfTreatmentModal,
});

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

// ==================== 确认模态框 ====================
const [ConfirmModalComponent, confirmModalApi] = useVbenModal({
  connectedComponent: ConfirmModal,
});

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

/**
 * 打开常用方选择弹窗
 * @description 打开常用方弹窗，选择后自动填充药品到处方中
 */
function openCommonPrescriptionModal() {
  CommonPrescriptionModalApi.setData({
    type: activeCategory.value,
    onSelect: handleSelectCommonPrescription,
  });
  CommonPrescriptionModalApi.open();
}

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

  // 根据类型处理药品：整表覆盖为常用方内容，不与当前处方按药品 ID 去重合并
  if (type === 1) {
    currentDrugs.value = (recipes || []).map((recipe: any) => ({
      index_id: recipe.id,
      id: recipe.drug_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,
      instruction: recipe.instruction,
      type: recipe.type,
      select_number: recipe.select_number ?? 1,
    }));
  } else {
    currentDrugs.value = (recipes || []).map((recipe: any) => {
      const drugId = recipe.drug_id || recipe.id;
      return {
        index_id: recipe.id,
        id: drugId,
        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,
        select_number: recipe.select_number ?? 1,
      };
    });

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

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

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

  // 保存到本地存储
  updateLocalStorage();
}

/**
 * 应用患者选择的特色方到处方购物车
 * @param switchToPrescription 是否切换到开方 Tab（患者信息页导入时为 true）
 */
async function handleApplySpecialPrescription(switchToPrescription = false) {
  const registerId = doctorReceptionRegisterId.value;
  if (!registerId) {
    message.warning('请先选择患者');
    return;
  }
  applyingSpecialPrescription.value = true;
  try {
    const res = await applySpecialPrescriptionApi({ register_id: registerId });
    const typeMap: Record<string, number> = {
      west: 1,
      chinese: 2,
      granular: 3,
    };
    const categoryMap: Record<string, number> = {
      west: 2,
      chinese: 1,
      granular: 1,
    };
    const prescriptionType = res.prescription_type || 'chinese';
    activeCategory.value = categoryMap[prescriptionType] || 1;
    if (switchToPrescription) {
      tabType.value = 2;
    }

    await handleSelectCommonPrescription(
      {
        prescription: {
          dosage: res.dosage ?? res.dose_count ?? 7,
          day_dosage: res.day_dosage ?? 2,
          rule_type: res.rule_type ?? 1,
          package_method_id: res.package_method_id ?? 2,
          clinical_diagnose: res.clinical_diagnose ?? '',
          doctor_order: res.doctor_order ?? '',
        },
        recipes: res.recipes || [],
      },
      typeMap[prescriptionType] || 2,
    );

    appliedSpecialPrescriptionId.value = Number(res.special_prescription_id) || 0;
    appliedSpecialPrescriptionExpectedTotal.value =
      res.expected_total_price != null ? Number(res.expected_total_price) : null;

    if (selectPatientId.value) {
      const value = await getPatientItem(selectPatientId.value);
      patientInfo.value = value;
    }
    message.success(`已应用特色方：${res.special_prescription_name || ''}`);
  } catch (error) {
    console.error('应用特色方失败:', error);
    message.error('应用特色方失败，请稍后重试');
  } finally {
    applyingSpecialPrescription.value = false;
  }
}

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

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

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

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

  if (![1, 2].includes(activeCategory.value)) {
    message.warning('当前分类不支持保存为常用方');
    return;
  }

  isSavingCommonPrescription.value = true;

  try {
    // 根据处方类型选择不同的保存接口
    if (activeCategory.value === 1) {
      // 中药处方 - 构建药品详细信息数组
      const drugs = currentDrugs.value.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: myStoreId.value,
        clinical_diagnose: diagnosis.value || '',
        doctor_order: medicalAdvice.value || '',
        category: String(category.value),
        dosage: dosage.value,
        day_dosage: dayDosage.value,
        rule_type: ruleType.value,
        package_method_id: ruleType.value === 1 ? packageMethodId.value : undefined,
        process_rule_id: ruleType.value === 2 ? (processRuleId.value || undefined) : undefined,
        child_process_rule_id: ruleType.value === 2 ? (childProcessRuleId.value || undefined) : undefined,
        process_rule_note_id: ruleType.value === 2 ? (processRuleNoteId.value || undefined) : undefined,
      });
    } else {
      // 西药处方 - 构建药品详细信息数组
      const drugs = currentDrugs.value.map((drug) => ({
        drug_id: drug.id,
        drug_name: drug.drug_name,
        number: drug.number || 1,
        price: drug.price || 0,
        image: drug.image || '',
        instruction: drug.instruction || '',
        use_type_id: drug.use_type?.id || 0,
        use_frequency_id: drug.use_frequency?.id || 0,
        use_time_id: drug.use_num?.id || 0,
        unit_id: drug.unit?.id || 0,
        select_number: drug.select_number || 1,
      }));

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

    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 = '';
};

const openWesternModal = () => {
  if (guardSpecialPrescriptionCartEdit()) return;
  // 判断是否为简单产品类型（3,5,6,7）
  const simpleProductTypes = [3, 5, 6, 7];
  if (simpleProductTypes.includes(activeCategory.value)) {
    // 使用简单产品模态框
    SimpleProductModalApi.setData({
      values: activeCategory.value,
      activePatient_id: activePatient.value?.id,
      getCurrentDrugs,
      storagePrefix: '', // 接诊页面不加前缀
    });
    SimpleProductModalApi.open();
  } else {
    // 使用原有的西药/中药模态框
  WesternDrugModalApi.setData({
    values: activeCategory.value,
    activePatient_id: activePatient.value?.id,
    getCurrentDrugs,
    storagePrefix: '', // 接诊页面不加前缀
  });
  WesternDrugModalApi.open();
  }
};
const openPrescriptionDetail = (values) => {
  // 打开西药处方模态框逻辑
  PrescriptionDetailModalApi.setData({
    values,
  });
  PrescriptionDetailModalApi.open();
};

// 根据创制string来把字符串的逗号分开变成数组
function splitString(str: string) {
  if (!str) {
    return [];
  }
  return str.split(',');
}

/**
 * 切换tab（中药/西药切换）
 * @param id 类型：1-中药，2-西药
 * @description 切换Tab时：
 *              1. 先保存当前Tab的药品数据
 *              2. 更新activeCategory
 *              3. 加载新Tab对应的药品数据
 *              4. 如果切换到中药且当前诊所为西医诊所，显示转诊提示
 */
function tabChange(id) {
  // 先保存当前Tab的药品数据
  localStorage.setItem(
    getStorageKey(activePatient.value?.id, activeCategory.value),
    JSON.stringify(currentDrugs.value),
  );

  // 更新Tab类型
  localStorage.setItem(`activeCategory${activePatient.value?.id}`, id);
  activeCategory.value = id;
  if (id === 1) {
    checkSalespersonTransfer();
  }

  // 加载新Tab对应的药品数据
  currentDrugs.value = JSON.parse(
    localStorage.getItem(getStorageKey(activePatient.value?.id, id)) || '[]',
  );

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

/**
 * 检测并显示转诊提示
 * @description 当切换到中药处方时，如果当前诊所为西医诊所，显示转诊提示
 * 半小时内只提醒一次
 */
async function checkAndShowTransferTip() {
  try {
    // 检查上次提醒时间，如果距离上次提醒不足30分钟，则不显示警告
    const storageKey = `transferTipLastShown_${myStoreId.value}`;
    const lastShownTime = localStorage.getItem(storageKey);
    const now = Date.now();
    const thirtyMinutes = 30 * 60 * 1000; // 30分钟 = 1800000 毫秒

    if (lastShownTime) {
      const timeDiff = now - Number.parseInt(lastShownTime);
      if (timeDiff < thirtyMinutes) {
        // 距离上次提醒不足30分钟，不显示警告
        return;
      }
    }

    // 调用新接口获取当前诊所类型和委托诊所信息
    const registerId = Number.parseInt(
      localStorage.getItem('doctorReception-id') || '0',
      10,
    );
    const storeInfo = await getCurrentStoreTypeApi({
      store_id: myStoreId.value,
      ...(registerId > 0 ? { register_id: registerId } : {}),
    });
    // const storeInfo = res;

    if (!storeInfo) {
      return;
    }
    console.log(storeInfo, 'aaaaaaaaaaaaaaaaa')

    // 检测是否为西医诊所（clinic_type === 1）
    if (storeInfo.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 });
      infoModalApi.setData({
          content: `检测到当前诊所为西医诊所，本次处方开具后自动转接到【${storeName}】的【${doctorName}】的在线复诊中`,
        });
      infoModalApi.open();

      // 更新上次提醒时间戳
      localStorage.setItem(storageKey, String(now));
    }
  } catch (error) {
    console.error('获取诊所信息失败:', error);
  }
}

/**
 * 接诊
 */
function reception() {
  receptionApi(localStorage.getItem(`doctorReception-id`)).then((value) => {
    message.success('接诊成功');
    updateTabType.value = false;
    getPatientListByReception();
    receptionStatus.value = 2;
  });
}

const updateReceptionStatus = () => {
  receptionStatus.value = 0;
  tabType.value = 0;
}

/**
 * 拒诊
 */
function refuseReception() {
  RefusalOfTreatmentModalApi.setData({
    values: {
      register_id: localStorage.getItem(`doctorReception-id`)
    },
    getPatientListByReception,
    updateReceptionStatus,
    // 在patients中循环查询id = selectPatientId.value的

    // let patient = patients.
    // selectPatient(localStorage.getItem(`doctorReception-id`));
  })

  RefusalOfTreatmentModalApi.open();
}

/**
 * 结束诊断
 */
function endOfDiagnosis() {
  endOfDiagnosisApi(localStorage.getItem(`doctorReception-id`)).then(
    (value) => {
      message.success('接诊成功');
      updateTabType.value = false;
      getPatientListByReception();
      receptionStatus.value = 2;
      tabType.value = 0;
    },
  );
}

// 基础配置
const processRuleList = ref([]);
// 子配置
const childProcessRuleList = ref([]);
// 规格
const processRuleNoteList = ref([]);
const processRuleId = ref();
const processRuleNoteId = ref();
const childProcessRuleId = ref();

async function loadProcessRuleData(pid = 0, ruleId = 0) {
  const data = ruleId === 0 ? { pid } : { rule_id: ruleId };
  const value = await getProcessRuleList(data);
  if (ruleId !== 0) {
    processRuleNoteList.value = value;
  } else if (pid === 0) {
    processRuleList.value = value;
  } else {
    childProcessRuleList.value = value;
  }
}

function parsePrescriptionDetailContent(detail: any): Record<string, any> {
  let c = detail?.content;
  if (typeof c === 'string') {
    try {
      c = JSON.parse(c);
    } catch {
      c = {};
    }
  }
  return c && typeof c === 'object' ? c : {};
}

function mapWestRepiceToProduct(recipe: any): Record<string, any> | null {
  if (!recipe) return null;
  let drugObj: Record<string, any> = {};
  try {
    const raw = recipe.content;
    drugObj = typeof raw === 'string' ? JSON.parse(raw) : (raw || {});
  } catch {
    return null;
  }
  const drugId = Number(drugObj.id);
  if (!drugId) return null;

  const selectNumber = Math.max(
    1,
    Number(recipe.number ?? drugObj.select_number ?? drugObj.number ?? 1) || 1,
  );
  const grainNumber = Math.max(
    1,
    Number(
      drugObj.number ?? drugObj.grain_number ?? recipe.grain_number ?? 1,
    ) || 1,
  );

  const timeId = recipe.time_id ?? drugObj.time_id;
  const typeId = recipe.type_id ?? drugObj.type_id;
  const freqId = recipe.f_id ?? drugObj.frequency_id;
  const unitId = recipe.wu_id ?? drugObj.unit_id;

  return {
    index_id: drugId,
    id: drugId,
    drug_name: drugObj.drug_name || drugObj.name || '',
    number: grainNumber,
    use_num: drugTime.value.find((item: any) => item.id === timeId),
    use_type: drugUseType.value.find((item: any) => item.id === typeId),
    use_frequency: drugUseFrequency.value.find(
      (item: any) => item.id === freqId,
    ),
    unit: drugUnit.value.find((item: any) => item.id === unitId),
    price: Number(drugObj.sell_price ?? drugObj.price ?? 0),
    way_id: drugObj.way_id,
    use_ways: drugUseWay.value.find((item: any) => item.id === drugObj.way_id),
    time_id: timeId,
    type_id: typeId,
    frequency_id: freqId,
    unit_id: unitId,
    image: drugObj.image || '',
    instruction: drugObj.instruction || '',
    type: drugObj.type,
    select_number: selectNumber,
  };
}

/**
 * 将历史处方详情写入当前接诊编辑区（不提交）
 */
async function applyHistoricalPrescriptionDetail(detail: any): Promise<boolean> {
  const content = parsePrescriptionDetailContent(detail);
  const pt = Number(detail.prescription_type);
  const supported = [1, 2, 3, 5, 6, 7];
  if (!supported.includes(pt)) {
    message.warning('该处方类型暂不支持复用');
    return false;
  }

  const pid = activePatient.value?.id;
  if (!pid) {
    message.warning('请先选择患者');
    return false;
  }

  localStorage.setItem(
    getStorageKey(pid, activeCategory.value),
    JSON.stringify(currentDrugs.value),
  );

  activeCategory.value = pt;
  localStorage.setItem(`activeCategory${pid}`, String(pt));

  const repiceList = Array.isArray(content.repice) ? content.repice : [];

  if (pt === 1) {
    const rep0 = repiceList[0];
    if (!rep0) {
      message.warning('处方中药品数据为空');
      return false;
    }
    let rows: any[] = [];
    try {
      const raw = rep0.content;
      rows = typeof raw === 'string' ? JSON.parse(raw) : (raw || []);
    } catch {
      message.error('解析中药处方失败');
      return false;
    }
    if (!Array.isArray(rows) || rows.length === 0) {
      message.warning('处方中药品数据为空');
      return false;
    }

    currentDrugs.value = rows.map((d: any) => {
      const drugId = Number(d.drug_id ?? d.id);
      // 落库煎法在 ChineseMedicineModel.order，详情可能带 use_way / useWay
      const wayId =
        d.way_id ?? d.use_way?.id ?? d.useWay?.id ?? d.order;
      return {
        index_id: d.id ?? drugId,
        id: drugId,
        drug_name: d.name || d.drug_name || '',
        number: d.number ?? 1,
        price: Number(d.price ?? 0),
        way_id: wayId,
        use_ways:
          drugUseWay.value.find((item: any) => item.id === wayId) ??
          d.use_way ??
          d.useWay,
        use_num: drugTime.value.find((item: any) => item.id === d.time_id),
        use_type: drugUseType.value.find((item: any) => item.id === d.type_id),
        use_frequency: drugUseFrequency.value.find(
          (item: any) => item.id === d.frequency_id,
        ),
        unit: drugUnit.value.find((item: any) => item.id === d.unit_id),
        time_id: d.time_id,
        type_id: d.type_id,
        frequency_id: d.frequency_id,
        unit_id: d.unit_id,
        image: d.image || '',
        instruction: d.instruction || '',
        type: d.type,
      };
    });

    ruleType.value = rep0.deployment === 2 ? 1 : 2;
    dosage.value = Number(rep0.dosage ?? 7);
    dayDosage.value = Number(rep0.consumption ?? 2);
    packageMethodId.value = rep0.package_method_id ?? 2;

    if (rep0.process_rule_id && Number(rep0.process_rule_id) > 0) {
      processRuleId.value = rep0.process_rule_id;
      await loadProcessRuleData(rep0.process_rule_id, 0);
    }
    if (rep0.child_process_rule_id && Number(rep0.child_process_rule_id) > 0) {
      childProcessRuleId.value = rep0.child_process_rule_id;
      await loadProcessRuleData(0, rep0.child_process_rule_id);
    }
    if (rep0.process_rule_note_id && Number(rep0.process_rule_note_id) > 0) {
      processRuleNoteId.value = rep0.process_rule_note_id;
    }

    if (!rep0.process_rule_id) {
      message.warning('历史处方未包含完整加工规则，请核对包法/制剂与规格');
    }
  } else {
    const mapped: any[] = [];
    for (const recipe of repiceList) {
      const row = mapWestRepiceToProduct(recipe);
      if (row) mapped.push(row);
    }
    if (mapped.length === 0) {
      message.warning('未解析到可复用的药品行');
      return false;
    }
    currentDrugs.value = mapped;
  }

  diagnosis.value =
    detail.clinical_diagnose ?? content.clinical_diagnose ?? '';
  medicalAdvice.value = detail.doctor_order ?? content.doctor_order ?? '';
  category.value =
    detail.category === 2 || detail.category === '2' || content.category === '医保'
      ? 2
      : 1;
  doctorSecondSign.value = 0;
  processRulePrice.value = 0;

  localStorage.setItem(
    getStorageKey(pid, activeCategory.value),
    JSON.stringify(currentDrugs.value),
  );
  if (activePatient.value?.id) {
    localStorage.setItem(
      `activeCategory${activePatient.value.id}`,
      String(activeCategory.value),
    );
  }
  getCurrentDrugs();
  return true;
}

async function reusePrescriptionFromList(prescriptionId: number) {
  if (!activePatient.value?.id) {
    message.warning('请先选择患者');
    return;
  }
  const draft = currentDrugs.value;
  const go = async () => {
    try {
      const detail = await getPrescriptionInfoApi(prescriptionId);
      const ok = await applyHistoricalPrescriptionDetail(detail);
      if (ok) {
        tabType.value = 2;
        message.success('已复用到开方页，请核对后发送');
      }
    } catch (e) {
      console.error(e);
      message.error('加载处方详情失败');
    }
  };

  if (draft.length > 0) {
    AntModal.confirm({
      title: '覆盖当前草稿？',
      content: '当前处方清单中有药品，复用将替换为所选历史处方内容。',
      onOk: go,
    });
  } else {
    await go();
  }
}

function confirmWithdrawPrescription(item: any) {
  const registerId = Number.parseInt(
    localStorage.getItem(`doctorReception-id`) || '0',
    10,
  );
  if (!registerId || !item?.id) {
    message.error('参数错误');
    return;
  }
  AntModal.confirm({
    title: '确认撤回处方？',
    content:
      '撤回后患者将无法继续支付该订单，库存占用将释放。此操作不可撤销。',
    async onOk() {
      try {
        await withdrawPrescriptionApi({
          prescription_id: item.id,
          register_id: registerId,
        });
        message.success('处方已撤回');
        if (selectPatientId.value) {
          const value = await getPatientItem(selectPatientId.value);
          patientInfo.value = value;
          userPatientHealthInquiry.value = value.user_patient_health_inquiry;
          prescriptionList.value = value.prescription;
        }
      } catch (e: any) {
        message.error(
          e?.response?.data?.message || e?.message || '撤回失败',
        );
        return Promise.reject(e);
      }
    },
  });
}

loadProcessRuleData();

/**
 * 选择煎法
 * @param id
 */
function selectProcessRule(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  processRuleId.value = id;
  loadProcessRuleData(id);  // 加载煎法选项
}

/**
 * 选择规格
 * @param id
 */
function selectProcessRuleNot(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  childProcessRuleId.value = id;
  loadProcessRuleData(0, id);  // 加载备注选项
}

/**
 * 选择备注
 * @param id
 */
function selectProcessRuleNotCommit(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  processRuleNoteId.value = id;
}

const packageMethodId = ref(2);
const packageMethod = [
  {label: '味包', value: 1},
  {label: '剂包', value: 2},
];

function selectPackageMethod(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  packageMethodId.value = id;
}

// jishu
const dosage = ref(7);
const dayDosage = ref(2);

/**
 * 清空药方：退出特色方 SKU 计价状态，恢复可编辑
 * @param showToast 是否提示成功
 */
function clearPrescriptionCart(showToast = true) {
  currentDrugs.value = [];
  diagnosis.value = '';
  medicalAdvice.value = '';
  packageMethodId.value = 2;
  dosage.value = 7;
  dayDosage.value = 2;
  newDrugInfo.value = {};
  clearAppliedSpecialPrescription();
  priceDiscount.value = 100;
  updateLocalStorage();
  if (showToast) {
    message.success('已清空药方');
  }
}

/** 清空药方（有药品时二次确认） */
function handleClearPrescriptionCart() {
  if (currentDrugs.value.length === 0 && !appliedSpecialPrescriptionId.value) {
    message.info('当前无药方内容');
    return;
  }
  AntModal.confirm({
    title: '清空药方',
    content: '确定清空当前药方吗？特色方将需重新应用。',
    okText: '确定',
    cancelText: '取消',
    onOk: () => clearPrescriptionCart(),
  });
}

function updateChineseNumber() {
  updateLocalStorage();
}

// 二次签名确认弹窗
const doctorSecondSignModal = ref(false);

/**
 * 在新的药品数量框失去焦点后弹出新药品弹窗
 */
function newDrugBlur() {
  // 如果没输入克数，默认为 1g
  if (!newDrugInfo.value.number) {
    newDrugInfo.value.number = 1;
  }

  if (newDrugInfo.value.id && newDrugInfo.value.name && newDrugInfo.value.number > 0) {
    confirmModalApi.setData({
      title: '确认添加',
      content: `要把【${newDrugInfo.value.name}】添加到清单吗？`,
      onConfirm: addDrugByChinese,
    });
    confirmModalApi.open();
  }
}

function doctorSecondSignModalOk() {
  doctorSecondSign.value = 1;
  doctorSecondSignModal.value = false;
  sendPrescription();
}

function updateChineseNumberGoNewDrug(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    updateLocalStorage();
    setTimeout(() => {
      // 获取新药品卡片中的克数输入框并聚焦
      const newDrugNumberInput = document.querySelector(
        '.new-select-drug-name input',
      );
      if (newDrugNumberInput) {
        (newDrugNumberInput as HTMLElement).focus();
      }
    }, 100);
  }
}

/**
 * 获取药品列表
 * @param {string} searchText - 搜索关键词
 */
const getDrugListByWesternModal = debounce(async (searchText = '') => {
  if (searchText === '' && activeCategory.value === 1) {
    drugList.value = [];
    return;
  }

  getCurrentDrugs();

  try {
    const registerId = Number.parseInt(
      localStorage.getItem('doctorReception-id') || '0',
      10,
    );
    const res = await getProductListDoctorReception({
      store_id: myStoreId.value,
      type: activeCategory.value,
      name: searchText,
      ...(registerId > 0 ? { register_id: registerId } : {}),
    });

    drugList.value = res.map((item) => {
      const matched = currentDrugs.value.find((v) => v.index_id === item.id);
      return {
        ...item,
        select_number: matched?.select_number || 0,
        drug: {
          ...item.drug,
          number: matched?.number || 1,
        },
      };
    });
  } catch (error) {
    console.error('获取药品列表失败:', error);
    message.error('获取药品列表失败');
  }
}, 300);

// getDrugListByWesternModal();

/**
 * 选择药品
 */
function selectNewDrugInfo() {
  // 如果是新药品输入框，调用添加新药品方法
  const check = currentDrugs.value.find((v) => v.id === newDrugInfo.value.id);
  if (check) {
    newDrugInfo.value.id = '';
    message.error('该药品已经在处方中了！');
    return;
  }

  const data = drugList.value.find((v) => v.drug_id === newDrugInfo.value.id);
  newDrugInfo.value.price = data.price;
  newDrugInfo.value.name = data.drug.drug_name;
  setTimeout(() => {
    // 获取新药品卡片中的克数输入框并聚焦
    const newDrugNumberInput = document.querySelector(
      '.new-number-input input',
    );
    if (newDrugNumberInput) {
      (newDrugNumberInput as HTMLElement).focus();
    }
  }, 100);
}

const selectChineseIndex = ref(-1);
const selectChineseId = ref(0);

/**
 * 选择药品
 * @param id
 */
function selectOldDrugInfo(id) {
  if (guardSpecialPrescriptionCartEdit()) return;
  const check = JSON.parse(
    localStorage.getItem(getStorageKey(activePatient.value?.id, activeCategory.value)) || '[]',
  ).find((v) => v.id === id);
  if (check) {
    currentDrugs.value[selectChineseIndex.value].id = selectChineseId.value;
    drugList.value = [];
    message.error('该药品已经在处方中了！');
    return;
  }
  const oldDrugInfo = currentDrugs.value[selectChineseIndex.value];
  // 如果是新药品输入框，调用添加新药品方法
  const data = drugList.value.find((v) => v.drug_id === id);

  // 创建新的商品对象（避免直接修改原始数据）
  const newProduct = {
    // 索引ID（用于在列表中查找）
    index_id: data.id,
    // 药品ID
    id: data.drug.id,
    // 药品名称
    drug_name: data.drug.drug_name,
    // 药品数量
    number: data.drug.number,
    // 药品使用数量信息
    use_num: drugTime.value.find((item) => item.id === data.drug.time_id),
    // 药品使用类型信息
    use_type: drugUseType.value.find((item) => item.id === data.drug.type_id),
    // 药品使用频率信息
    use_frequency: drugUseFrequency.value.find(
      (item) => item.id === data.drug.frequency_id,
    ),
    // 药品单位信息
    unit: drugUnit.value.find((item) => item.id === data.drug.unit_id),
    // 药品价格
    price: data.price,
    buy_price: data.buy_price,
    // 药品使用方式ID
    way_id: data.drug?.way_id,
    // 药品使用方式信息
    use_ways: drugUseWay.value.find((item) => item.id === data.drug.way_id),
    // 药品使用时间ID
    time_id: data.drug.time_id,
    // 药品类型ID
    type_id: data.drug.type_id,
    // 药品使用频率ID
    frequency_id: data.drug.frequency_id,
    // 药品单位ID
    unit_id: data.drug.unit_id,
    // 药品图片
    image: data.drug.image,
    // 药品说明书
    instruction: data.drug.instruction,
    // 药品类型
    type: data.drug.type,
  };
  currentDrugs.value[selectChineseIndex.value] = newProduct;
  updateLocalStorage();
  // const data = drugList.value.find((v) => v.drug_id === id);
  setTimeout(() => {
    // 获取新药品卡片中的克数输入框并聚焦
    const newDrugNumberInput = document.querySelector(
      `.old-number-input-${selectChineseIndex.value} input`,
    );
    if (newDrugNumberInput) {
      (newDrugNumberInput as HTMLElement).focus();
    }
  }, 100);
}

/**
 * 写入当前修改的下标
 * @param index
 */
function setSelectChineseIndex(index, id) {
  selectChineseIndex.value = index;
  selectChineseId.value = id;
}

/**
 * 查询中药列表
 * @param inputValue
 */
function searchOption(inputValue) {
  getDrugListByWesternModal(inputValue);
}

/**
 * 添加中药
 */
function addDrugByChinese() {
  if (guardSpecialPrescriptionCartEdit()) return;
  // 如果是新药品输入框，调用添加新药品方法
  const check = currentDrugs.value.find(
    (v) => v.id === newDrugInfo.value.id,
  );
  if (check) {
    message.error('该药品已经在处方中了！');
    return;
  }
  const data = drugList.value.find(
    (v) => v.drug_id === newDrugInfo.value.id,
  );
  if (data === null || data === undefined) {
    message.error('请选择药品');
    return;
  }
  data.drug.number = newDrugInfo.value.number;
  data.drug.way_id = newDrugInfo.value.way_id;
  addProducts(data);
  newDrugInfo.value = {};
}
/**
 * 添加操作
 */
function selectDrugByNewDrugInfo(event: KeyboardEvent, isNewDrug: boolean) {
  // 如果按下的是回车键
  if (event.key === 'Enter') {
    // 阻止默认行为（防止表单提交）
    event.preventDefault();

    if (isNewDrug) {
      // 如果是新药品输入框，调用添加新药品方法
      addDrugByChinese();
    } else {
      // 如果是已有药品输入框，调用更新数量方法
      updateChineseNumber();
    }
    setTimeout(() => {
      // 获取新药品卡片中的克数输入框并聚焦
      const newDrugNumberInput = document.querySelector(
        '.new-select-drug-name input',
      );
      if (newDrugNumberInput) {
        (newDrugNumberInput as HTMLElement).focus();
      }
    }, 100);
  }
}

/**
 * 添加商品到处方
 * @param {object} data - 商品对象
 */
function addProducts(data) {
  if (guardSpecialPrescriptionCartEdit()) return;
  // 查找是否已存在于选择列表中
  const existItem = currentDrugs.value.find(
    (item) => item.index_id === data.id,
  );

  if (existItem) {
    message.warn('已经存在了');
    return;
  }
  // 创建新的商品对象（避免直接修改原始数据）
  const newProduct = {
    // 索引ID（用于在列表中查找）
    index_id: data.id,
    // 药品ID
    id: data.drug.id,
    // 药品名称
    drug_name: data.drug.drug_name,
    // 药品数量
    number: data.drug.number,
    // 药品使用数量信息
    use_num: drugTime.value.find((item) => item.id === data.drug.time_id),
    // 药品使用类型信息
    use_type: drugUseType.value.find((item) => item.id === data.drug.type_id),
    // 药品使用频率信息
    use_frequency: drugUseFrequency.value.find(
      (item) => item.id === data.drug.frequency_id,
    ),
    // 药品单位信息
    unit: drugUnit.value.find((item) => item.id === data.drug.unit_id),
    // 药品价格
    price: data.price,
    buy_price: data.buy_price,
    // 药品使用方式ID
    way_id: data.drug?.way_id,
    // 药品使用方式信息
    use_ways: drugUseWay.value.find((item) => item.id === data.drug.way_id),
    // 药品使用时间ID
    time_id: data.drug.time_id,
    // 药品类型ID
    type_id: data.drug.type_id,
    // 药品使用频率ID
    frequency_id: data.drug.frequency_id,
    // 药品单位ID
    unit_id: data.drug.unit_id,
    // 药品图片
    image: data.drug.image,
    // 药品说明书
    instruction: data.drug.instruction,
    // 药品类型
    type: data.drug.type,
  };

  // 首次添加，初始化数量为1
  newProduct.select_number = 1;

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

  // 更新本地存储
  updateLocalStorage();

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

/**
 * 处理DrugSearchSelect组件的select事件（用于新类型：3,5,6,7）
 * @param drug 选中的药品数据
 */
function handleSimpleProductSelect(drug: any) {
  if (guardSpecialPrescriptionCartEdit()) return;
  // 检查是否已存在
  const existItem = currentDrugs.value.find(
    (item) => 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,
    instruction: drug.drug?.instruction || drug.instruction || '',
    type: drug.drug?.type || drug.type || activeCategory.value,
    select_number: 1,
  };

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

  // 更新本地存储
  updateLocalStorage();

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

const newDrugInfo = ref({});

/**
 * 获取转诊信息
 * @param transferPrescriptionId 转诊处方ID
 */
const fetchTransferPrescription = async (transferPrescriptionId: number) => {
  if (!transferPrescriptionId) return;

  loadingTransfer.value = true;
  try {
    // 通过转诊处方ID获取转诊信息
    // 注意：这里需要根据实际API调整，可能需要通过register_id获取
    const registerId = Number.parseInt(localStorage.getItem(`doctorReception-id`));
    if (registerId) {
      const res = await getTransferPrescriptionByRegisterApi(registerId);
      const data = res?.result || res?.data || res;
      if (data && data.id) {
        transferPrescription.value = data;
      } else {
        transferPrescription.value = null;
      }
    }
  } catch (error) {
    console.error('获取转诊信息失败:', error);
    transferPrescription.value = null;
  } finally {
    loadingTransfer.value = false;
  }
};

/**
 * 处理转诊导入成功
 */
const handleTransferImportSuccess = () => {
  // 转诊导入成功后，可以刷新患者信息
  if (selectPatientId.value) {
    getPatientItem(selectPatientId.value).then((value) => {
      patientInfo.value = value;
      userPatientHealthInquiry.value = value.user_patient_health_inquiry;
      prescriptionList.value = value.prescription;
    });
  }
};

function switchStore(id) {
  switchStoreApi({store_id: id}).then(() => {
    myStoreId.value = id;
    updateLocalStorageStoreInfo();
    // 根据id在storeList中查找诊所名称
    const storeInfo = myStoreList.value.find((item) => item.id === id);
    message.success(`已经切换到【${storeInfo.name}】`);
  });
}

/**
 * 储存本地缓存
 */
function updateLocalStorageStoreInfo() {
  localStorage.setItem(`myStoreId`, myStoreId.value);
  userStore.userInfo.store_id = myStoreId.value;
  userStore.setUserInfo(userStore.userInfo);
  tabType.value = 0;
  getPatientListByReception();
}
const leftShow = ref(true)
// 获取doctorReceptionLeftShow
function getDoctorReceptionLeftShow() {
  const localStorageLeftShow = localStorage.getItem(`doctorReceptionLeftShow`);
  leftShow.value = localStorageLeftShow !== 'false';
}
getDoctorReceptionLeftShow();
// 监听leftShow存入缓存
watch(
  () => leftShow.value,
  async (enable) => {
    localStorage.setItem(`doctorReceptionLeftShow`, enable);
  },
  {
    immediate: true,
  },
);
</script>

<template>
  <div :class="leftShow === true? 'container-box-grid':'container-box'">
    <RefusalOfTreatmentModals />
    <InfoModalComponent />
<!--    如果leftShow === true展示收起，反之则显示展开-->
    <div>
      <Button :class="`${leftShow === true? 'w-full': 'sticky top-5 left-5'}`" type="primary" @click="leftShow = !leftShow">{{ leftShow === true ? '收起患者列表' : '展开患者列表' }}</Button>
      <!-- 左侧患者列表 -->
      <div v-if="leftShow" class="patient-panel">
        <Select v-model:value="myStoreId" class="w-full" @change="switchStore">
          <SelectOption v-for="item in myStoreList" :value="item.id">
            {{ item.name }}
          </SelectOption>
        </Select>
        <RadioGroup
          v-model:value="listType"
          class="w-full"
          style="text-align: center"
          @change="updatePatientList"
        >
          <RadioButton :value="1" class="w-1/2">当前</RadioButton>
          <RadioButton :value="2" class="w-1/2">历史</RadioButton>
        </RadioGroup>
        <div
          v-for="(patient, index) in patients"
          :key="index"
        >

          <div
            v-if="patient.user_patient"
            :class="{ active: selectPatientId === patient.id }"
            class="patient-card"
            @click="selectPatient(patient)"
          >
            <div class="patient-info">
              <h3 class="flex flex-wrap items-center gap-2">
                {{ patient.user_patient.name }}
                <Tag
                  v-if="patient.special_prescription_patient_record"
                  :color="patient.special_prescription_patient_record.status === 0 ? 'orange' : 'default'"
                >
                  特色方{{
                    patient.special_prescription_patient_record.status === 0
                      ? '·待导入'
                      : ''
                  }}
                </Tag>
              </h3>
              <p class="phone">{{ patient.user_patient.mobile }}</p>
              <p class="text-sm text-gray-500">
                推广员：{{ patient.salesperson?.nick_name || '无' }}
              </p>
              <span :class="getRegisterStatus(patient.status)" class="status">{{
                  getRegisterStatus(patient.status)
                }}</span>
              {{ patient.updated_at }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧处方区域 -->
    <Page v-if="tabType === 1" class="prescription-panel">
      <div class="prescription-header">
        <Button
          v-if="receptionStatus === 1"
          class="send-btn"
          type="primary"
          @click="reception"
        >
          接诊
        </Button>
        <Button
          v-if="receptionStatus === 1"
          class="send-btn"
          type="primary"
          danger
          @click="refuseReception"
        >
          拒诊
        </Button>
        <Button
          v-if="receptionStatus === 2"
          class="send-btn"
          type="primary"
          @click="showPrescription"
        >
          开具处方
        </Button>
        <Button
          v-if="receptionStatus === 2"
          class="mb-10 ml-10"
          danger
          type="primary"
          @click="endOfDiagnosis"
        >
          结束诊断
        </Button>
      </div>
      <div class="prescription-content">
        <Descriptions
          :column="{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }"
          bordered
          title="患者信息"
        >
          <Descriptions.Item label="患者姓名">
            {{ activePatient.name }}
          </Descriptions.Item>
          <Descriptions.Item label="患者年龄">
            {{ activePatient.age }}
          </Descriptions.Item>
          <Descriptions.Item label="患者性别">
            {{
              activePatient.sex === 1
                ? '男'
                : activePatient.sex === 2
                  ? '女'
                  : '未填写'
            }}
          </Descriptions.Item>
        </Descriptions>
        <SpecialPrescriptionImportCard
          v-if="specialPrescriptionRecord && hasSpecialPrescriptionRecord"
          :record="specialPrescriptionRecord"
          :purchase-label="specialPrescriptionPurchaseLabel"
          :loading="applyingSpecialPrescription"
          @apply="handleApplySpecialPrescription(true)"
        />
        <Descriptions
          v-if="userPatientHealthInquiry"
          :column="{ xxl: 2, xl: 2, lg: 2, md: 2, sm: 2, xs: 2 }"
          bordered
          class="mt-5"
          title="健康信息"
        >
          <Descriptions.Item label="肝功能">
            <span>{{
                userPatientHealthInquiry.liver_function === 0 ? '正常' : '异常'
              }}</span>
            <p
              v-if="userPatientHealthInquiry.liver_function === 1"
              class="mt-3"
            >
              <Tag
                v-for="item in splitString(
                  userPatientHealthInquiry.liver_index,
                )"
                color="#455cda"
              >
                {{ item }}
              </Tag>
            </p>
          </Descriptions.Item>
          <Descriptions.Item label="肾功能">
            <span>{{
                userPatientHealthInquiry.renal_function === 0 ? '正常' : '异常'
              }}</span>
            <p
              v-if="userPatientHealthInquiry.renal_function === 1"
              class="mt-3"
            >
              <Tag
                v-for="item in splitString(
                  userPatientHealthInquiry.renal_index,
                )"
                color="#455cda"
              >
                {{ item }}
              </Tag>
            </p>
          </Descriptions.Item>
          <Descriptions.Item label="既往史">
            <span>{{
                userPatientHealthInquiry.person_status === 0 ? '无' : '有'
              }}</span>
            <p v-if="userPatientHealthInquiry.person_status === 1" class="mt-3">
              <Tag
                v-for="item in splitString(
                  userPatientHealthInquiry.person_history,
                )"
                color="#455cda"
              >
                {{ item }}
              </Tag>
            </p>
          </Descriptions.Item>
          <Descriptions.Item label="过敏史">
            <span>{{
                userPatientHealthInquiry.allergic_status === 0 ? '无' : '有'
              }}</span>
            <p
              v-if="userPatientHealthInquiry.allergic_status === 1"
              class="mt-3"
            >
              <Tag
                v-for="item in splitString(
                  userPatientHealthInquiry.allergic_history,
                )"
                color="#455cda"
              >
                {{ item }}
              </Tag>
            </p>
          </Descriptions.Item>
          <Descriptions.Item label="家庭遗传史">
            <span>{{
                userPatientHealthInquiry.family_status === 0 ? '无' : '有'
              }}</span>
            <p v-if="userPatientHealthInquiry.family_status === 1" class="mt-3">
              <Tag
                v-for="item in splitString(
                  userPatientHealthInquiry.family_history,
                )"
                color="#455cda"
              >
                {{ item }}
              </Tag>
            </p>
          </Descriptions.Item>
        </Descriptions>

        <Descriptions
          :column="{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }"
          class="mt-5"
          title="处方记录"
        >
          <Descriptions.Item>
            <Timeline>
              <TimelineItem v-for="item in prescriptionList" :key="item.id">
                <Tag color="#455cda">{{ item.prescription_no }}</Tag>
                <Button type="link" @click="openPrescriptionDetail(item.id)">
                  查看处方
                </Button>
                <Button
                  v-if="item.can_withdraw"
                  danger
                  type="link"
                  @click="confirmWithdrawPrescription(item)"
                >
                  撤回
                </Button>
                <Button type="link" @click="reusePrescriptionFromList(item.id)">
                  复用
                </Button>
                <span class="time-line-item-created">{{
                    item.created_at
                  }}</span>
                <Tag class="ml-5" :color="item.category === 1? '' : '#455cda'">
                  {{
                    item.prescription_type === 1 ? '中药处方' :
                    item.prescription_type === 2 ? '西药处方' :
                    item.prescription_type === 3 ? '保健食品' :
                    item.prescription_type === 5 ? '产品服务包' :
                    item.prescription_type === 6 ? '非药品' :
                    item.prescription_type === 7 ? '医疗器械' :
                    '未知类型'
                  }} /
                  {{ item.category === 1 ? '自费' : '医保' }}
                </Tag>

                <template v-if="Number(item.cancel_status) === 1">
                  <Tag color="default">
                    {{
                      String(item.cancel_remark || '').includes('医生撤回')
                        ? '已撤回'
                        : '已取消'
                    }}
                  </Tag>
                </template>
                <template v-else>
                  <Tag v-if="item.status === 0" color="warning">待审核</Tag>
                  <Tag v-else-if="item.status === 1" color="success">已通过</Tag>
                  <Tag v-else-if="item.status === 2" color="error">未通过</Tag>
                  <Tag v-else-if="item.status === 3" color="#455cda">无需审核</Tag>
                  <Tag v-else-if="item.status === 4" color="#455cda">无需审核</Tag>
                </template>
                <Tag color="#455cda">处方ID：{{ item.id }}</Tag>
                <!--                <Tag class="ml-5">-->
                <!--                  {{ item.category === 1 ? '自费' : '医保' }}-->
                <!--                </Tag>-->
              </TimelineItem>
            </Timeline>
          </Descriptions.Item>
        </Descriptions>

        <!-- 转诊处方卡片 -->
        <div v-if="transferPrescription" class="transfer-section mt-5">
          <TransferPrescriptionCard
            :transfer-data="transferPrescription"
            :register-id="doctorReceptionRegisterId"
            @import-success="handleTransferImportSuccess"
          />
        </div>
      </div>
    </Page>

    <Page v-if="tabType === 2" class="prescription-panel">
      <Button class="mb-10" type="primary" @click="tabType = 1">
        返回上一页
      </Button>

      <div class="prescription-header">
        <h2>{{ activePatient.name }} 的处方</h2>
      </div>

      <!-- 药品分类导航 -->
      <div class="drug-categories">
        <button
          v-for="category in categories"
          :key="category.value"
          :class="{ active: activeCategory === category.value }"
          @click="tabChange(category.value)"
        >
          {{ category.label }}
        </button>
      </div>

      <SpecialPrescriptionImportCard
        v-if="hasSpecialPrescriptionRecord"
        class="mt-5 max-w-xl"
        :record="specialPrescriptionRecord"
        :purchase-label="specialPrescriptionPurchaseLabel"
        :loading="applyingSpecialPrescription"
        @apply="() => handleApplySpecialPrescription()"
      />

      <div class="mt-5">
        <Button
          v-if="activeCategory === 2 && !isSpecialPrescriptionCartLocked"
          type="primary"
          @click="openWesternModal"
        >
          添加商品
        </Button>
        <Button
          v-if="canUseCommonPrescription"
          type="primary"
          :class="activeCategory !== 1 ? 'ml-3' : ''"
          @click="openCommonPrescriptionModal"
        >
          选择常用方
        </Button>
        <Button
          v-if="canUseCommonPrescription"
          type="default"
          class="ml-3"
          @click="openSaveCommonPrescriptionModal"
        >
          <SaveOutlined />
          保存常用方
        </Button>
        <Button
          type="default"
          danger
          class="ml-3"
          @click="handleClearPrescriptionCart"
        >
          清空药方
        </Button>
        <Button
          v-if="activeCategory === 1 && hasSalespersonTransfer"
          type="default"
          class="ml-3"
          @click="salespersonTransferDrawerOpen = true"
        >
          查看传方
        </Button>
        <RadioGroup
          v-if="allowInsuranceCategory === 1"
          v-model:value="category"
          class="ml-5"
        >
          <RadioButton :value="1">自费</RadioButton>
          <RadioButton :value="2">医保</RadioButton>
        </RadioGroup>
      </div>
      <SalespersonTransferDrawer
        v-model:open="salespersonTransferDrawerOpen"
        :register-id="doctorReceptionRegisterId"
        @import="handleSalespersonTransferImport"
      />
      <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"
            :src="image"
            :width="200"
          />
        </ImagePreviewGroup>
      </div>
      <!-- 已选药品列表 -->
      <!-- 中药 -->
      <div v-if="activeCategory === 1" class="mb-5 mt-3 flex" style="flex-wrap: wrap; width: 100%;">
        <Row>
          <Col
            v-for="(drug, index) in currentDrugs"
            :key="`${drug.index_id || drug.id}-${index}`"
            :lg="12"
            :md="24"
            :sm="24"
            :xl="leftShow ? 12 : 8"
            :xs="leftShow ? 12 : 8"
            :xxl="leftShow ? 8 : 6"
          >
            <Card class="mt-0" title="">
              <div>
                <span class="card-index">{{ index + 1 }}、</span>
                <p>
                  <Select
                    v-model:value="drug.id"
                    :disabled="isSpecialPrescriptionCartLocked"
                    :filter-option="false"
                    class="old-select-drug-name"
                    style="min-width: 100px"
                    placeholder="药名"
                    show-search
                    @change="selectOldDrugInfo"
                    @dropdown-visible-change="
                      setSelectChineseIndex(index, drug.id)
                    "
                    @search="searchOption"
                  >
                    <SelectOption v-if="drugList.length === 0" :value="drug.id">
                      {{ drug.drug_name }}
                    </SelectOption>
                    <SelectOption
                      v-for="(value, index) in drugList"
                      v-else
                      :key="index"
                      :value="value.drug.id"
                    >
                      {{ value.drug.drug_name }}
                    </SelectOption>
                  </Select>
                  ,
                  <InputNumber
                    v-model:value="drug.number"
                    :disabled="isSpecialPrescriptionCartLocked"
                    :class="`w-1/5 old-number-input-${index}`"
                    style="min-width: 100px"
                    :controls="false"
                    @blur="updateChineseNumber"
                    @keydown="updateChineseNumberGoNewDrug($event)"
                  >
                    <template #addonAfter> g</template>
                  </InputNumber>
                  ,
                  <span>
                    <Select
                      :value="drug?.way_id"
                      :disabled="isSpecialPrescriptionCartLocked"
                      placeholder="用法"
                      @change="selectDrugUseWayChange"
                      @dropdown-visible-change="
                        selectProductChange(index)
                      "
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(value, index) in drugUseWay"
                        :key="index"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>
                  </span>
                  <p class="card-price">
                    ￥<span>{{ (drug.price * drug.number).toFixed(2) }}</span>
                    <span
                      v-if="getChineseItemMargin(drug) && getChineseItemMargin(drug) !== '--'"
                      class="ml-2 text-gray-500 text-sm"
                    >
                      毛利率 {{ getChineseItemMargin(drug) }}%
                    </span>
                  </p>
                  <Button
                    v-if="!isSpecialPrescriptionCartLocked"
                    class="card-delete"
                    type="link"
                    @click="removeDrug(index)"
                  >
                    <DeleteTwoTone/>
                  </Button>
                </p>
              </div>
            </Card>
          </Col>
          <Col
            v-if="!isSpecialPrescriptionCartLocked"
            :lg="12"
            :md="12"
            :sm="12"
            :xl="leftShow ? 12 : 8"
            :xs="leftShow ? 12 : 8"
            :xxl="leftShow ? 8 : 6"
          >
            <Card title="">
              <div>
                <span class="card-index">{{ currentDrugs.length + 1 }}、</span>
                <div>
                  <Select
                    v-model:value="newDrugInfo.id"
                    :filter-option="false"
                    class="new-select-drug-name w-1/5"
                    placeholder="药名"
                    show-search
                    style="min-width: 100px"
                    @change="selectNewDrugInfo"
                    @search="searchOption"
                  >
                    <SelectOption
                      v-for="(value, index) in drugList"
                      :key="index"
                      :value="value.drug_id"
                    >
                      {{ value.drug.drug_name }}
                    </SelectOption>
                  </Select>
                  ,
                  <InputNumber
                    v-model:value="newDrugInfo.number"
                    class="new-number-input w-1/5"
                    style="min-width: 100px"
                    @blur="newDrugBlur"
                    @keydown="selectDrugByNewDrugInfo($event, true)"
                  >
                    <template #addonAfter> g</template>
                  </InputNumber>
                  ,
                  <span>
                    <Select
                      v-model:value="newDrugInfo.way_id"
                      placeholder="用法"
                      @keydown="selectDrugByNewDrugInfo($event, true)"
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(value, index) in drugUseWay"
                        :key="index"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>
                  </span>
                  <p class="card-price">
                    ￥<span>{{
                      (
                        (newDrugInfo.price || 0) * (newDrugInfo.number || 1)
                      ).toFixed(2)
                    }}元</span>
                  </p>
                </div>
              </div>
            </Card>
          </Col>
          <!-- 不知道为什么会出问题 -->
          <Col
            v-if="currentDrugs.length < 3"
            :lg="12"
            :md="24"
            :sm="24"
            :xl="12"
            :xs="24"
            :xxl="8"
          >

            <Card title="" style="opacity: 0">
              <div>
                <span class="card-index">{{ currentDrugs.length + 1 }}、</span>
                <div>
                  <Select
                    v-model:value="newDrugInfo.id"
                    :filter-option="false"
                    class="new-select-drug-name w-1/5"
                    style="min-width: 100px"
                    placeholder="药名"
                    show-search
                    @change="selectNewDrugInfo"
                    @search="searchOption"
                    disabled
                  >
                    <SelectOption
                      v-for="(value, index) in drugList"
                      :key="index"
                      :value="value.drug_id"
                      disabled
                    >
                      {{ value.drug.drug_name }}
                    </SelectOption>
                  </Select>
                  ,
                  <InputNumber
                    v-model:value="newDrugInfo.number"
                    class="new-number-input w-1/5"
                    style="min-width: 100px"
                    @blur="updateChineseNumber"
                    @keydown="selectDrugByNewDrugInfo($event, true)"
                    disabled
                  >
                    <template #addonAfter> g</template>
                  </InputNumber>
                  ,
                  <span>
                    <Select
                      v-model:value="newDrugInfo.way_id"
                      placeholder="用法"
                      @keydown="selectDrugByNewDrugInfo($event, true)"
                      disabled
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(value, index) in drugUseWay"
                        :key="index"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>
                  </span>
                  <p class="card-price">
                    ￥<span>{{
                      (
                        (newDrugInfo.price || 0) * (newDrugInfo.number || 1)
                      ).toFixed(2)
                    }}元</span>
                  </p>
                </div>
              </div>
            </Card>
          </Col>
          <Col
            v-if="currentDrugs.length < 3"
            :lg="12"
            :md="24"
            :sm="24"
            :xl="12"
            :xs="24"
            :xxl="8"
          >

            <Card title="" style="opacity: 0">
              <div>
                <span class="card-index">{{ currentDrugs.length + 1 }}、</span>
                <div>
                  <Select
                    v-model:value="newDrugInfo.id"
                    :filter-option="false"
                    class="new-select-drug-name w-1/5"
                    style="min-width: 100px"
                    placeholder="药名"
                    show-search
                    @change="selectNewDrugInfo"
                    @search="searchOption"
                    disabled
                  >
                    <SelectOption
                      v-for="(value, index) in drugList"
                      :key="index"
                      :value="value.drug_id"
                      disabled
                    >
                      {{ value.drug.drug_name }}
                    </SelectOption>
                  </Select>
                  ,
                  <InputNumber
                    v-model:value="newDrugInfo.number"
                    class="new-number-input w-1/5"
                    style="min-width: 100px"
                    @blur="updateChineseNumber"
                    @keydown="selectDrugByNewDrugInfo($event, true)"
                    disabled
                  >
                    <template #addonAfter> g</template>
                  </InputNumber>
                  ,
                  <span>
                    <Select
                      v-model:value="newDrugInfo.way_id"
                      placeholder="用法"
                      @blur="updateChineseNumber"
                      @keydown="selectDrugByNewDrugInfo($event, true)"
                      disabled
                    >
                      <SelectOption :value="0">煎服</SelectOption>
                      <SelectOption
                        v-for="(value, index) in drugUseWay"
                        :key="index"
                        :value="value.id"
                      >
                        {{ value.name }}
                      </SelectOption>
                    </Select>
                  </span>
                  <p class="card-price">
                    ￥<span>{{
                      (
                        (newDrugInfo.price || 0) * (newDrugInfo.number || 1)
                      ).toFixed(2)
                    }}元</span>
                  </p>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
      <!-- 西（中成）药列表（type=2） -->
      <div v-else-if="activeCategory === 2" class="selected-drugs">
        <div class="drug-table">
          <div class="table-header">
            <span v-if="activeCategory !== 1">商品图片</span>
            <span>商品名称</span>
            <span>数量</span>
            <span>单价</span>
            <span>操作</span>
          </div>
          <div class="table-body">
            <div
              v-for="(drug, index) in currentDrugs"
              :key="drug.id"
              class="table-row"
            >
              <div
                v-if="activeCategory !== 1"
                style="width: 120px; margin: 0 auto"
              >
                <Image :src="drug.image"/>
              </div>
              <div>
                <p>
                  <span>药品名称：{{ drug.drug_name }}</span>
                </p>
                <!-- 西药用法显示/编辑模式 -->
                <p v-if="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="activeCategory !== 1 && drug.isEditing" class="edit-usage-form">
                  <span>用法：</span>
                  <Select
                    :value="drug.use_type?.id"
                    :disabled="isSpecialPrescriptionCartLocked"
                    size="small"
                    style="width: 80px"
                    @change="(val) => updateDrugUsage(index, 'use_type', drugUseType.find(item => item.id === val))"
                  >
                    <SelectOption v-for="item in drugUseType" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </SelectOption>
                  </Select>
                  <Select
                    :value="drug.use_frequency?.id"
                    :disabled="isSpecialPrescriptionCartLocked"
                    size="small"
                    style="width: 100px; margin-left: 4px"
                    @change="(val) => updateDrugUsage(index, 'use_frequency', drugUseFrequency.find(item => item.id === val))"
                  >
                    <SelectOption v-for="item in drugUseFrequency" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </SelectOption>
                  </Select>
                  <Select
                    :value="drug.use_num?.id"
                    :disabled="isSpecialPrescriptionCartLocked"
                    size="small"
                    style="width: 80px; margin-left: 4px"
                    @change="(val) => updateDrugUsage(index, 'use_num', drugTime.find(item => item.id === val))"
                  >
                    <SelectOption v-for="item in drugTime" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </SelectOption>
                  </Select>
                  <span style="margin-left: 4px">每次</span>
                  <InputNumber
                    v-model:value="drug.number"
                    :disabled="isSpecialPrescriptionCartLocked"
                    :min="1"
                    size="small"
                    style="width: 60px; margin-left: 4px"
                  />
                  <Select
                    :value="drug.unit?.id"
                    :disabled="isSpecialPrescriptionCartLocked"
                    size="small"
                    style="width: 60px; margin-left: 4px"
                    @change="(val) => updateDrugUsage(index, 'unit', drugUnit.find(item => item.id === val))"
                  >
                    <SelectOption v-for="item in drugUnit" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </SelectOption>
                  </Select>
                </div>
              </div>
              <div>
                <div v-if="activeCategory === 1" class="quantity-control">
                  <InputNumber
                    v-model:value="drug.select_number"
                    class="w-full"
                    @blur="updateChineseNumber"
                  >
                    <template #addonAfter> g</template>
                  </InputNumber>
                </div>
                <div v-else class="quantity-control">
                  <Button type="primary" :disabled="isSpecialPrescriptionCartLocked" @click="decrement(index)">-</Button>
                  <span style="margin: 0 20px">{{ drug.select_number }}</span>
                  <Button type="primary" :disabled="isSpecialPrescriptionCartLocked" @click="increment(index)">+</Button>
                </div>
              </div>
              <span>{{ drug.price }}</span>
              <div>
                <Button
                  v-if="activeCategory !== 1 && !drug.isEditing && !isSpecialPrescriptionCartLocked"
                  type="link"
                  @click="toggleEditDrug(index)"
                >编辑</Button>
                <Button
                  v-if="activeCategory !== 1 && drug.isEditing"
                  type="link"
                  @click="saveEditDrug(index)"
                >保存</Button>
                <Button v-if="!isSpecialPrescriptionCartLocked" type="link" @click="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(activeCategory)" class="selected-drugs">
        <!-- 搜索组件 -->
        <div class="mb-5">
          <DrugSearchSelect
            v-if="!isSpecialPrescriptionCartLocked"
            :type="activeCategory"
            :store-id="myStoreId"
            :placeholder="`输入${categories.find(c => c.value === 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 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" :disabled="isSpecialPrescriptionCartLocked" @click="decrement(index)">-</Button>
                  <span style="margin: 0 20px">{{ drug.select_number }}</span>
                  <Button type="primary" :disabled="isSpecialPrescriptionCartLocked" @click="increment(index)">+</Button>
                </div>
              </div>
              <span>{{ drug.price }}</span>
              <div>
                <Button v-if="!isSpecialPrescriptionCartLocked" type="link" @click="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">
        <div v-if="activeCategory === 1" class="mb-5">
          <RadioGroup v-model:value="ruleType" :disabled="isSpecialPrescriptionCartLocked">
            <RadioButton :value="1">自制剂</RadioButton>
            <RadioButton :value="2">委托调剂</RadioButton>
          </RadioGroup>
          <div v-if="ruleType === 1">
            <!-- 选择包法-->
            <Select
              :value="packageMethodId"
              :disabled="isSpecialPrescriptionCartLocked"
              class="mt-3 w-1/5"
              placeholder="请选择包法"
              @change="selectPackageMethod"
            >
              <SelectOption
                v-for="(value, index) in packageMethod"
                :key="index"
                :value="value.value"
              >
                {{ value.label }}
              </SelectOption>
            </Select>
          </div>
          <div v-else-if="ruleType === 2">
            <!-- 选择制剂-->
            <Select
              v-model:value="processRuleId"
              :disabled="isSpecialPrescriptionCartLocked"
              class="mt-3 w-1/5"
              placeholder="请选择制剂"
              @change="selectProcessRule"
            >
              <SelectOption
                v-for="(value, index) in processRuleList"
                :key="index"
                :value="value.id"
              >
                {{ value.name }}
              </SelectOption>
            </Select>
            <!-- 选择规格-->
            <Select
              v-model:value="childProcessRuleId"
              :disabled="isSpecialPrescriptionCartLocked"
              class="ml-3 mt-3 w-1/5"
              placeholder="请选择煎法"
              @change="selectProcessRuleNot"
            >
              <SelectOption
                v-for="(value, index) in childProcessRuleList"
                :key="index"
                :value="value.id"
              >
                {{ value.name }}
              </SelectOption>
            </Select>
            <!-- 选择备注-->
            <Select
              v-model:value="processRuleNoteId"
              :disabled="isSpecialPrescriptionCartLocked"
              class="ml-3 mt-3 w-1/5"
              placeholder="请选择备注"
              @change="selectProcessRuleNotCommit"
            >
              <SelectOption
                v-for="(value, index) in processRuleNoteList"
                :key="index"
                :value="value.id"
              >
                {{ value.note }}
              </SelectOption>
            </Select>
          </div>
          <div class="mt-5">
            用量：
            <InputNumber v-model:value="dosage" :disabled="isSpecialPrescriptionCartLocked" class="w-1/5">
              <template #addonBefore>
                <MinusOutlined
                  key="prop"
                  @click="!isSpecialPrescriptionCartLocked && (dosage = dosage > 1 ? dosage - 1 : 1)"
                />
              </template>
              <template #addonAfter>
                <PlusOutlined
                  key="add"
                  @click="!isSpecialPrescriptionCartLocked && (dosage = dosage < 100 ? dosage + 1 : 100)"
                />
              </template>
            </InputNumber>
            天 / {{ dosage }} 剂
          </div>
          <div class="mt-5">
            频次：
            <InputNumber v-model:value="dayDosage" :disabled="isSpecialPrescriptionCartLocked" class="w-1/5">
              <template #addonBefore>
                <MinusOutlined
                  key="prop"
                  @click="!isSpecialPrescriptionCartLocked && (dayDosage = dayDosage > 1 ? dayDosage - 1 : 1)"
                />
              </template>
              <template #addonAfter>
                <PlusOutlined
                  key="add"
                  @click="!isSpecialPrescriptionCartLocked && (dayDosage = dayDosage < 100 ? dayDosage + 1 : 100)"
                />
              </template>
            </InputNumber>
            次/天
          </div>
        </div>
        <Button type="primary" @click="openDiagnosisModal">
          常用诊断
        </Button>
        <Textarea
          v-model:value="diagnosis"
          placeholder="输入诊断结果..."
        />
        <Button type="primary" @click="openDoctorOrderModal">
          常用医嘱
        </Button>
        <Textarea
          v-model:value="medicalAdvice"
          placeholder="输入医嘱..."
        />
        诊疗费用：
        <InputNumber
          v-model:value="treatmentPrice"
          placeholder="请输入诊疗价格"
        >
          <template #addonAfter> /元</template>
        </InputNumber>
      </div>

      <!-- 费用总计 -->
      <div class="price-box">
        <div class="total-cost">加工费：¥{{ processingFee.toFixed(2) }}</div>
        <div class="total-cost">
          商品价格：
          <Button
            v-if="priceAdjustEnabled && currentDrugs.length && !isSpecialPrescriptionCartLocked"
            type="link"
            class="!p-0"
            @click="openOrderPriceAdjust"
          >
            ¥{{ totalProductCost.toFixed(2) }}
          </Button>
          <template v-else>¥{{ totalProductCost.toFixed(2) }}</template>
          <span
            v-if="chineseGrossMarginPercent !== null"
            class="ml-3 text-orange-600"
          >
            毛利率 {{ chineseGrossMarginPercent }}%
          </span>
        </div>
        <div class="total-cost">总计：¥{{ totalCost.toFixed(2) }}</div>

        <div v-if="priceAdjustEnabled && currentDrugs.length" class="mt-2 text-sm text-gray-600">
          当前浮动：{{ priceDiscountLabel || '无' }}
          <Button v-if="priceDiscount !== 100" type="link" size="small" @click="clearCartPriceDiscount">
            清除浮动
          </Button>
        </div>

        <Button
          v-if="activeCategory === 1"
          class="mt-5 w-full"
          style="display: block"
          type="primary"
          @click="checkChineseMedicineConflict"
        >
          发送处方
        </Button>
        <Button
          v-else
          class="mt-5 w-full"
          style="display: block"
          type="primary"
          @click="sendPrescription"
        >
          发送处方
        </Button>
        <Button
          v-if="canUseCommonPrescription && currentDrugs.length"
          type="link"
          class="mt-2 w-full"
          @click="openSaveCommonPrescriptionModal"
        >
          保存为常用方
        </Button>
      </div>
    </Page>
    <div v-else-if="tabType === 0" class="prescription-panel">
      <Empty/>
    </div>
    <DiagnosisModals/>
    <DoctorOrderModals/>
    <WesternDrugModal/>
    <SimpleProductModalComponent/>
    <PrescriptionDetailModal/>
    <!-- 常用方选择弹窗 -->
    <CommonPrescriptionModals/>
    <!-- 确认添加药品弹窗 -->
    <ConfirmModalComponent />
    <PriceAdjustDrawer />
    <AntModal title="二次签名" v-model:open="doctorSecondSignModal" @ok="doctorSecondSignModalOk">
      <div class="doctor-second-sign-title">有毒：</div>
      <p v-for="item in checkData.message.poisonous || []">【{{ item }}】</p>
      <div class="doctor-second-sign-title">十八反：</div>
      <p v-for="item in checkData.message.opposition || []">【{{ item }}】</p>
      <div class="doctor-second-sign-title">十九畏：</div>
      <p v-for="item in checkData.message.conflict || []">【{{ item }}】</p>
      <p class="mt-5" style="color: red;">如需继续开方需要二次签名，确认要二次签名吗？</p>
    </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">
          将当前处方（{{ 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">
          类型：{{ activeCategory === 1 ? '中药' : '西药（中成药）' }}
        </p>
      </div>
    </AntModal>
  </div>
</template>

<style scoped>
/* 覆盖antd */
:global(.ant-select-item-option-active)  {
  background-color: rgba(55, 71, 162, 0.71) !important;
  color: white !important;
}
.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;
}

.container-box {
  min-height: 90vh;
}
.container-box-grid {
  min-height: 90vh;
  display: grid;
  grid-template-columns: 300px 1fr;
}

.patient-panel {
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.dark .patient-panel {
  border-right: 1px solid #333;
}

.patient-card {
  padding: 1rem;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: all 0.3s;
}

.dark .patient-card {
  border-bottom: 1px solid #333;
}

.patient-card.active {
  border-left: 4px solid #455cda;
  background-color: rgba(69, 92, 218, 0.1);
}

.status {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8em;
}

.status.待支付 {
  background: #f4f4f5;
  color: #909399;
}

.status.待接诊 {
  background: #fef0f0;
  color: #f56c6c;
}

.status.接诊中 {
  background: #f0f9eb;
  color: #67c23a;
}

.status.已结束 {
  background: #f4f4f5;
  color: #909399;
}

.status.已取消 {
  background: #fef0f0;
  color: #f56c6c;
}

.status.待评价 {
  background: #f4f4f5;
  color: #909399;
}

.status.已评价 {
  background: #f4f4f5;
  color: #909399;
}

.status.已拒诊 {
  background: #f4f4f5;
  color: #909399;
}

.dark .status.待接诊,
.dark .status.已接诊 {
  background: #333;
}

.prescription-panel {
  padding: 1rem;
}

.drug-categories {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
}

.drug-categories button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 10px;
  cursor: pointer;
}

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

.drug-categories button.active {
  color: #fff;
  border-color: transparent;
  animation: pulse 0.5s /*infinite*/;
  animation-fill-mode: forwards;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    background: #455cda;
    transform: scale(1);
  }
}

.drug-item {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  margin: 8px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.drug-item:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

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

.table-body {
  max-height: 30vh;
  overflow-y: auto;
}

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

.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;
}

.send-btn {
  cursor: pointer;
  margin-right: 10px;
  float: right;
}

.diagnosis-area textarea {
  width: 100%;
  height: 100px;
  padding: 8px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

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

.price-box {
  position: fixed;
  right: 10px;
  bottom: 62px;
}

.total-cost {
  text-align: right;
  font-size: 1.2em;
  font-weight: bold;
  color: #f56c6c;
  margin-top: 1rem;
}

.prescription-content {
  margin-top: 3%;
}

.time-line-item-created {
  color: #909399;
  font-size: 0.8em;
}

/* 简单产品列表样式 */
.simple-product-list {
  margin: 1rem 0;
}

.selected-products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.product-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.dark .product-card {
  border-color: #333;
}

.product-card-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-image {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
}

.product-image-placeholder {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 6px;
  color: #999;
  font-size: 12px;
}

.dark .product-image-placeholder {
  background: #374151;
  color: #6b7280;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.dark .product-name {
  color: #f3f4f6;
}

.product-price {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.dark .product-price {
  color: #9ca3af;
}

.product-quantity {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.product-total {
  font-size: 16px;
  font-weight: 600;
  color: #ff4d4f;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid #e4e7ed;
}

.dark .product-actions {
  border-top-color: #333;
}
</style>
