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

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

import {
  DeleteTwoTone,
  LeftOutlined,
  RightOutlined,
  MinusOutlined,
  PlusOutlined,
  SaveOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
import {
  Modal as AntModal,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Image,
  ImagePreviewGroup,
  Input,
  InputNumber,
  message,
  RadioButton,
  RadioGroup,
  Row,
  Select,
  SelectOption,
  Tag,
  Textarea,
  Timeline,
  TimelineItem,
  Tooltip,
} from 'ant-design-vue';

import {
  saveChineseCommonPrescriptionApi,
  saveWestCommonPrescriptionApi,
} from '#/views/business/chat/api';
import { usePrescriptionStore } from '#/store/prescription';
// import { getTraditionalChineseMedicineAllApi } from '#/views/doctor/doctor-reception/api';
// 导入子组件
import DiagnosisModal from '#/views/doctor/doctor-reception/components/DiagnosisModal.vue';
import DoctorOrderModal from '#/views/doctor/doctor-reception/components/DoctorOrderModal.vue';
import PrescriptionDetail from '#/views/doctor/doctor-reception/components/PrescriptionDetail.vue';
import WesternModal from '#/views/doctor/doctor-reception/components/WesternModal.vue';
import SimpleProductModal from '#/views/doctor/doctor-reception/components/SimpleProductModal.vue';
// 常用方选择弹窗组件
import CommonPrescriptionModal from '#/views/doctor/doctor-reception/components/CommonPrescriptionModal.vue';
// 信息提示模态框
import InfoModal from '#/components/modal/InfoModal.vue';
// 药品搜索选择组件
import { DrugSearchSelect } from '#/components/drug-search-select';

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

const modalData = ref<any>();
// 修改：默认折叠 (true)
const isPatientInfoCollapsed = ref(true);
const visible = ref(false);
const previewImage = ref([]);
const showNewDrugModal = ref(false);
const doctorSecondSignModal = ref(false);

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

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

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

// 使用 Pinia store
const prescriptionStore = usePrescriptionStore();

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

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

const submittingType = ref(false);
const [Modal, modalApi] = useVbenModal({
  draggable: true,
  confirmText: '发送处方',
  submitting: submittingType.value,
  // 增加 modal 宽度以适应左右布局
  class: 'w-[95%] max-w-[1400px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    submittingType.value = true;
    await handleCheckChineseMedicineConflict();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      modalData.value = modalApi.getData<Record<string, any>>();

      if (modalData.value?.registerId) {
        // 获取存储前缀，默认为在线复诊-药店
        const storagePrefix = modalData.value?.storagePrefix || 'onlineConsultation-';

        // 使用完整初始化，包含患者信息（传递 true 以获取患者信息）
        await prescriptionStore.initializePrescription(
          modalData.value.registerId,
          true,
          storagePrefix,
        );
        prescriptionStore.loadFromLocalStorage();
        // 获取挂号诊所信息
        await prescriptionStore.fetchRegisterStoreInfo();
        
        // 如果恢复的处方类型是中药，检测并显示转诊提示
        if (prescriptionStore.activeCategory === 1) {
          await checkAndShowTransferTip();
        }
      } else {
        console.warn('未提供registerId');
      }
    }
  },
});

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

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

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

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

const [DoctorOrderModals, DoctorOrderModalApi] = useVbenModal({
  connectedComponent: DoctorOrderModal,
});

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

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

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

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

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

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

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

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

  const storeInfo = prescriptionStore.registerStoreInfo;

  if (storeInfo?.is_from_transfer === 1 && storeInfo?.delegate_store_id) {
    await executeSendPrescription(doctorSecondSignValue, 1, storeInfo.delegate_store_id);
  } else if (storeInfo?.store_id) {
    await executeSendPrescription(doctorSecondSignValue, 1, storeInfo.store_id);
  } else {
    await executeSendPrescription(doctorSecondSignValue, 0, null);
  }
};

// 执行发送处方
const executeSendPrescription = async (
  doctorSecondSignValue: number,
  sendMode: number,
  customStoreId: number | null,
) => {
  const result = await prescriptionStore.sendPrescription(
    doctorSecondSignValue,
    sendMode,
    customStoreId,
  );
  
  // 检查返回结果，可能是boolean或包含转诊信息的对象
  const success = typeof result === 'boolean' ? result : result?.success !== false;
  const prescriptionResult = typeof result === 'object' ? result : null;
  
  if (success) {
    // 检查是否需要转诊（西医诊所开中药处方）
    if (prescriptionResult?.need_transfer || prescriptionResult?.result?.need_transfer) {
      const transferId = prescriptionResult?.transfer_prescription_id || prescriptionResult?.result?.transfer_prescription_id;
      if (transferId) {
        // 显示转诊确认提示
        AntModal.info({
          title: '转诊提示',
          content: '该处方已触发转诊流程，转诊消息已发送给委托诊所的在线问诊医生。',
          okText: '确定',
          onOk: () => {
            if (modalData.value?.onPrescriptionSent) {
              modalData.value.onPrescriptionSent();
            }
            submittingType.value = false;
            modalApi.close();
          },
        });
        return;
      }
    }
    
    if (modalData.value?.onPrescriptionSent) {
      modalData.value.onPrescriptionSent();
    }
    submittingType.value = false;
    modalApi.close();
  }
};

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

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

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

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

const tabChange = async (id: number) => {
  prescriptionStore.changeCategory(id);
  
  // 如果切换到中药（id === 1），检测当前诊所是否为西医诊所
  if (id === 1) {
    await checkAndShowTransferTip();
  }
};

/**
 * 检测并显示转诊提示
 * @description 当切换到中药处方时，如果当前诊所为西医诊所，显示转诊提示
 */
const checkAndShowTransferTip = async () => {
  try {
    // 重新获取挂号诊所信息，确保包含最新的诊所类型和委托诊所信息
    await prescriptionStore.fetchRegisterStoreInfo();
    
    const storeInfo = prescriptionStore.registerStoreInfo;
    if (!storeInfo) {
      return;
    }
    
    // 检测是否为西医诊所（current_store_clinic_type === 1）
    if (storeInfo.current_store_clinic_type === 1 && storeInfo.delegate_store) {
      const delegateStore = storeInfo.delegate_store;
      const doctorName = delegateStore.doctor?.name || '委托医生';
      const storeName = delegateStore.name || '委托诊所';
      
      infoModalApi
        .setState({ title: '转诊提示', width: 500 })
        .setData({
          content: `检测到当前诊所为西医诊所，本次处方开具后自动转接到【${storeName}】的【${doctorName}】的在线复诊中`,
        })
        .open();
    }
  } catch (error) {
    console.error('获取诊所信息失败:', error);
  }
};

const togglePatientInfo = () => {
  isPatientInfoCollapsed.value = !isPatientInfoCollapsed.value;
};

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

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

// 打开诊断模态框
const openDiagnosisModal = () => {
  DiagnosisModalApi.setData({
    values: prescriptionStore.diagnosis,
    updateDiagnosis: (values: string) => {
      prescriptionStore.diagnosis = values;
    },
  });
  DiagnosisModalApi.open();
};

// 打开医嘱模态框
const openDoctorOrderModal = () => {
  DoctorOrderModalApi.setData({
    values: prescriptionStore.medicalAdvice,
    updateDoctorOrder: (values: string) => {
      prescriptionStore.medicalAdvice = values;
    },
  });
  DoctorOrderModalApi.open();
};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  isSavingCommonPrescription.value = true;

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

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

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

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

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

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

      <!-- 左侧：患者信息区域 (支持折叠) -->
      <div
        class="left-panel flex flex-col border-r pr-2 transition-all duration-300 ease-in-out"
        :class="isPatientInfoCollapsed ? 'w-12 items-center' : 'w-80'"
      >
        <!-- 切换按钮栏 -->
        <div class="flex w-full items-center justify-between border-b pb-2 mb-2" :class="{'flex-col gap-2 border-b-0': isPatientInfoCollapsed}">
          <h2 v-if="!isPatientInfoCollapsed" class="text-lg font-semibold whitespace-nowrap overflow-hidden">
            患者信息
            <span v-if="prescriptionStore.activePatient" class="ml-2 text-xs text-green-500">(已加载)</span>
          </h2>
          <Tooltip :title="isPatientInfoCollapsed ? '展开患者信息' : '折叠'">
            <Button type="text" size="small" @click="togglePatientInfo" class="hover:bg-gray-100 rounded">
              <RightOutlined v-if="isPatientInfoCollapsed" />
              <LeftOutlined v-else />
            </Button>
          </Tooltip>
        </div>

        <!-- 折叠状态下的垂直文字/图标 -->
        <div v-if="isPatientInfoCollapsed" class="flex flex-col items-center gap-4 mt-4 h-full cursor-pointer" @click="togglePatientInfo">
          <UserOutlined class="text-xl text-gray-500"/>
          <div class="vertical-text text-gray-500 font-medium tracking-widest text-sm">患者详情</div>
        </div>

        <!-- 展开状态下的内容 -->
        <div v-show="!isPatientInfoCollapsed" class="flex-1 overflow-y-auto pr-1">
          <!-- 调试信息 -->
          <div
            v-if="!prescriptionStore.activePatient"
            class="mb-4 rounded border border-yellow-200 bg-yellow-50 p-4 text-xs"
          >
            <p class="text-yellow-800 font-bold mb-1">调试信息：</p>
            <p>ID: {{ prescriptionStore.currentRegisterId }}</p>
            <p>状态: {{ prescriptionStore.activePatient ? '已加载' : '未加载' }}</p>
          </div>

          <!-- 患者信息 (改为单列显示以适应侧边栏) -->
          <Descriptions
            v-if="prescriptionStore.activePatient"
            :column="1"
            bordered
            size="small"
            class="mb-4"
          >
            <Descriptions.Item label="姓名">{{ prescriptionStore.activePatient.name || '未填写' }}</Descriptions.Item>
            <Descriptions.Item label="年龄">{{ prescriptionStore.activePatient.age || '未填写' }}</Descriptions.Item>
            <Descriptions.Item label="性别">
              {{
                prescriptionStore.activePatient.sex === 1
                  ? '男'
                  : prescriptionStore.activePatient.sex === 2
                    ? '女'
                    : '未填写'
              }}
            </Descriptions.Item>
          </Descriptions>

          <!-- 健康信息 -->
          <Descriptions
            v-if="prescriptionStore.userPatientHealthInquiry"
            :column="1"
            bordered
            size="small"
            class="mb-4"
            title="健康信息"
          >
            <Descriptions.Item label="肝功能">
              <span :class="{'text-red-500': prescriptionStore.userPatientHealthInquiry.liver_function === 1}">
                {{ prescriptionStore.userPatientHealthInquiry.liver_function === 0 ? '正常' : '异常' }}
              </span>
              <div v-if="prescriptionStore.userPatientHealthInquiry.liver_function === 1 && prescriptionStore.userPatientHealthInquiry.liver_index" class="mt-1 flex flex-wrap gap-1">
                <Tag v-for="item in splitString(prescriptionStore.userPatientHealthInquiry.liver_index)" :key="item" color="#455cda" class="mr-0 mb-1 text-xs">{{ item }}</Tag>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="肾功能">
              <span :class="{'text-red-500': prescriptionStore.userPatientHealthInquiry.renal_function === 1}">
                {{ prescriptionStore.userPatientHealthInquiry.renal_function === 0 ? '正常' : '异常' }}
              </span>
              <div v-if="prescriptionStore.userPatientHealthInquiry.renal_function === 1 && prescriptionStore.userPatientHealthInquiry.renal_index" class="mt-1 flex flex-wrap gap-1">
                <Tag v-for="item in splitString(prescriptionStore.userPatientHealthInquiry.renal_index)" :key="item" color="#455cda" class="mr-0 mb-1 text-xs">{{ item }}</Tag>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="既往史">
              {{ prescriptionStore.userPatientHealthInquiry.person_status === 0 ? '无' : '有' }}
              <div v-if="prescriptionStore.userPatientHealthInquiry.person_status === 1" class="mt-1 flex flex-wrap gap-1">
                <Tag v-for="item in splitString(prescriptionStore.userPatientHealthInquiry.person_history)" :key="item" color="#455cda" class="mr-0 mb-1 text-xs">{{ item }}</Tag>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="过敏史">
              {{ prescriptionStore.userPatientHealthInquiry.allergic_status === 0 ? '无' : '有' }}
              <div v-if="prescriptionStore.userPatientHealthInquiry.allergic_status === 1" class="mt-1 flex flex-wrap gap-1">
                <Tag v-for="item in splitString(prescriptionStore.userPatientHealthInquiry.allergic_history)" :key="item" color="#455cda" class="mr-0 mb-1 text-xs">{{ item }}</Tag>
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="家族史">
              {{ prescriptionStore.userPatientHealthInquiry.family_status === 0 ? '无' : '有' }}
              <div v-if="prescriptionStore.userPatientHealthInquiry.family_status === 1" class="mt-1 flex flex-wrap gap-1">
                <Tag v-for="item in splitString(prescriptionStore.userPatientHealthInquiry.family_history)" :key="item" color="#455cda" class="mr-0 mb-1 text-xs">{{ item }}</Tag>
              </div>
            </Descriptions.Item>
          </Descriptions>

          <!-- 处方记录 -->
          <div class="mb-5 mt-5">
            <div class="font-bold mb-2 text-base">历史处方</div>
            <div
              v-if="
                  prescriptionStore.prescriptionList &&
                  prescriptionStore.prescriptionList.length > 0
                "
            >
              <Timeline>
                <TimelineItem
                  v-for="item in prescriptionStore.prescriptionList"
                  :key="item.id"
                >
                  <div class="flex flex-col gap-1 text-xs">
                    <div class="flex justify-between items-center">
                      <Tag color="#455cda">{{ item.prescription_no }}</Tag>
                      <Button type="link" size="small" @click="openPrescriptionDetail(item)" class="p-0 h-auto">查看</Button>
                    </div>
                    <span class="text-gray-400">{{ item.created_at }}</span>
                    <div>
                      <Tag :color="item.category === 1 ? '' : '#455cda'" class="mr-1 scale-90 origin-left">
                        {{
                          item.prescription_type === 1
                            ? '中药'
                            : item.prescription_type === 3
                              ? '保健'
                              : item.prescription_type === 5
                                ? '服务包'
                                : item.prescription_type === 6
                                  ? '非药'
                                  : item.prescription_type === 7
                                    ? '器械'
                                    : '西药'
                        }}
                      </Tag>
                      <!-- 状态标签简化 -->
                      <Tag v-if="item.status === 0" color="warning" class="scale-90">待审</Tag>
                      <Tag v-else-if="item.status === 1" color="success" class="scale-90">通过</Tag>
                      <Tag v-else-if="item.status === 2" color="error" class="scale-90">拒</Tag>
                    </div>
                  </div>
                </TimelineItem>
              </Timeline>
            </div>
            <div v-else class="py-4 text-center text-gray-400 text-sm">
              暂无处方记录
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：处方开具区域 (占据剩余空间) -->
      <div class="right-panel flex-1 h-full overflow-y-auto px-2">
        <!-- 药品分类导航 -->
        <div class="drug-categories sticky top-0 bg-white dark:bg-[#151515] z-10 py-2 border-b mb-4">
          <button
            v-for="categoryItem in categories"
            :key="categoryItem.value"
            :class="{
              active: prescriptionStore.activeCategory === categoryItem.value,
            }"
            @click="tabChange(categoryItem.value)"
          >
            {{ categoryItem.label }}
          </button>
        </div>

        <!-- 费用类型选择和添加商品按钮 -->
        <div class="mb-4 flex items-center justify-between">
          <RadioGroup v-if="allowInsuranceCategory" v-model:value="prescriptionStore.category">
            <RadioButton :value="1">自费</RadioButton>
            <RadioButton :value="2">医保</RadioButton>
          </RadioGroup>

          <div class="flex gap-2">
            <!-- 选择常用方按钮 -->
            <Button
              type="default"
              @click="openCommonPrescriptionModal"
            >
              选择常用方
            </Button>
            <!-- 保存为常用方按钮 -->
            <Button
              type="default"
              @click="openSaveCommonPrescriptionModal"
            >
              <SaveOutlined />
              保存为常用方
            </Button>
            <Button
              v-if="prescriptionStore.activeCategory === 2"
              type="primary"
              @click="openWesternModal"
            >
              <PlusOutlined />
              添加商品
            </Button>
          </div>
        </div>

        <!-- 中药药品列表 -->
        <div
          v-if="prescriptionStore.activeCategory === 1"
          class="mb-5 mt-3 flex"
          style="flex-wrap: wrap; width: 100%"
        >
          <Row :gutter="[16, 16]" class="w-full">
            <Col
              v-for="(drug, index) in prescriptionStore.currentDrugs"
              :key="drug.id"
              :span="12"
              :xl="8"
              :xxl="6"
            >
              <Card class="prescription-card mt-0" title="">
                <div>
                  <span class="card-index">{{ index + 1 }}、</span>
                  <p>
                    <Select
                      v-model:value="drug.id"
                      :filter-option="false"
                      class="old-select-drug-name w-full mb-2"
                      placeholder="药名"
                      show-search
                      @change="prescriptionStore.selectOldDrugInfo"
                      @dropdown-visible-change="
                        prescriptionStore.setSelectChineseIndex(index, drug.id)
                      "
                      @search="searchOption"
                    >
                      <SelectOption
                        v-if="prescriptionStore.drugList.length === 0"
                        :value="drug.id"
                      >
                        {{ drug.drug_name }}
                      </SelectOption>
                      <SelectOption
                        v-for="(value, drugIndex) in prescriptionStore.drugList"
                        v-else
                        :key="drugIndex"
                        :value="value.drug.id"
                      >
                        {{ value.drug.drug_name }}
                      </SelectOption>
                    </Select>

                    <div class="flex gap-1 items-center">
                      <InputNumber
                        v-model:value="drug.number"
                        :class="`old-number-input-${index}`"
                        :controls="false"
                        style="width: 80px"
                        @blur="prescriptionStore.updateChineseNumber"
                        @keydown="
                            prescriptionStore.updateChineseNumberGoNewDrug($event)
                          "
                      >
                        <template #addonAfter> g</template>
                      </InputNumber>

                      <Select
                        :value="drug?.way_id"
                        placeholder="用法"
                        style="flex:1"
                        @change="prescriptionStore.selectDrugUseWayChange"
                        @dropdown-visible-change="
                            prescriptionStore.selectProductChange(drug.index_id)
                          "
                      >
                        <SelectOption :value="0">煎服</SelectOption>
                        <SelectOption
                          v-for="(
                              value, wayIndex
                            ) in prescriptionStore.drugUseWay"
                          :key="wayIndex"
                          :value="value.id"
                        >
                          {{ value.name }}
                        </SelectOption>
                      </Select>
                    </div>
                  </p>
                  <p class="card-price">
                    ￥<span>{{ (drug.price * drug.number).toFixed(2) }}</span>
                    <span
                      v-if="prescriptionStore.getChineseItemMargin(drug) && prescriptionStore.getChineseItemMargin(drug) !== '--'"
                      class="ml-2 text-gray-500 text-sm"
                    >
                      毛利率 {{ prescriptionStore.getChineseItemMargin(drug) }}%
                    </span>
                  </p>
                  <Button
                    class="card-delete"
                    type="link"
                    @click="prescriptionStore.removeDrug(index)"
                  >
                    <DeleteTwoTone />
                  </Button>
                </div>
              </Card>
            </Col>

            <!-- 新增药品卡片 -->
            <Col :span="12" :xl="8" :xxl="6">
              <Card class="prescription-card" title="">
                <div>
                  <span class="card-index">{{ prescriptionStore.currentDrugs.length + 1 }}、</span>
                  <div>
                    <Select
                      v-model:value="prescriptionStore.newDrugInfo.id"
                      :filter-option="false"
                      class="new-select-drug-name w-full mb-2"
                      placeholder="药名"
                      show-search
                      @change="prescriptionStore.selectNewDrugInfo"
                      @search="searchOption"
                    >
                      <SelectOption
                        v-for="(value, drugIndex) in prescriptionStore.drugList"
                        :key="drugIndex"
                        :value="value.drug_id"
                      >
                        {{ value.drug.drug_name }}
                      </SelectOption>
                    </Select>

                    <div class="flex gap-1 items-center">
                      <InputNumber
                        v-model:value="prescriptionStore.newDrugInfo.number"
                        class="new-number-input"
                        style="width: 80px"
                        @blur="newDrugBlur"
                        @keydown="
                            prescriptionStore.selectDrugByNewDrugInfo($event, true)
                          "
                      >
                        <template #addonAfter> g</template>
                      </InputNumber>

                      <Select
                        v-model:value="prescriptionStore.newDrugInfo.way_id"
                        placeholder="用法"
                        style="flex:1"
                        @keydown="
                            prescriptionStore.selectDrugByNewDrugInfo($event, true)
                          "
                      >
                        <SelectOption :value="0">煎服</SelectOption>
                        <SelectOption
                          v-for="(
                              value, wayIndex
                            ) in prescriptionStore.drugUseWay"
                          :key="wayIndex"
                          :value="value.id"
                        >
                          {{ value.name }}
                        </SelectOption>
                      </Select>
                    </div>

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

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

        <!-- 诊断和医嘱区域 -->
        <div class="diagnosis-area bg-gray-50 dark:bg-[#1f1f1f] p-4 rounded-lg">
          <!-- 中医证候 -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mb-2 flex items-center justify-between">
              <label class="font-medium">中医证候</label>
            </div>

            <Select
              v-if="prescriptionStore.traditionalChineseMedicine"
              v-model:value="prescriptionStore.diseasesSelected"
              :field-names="{
                label: 'name',
                value: 'id',
              }"
              :filter-option="filterOption"
              :options="prescriptionStore.traditionalChineseMedicine.diseases"
              class="w-full"
              placeholder="中医证候"
              show-search
            >
            </Select>
          </div>
          <!-- 中医治法 -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mb-2 flex items-center justify-between">
              <label class="font-medium">中医治法</label>
            </div>
            <Select
              v-if="prescriptionStore.traditionalChineseMedicine"
              v-model:value="prescriptionStore.methodSelected"
              :field-names="{
                label: 'name',
                value: 'id',
              }"
              :filter-option="filterOption"
              :options="prescriptionStore.traditionalChineseMedicine.method"
              class="w-full"
              placeholder="中医治法"
              show-search
            />
          </div>
          <!-- 中医疾病 -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-3">
            <div class="mb-2 flex items-center justify-between">
              <label class="font-medium">中医疾病</label>
            </div>

            <Select
              v-if="prescriptionStore.traditionalChineseMedicine"
              v-model:value="prescriptionStore.syndromeSelected"
              :field-names="{
                label: 'name',
                value: 'id',
              }"
              :filter-option="filterOption"
              :options="prescriptionStore.traditionalChineseMedicine.syndrome"
              class="w-full"
              placeholder="中医疾病"
              show-search
            />
          </div>
          <!-- 诊断输入 -->
          <div class="mb-3">
            <div class="mb-2 flex items-center justify-between">
              <label class="font-medium">常用诊断</label>
              <Button type="primary" size="small" @click="openDiagnosisModal">选择常用诊断</Button>
            </div>
            <Textarea
              v-model:value="prescriptionStore.diagnosis"
              disabled
              placeholder="输入常用诊断..."
              :rows="2"
            />
          </div>

          <!-- 医嘱输入 -->
          <div class="mb-3">
            <div class="mb-2 flex items-center justify-between">
              <label class="font-medium">医嘱</label>
              <Button type="primary" size="small" @click="openDoctorOrderModal">
                选择常用医嘱
              </Button>
            </div>
            <Textarea
              v-model:value="prescriptionStore.medicalAdvice"
              placeholder="输入医嘱..."
              :rows="2"
            />
          </div>

          <!-- 中药配置 -->
          <div v-if="prescriptionStore.activeCategory === 1" class="mb-5 border-t pt-4">
            <RadioGroup v-model:value="prescriptionStore.ruleType">
              <RadioButton :value="1">自制剂</RadioButton>
              <RadioButton :value="2">委托调剂</RadioButton>
            </RadioGroup>

            <div v-if="prescriptionStore.ruleType === 1" class="mt-3">
              <Select
                :value="prescriptionStore.packageMethodId"
                class="w-1/3"
                placeholder="请选择包法"
                @change="prescriptionStore.selectPackageMethod"
              >
                <SelectOption
                  v-for="(value, index) in packageMethod"
                  :key="index"
                  :value="value.value"
                >
                  {{ value.label }}
                </SelectOption>
              </Select>
            </div>

            <div v-else-if="prescriptionStore.ruleType === 2" class="mt-3 flex gap-2">
              <Select
                :value="prescriptionStore.processRuleId"
                class="flex-1"
                placeholder="请选择制剂"
                @change="prescriptionStore.selectProcessRule"
              >
                <SelectOption
                  v-for="(value, index) in prescriptionStore.processRuleList"
                  :key="index"
                  :value="value.id"
                >
                  {{ value.name }}
                </SelectOption>
              </Select>

              <Select
                :value="prescriptionStore.childProcessRuleId"
                class="flex-1"
                placeholder="请选择煎法"
                @change="prescriptionStore.selectProcessRuleNot"
              >
                <SelectOption
                  v-for="(value, index) in prescriptionStore.childProcessRuleList"
                  :key="index"
                  :value="value.id"
                >
                  {{ value.name }}
                </SelectOption>
              </Select>

              <Select
                :value="prescriptionStore.processRuleNoteId"
                class="flex-1"
                placeholder="请选择备注"
                @change="prescriptionStore.selectProcessRuleNotCommit"
              >
                <SelectOption
                  v-for="(value, index) in prescriptionStore.processRuleNoteList"
                  :key="index"
                  :value="value.id"
                >
                  {{ value.note }}
                </SelectOption>
              </Select>
            </div>

            <div class="mt-5 flex gap-4 items-center flex-wrap">
              <div class="flex items-center gap-2">
                <span class="mr-2 whitespace-nowrap">用量：</span>
                <div class="flex items-center border rounded" style="border-color: #d9d9d9;">
                  <Button
                    type="text"
                    size="small"
                    class="border-0 border-r rounded-l"
                    style="border-color: #d9d9d9;"
                    @click="
                      prescriptionStore.dosage =
                        prescriptionStore.dosage > 1
                          ? prescriptionStore.dosage - 1
                          : 1
                    "
                  >
                    <MinusOutlined />
                  </Button>
                  <InputNumber
                    v-model:value="prescriptionStore.dosage"
                    :controls="false"
                    :min="1"
                    :max="100"
                    class="border-0"
                    style="width: 80px; text-align: center;"
                  />
                  <Button
                    type="text"
                    size="small"
                    class="border-0 border-l rounded-r"
                    style="border-color: #d9d9d9;"
                    @click="
                      prescriptionStore.dosage =
                        prescriptionStore.dosage < 100
                          ? prescriptionStore.dosage + 1
                          : 100
                    "
                  >
                    <PlusOutlined />
                  </Button>
                </div>
                <span class="ml-2 whitespace-nowrap">天 / {{ prescriptionStore.dosage }} 剂</span>
              </div>

              <div class="flex items-center gap-2">
                <span class="mr-2 whitespace-nowrap">频次：</span>
                <div class="flex items-center border rounded" style="border-color: #d9d9d9;">
                  <Button
                    type="text"
                    size="small"
                    class="border-0 border-r rounded-l"
                    style="border-color: #d9d9d9;"
                    @click="
                      prescriptionStore.dayDosage =
                        prescriptionStore.dayDosage > 1
                          ? prescriptionStore.dayDosage - 1
                          : 1
                    "
                  >
                    <MinusOutlined />
                  </Button>
                  <InputNumber
                    v-model:value="prescriptionStore.dayDosage"
                    :controls="false"
                    :min="1"
                    :max="100"
                    class="border-0"
                    style="width: 80px; text-align: center;"
                  />
                  <Button
                    type="text"
                    size="small"
                    class="border-0 border-l rounded-r"
                    style="border-color: #d9d9d9;"
                    @click="
                      prescriptionStore.dayDosage =
                        prescriptionStore.dayDosage < 100
                          ? prescriptionStore.dayDosage + 1
                          : 100
                    "
                  >
                    <PlusOutlined />
                  </Button>
                </div>
                <span class="ml-2 whitespace-nowrap">次/天</span>
              </div>
            </div>
          </div>

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

        </div>

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

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

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

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

    <!-- 子模态框组件 - 按照VbenAdmin的方式声明 -->
    <WesternDrugModal />
    <SimpleProductModalComponent />
    <InfoModalComponent />
    <DiagnosisModals />
    <DoctorOrderModals />
    <PrescriptionDetailModal />
    <!-- 常用方选择弹窗 -->
    <CommonPrescriptionModals />
  </Modal>
</template>

<style scoped>
/* 保持原有样式，新增一些布局微调 */
.doctor-second-sign-title {
  font-size: 16px;
  margin: 10px 0;
  font-weight: bold;
  border-left: 5px solid rgb(55, 71, 162);
  padding-left: 10px;
}

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

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

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

.prescription-card {
  position: relative;
  min-height: 120px;
}

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

.drug-categories button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 10px;
  cursor: pointer;
  background: transparent;
  color: inherit;
  transition: all 0.3s;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  .right-panel {
    overflow: visible;
  }

  .drug-categories {
    flex-wrap: wrap;
    position: static; /* 移动端取消固定 */
  }

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

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