<script lang="ts" setup>
/**
 * 常用方编辑弹窗组件
 *
 * @description 用于编辑已保存的常用方，支持修改基本信息和药品列表
 *              - 支持西药、中药、颗粒药三种类型
 *              - 西药：使用搜索框添加药品
 *              - 中药/颗粒药：卡片式布局，直接在卡片内搜索修改
 *              - 支持通过弹窗选择诊断和医嘱
 *              - 自动填充药品默认用法
 * @author 系统
 * @date 2024
 */
import { ref, computed, nextTick } from 'vue';

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

import {
  DeleteOutlined,
  DeleteTwoTone,
  EditOutlined,
  MinusOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Row,
  Select,
  SelectOption,
  Spin,
  Tag,
} from 'ant-design-vue';
import { debounce } from 'lodash-es';

import { DrugSearchSelect } from '#/components/drug-search-select';
import {
  updateWestCommonPrescriptionApi,
  updateChineseCommonPrescriptionApi,
  updateGranularCommonPrescriptionApi,
} from '#/views/doctor/settings/api';
import {
  getDrugUseList,
  getProductListDoctorReception,
  getProcessRuleList,
} 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';

// ==================== 诊断和医嘱弹窗 ====================

/**
 * 诊断选择弹窗
 */
const [DiagnosisModalRender, diagnosisModalApi] = useVbenModal({
  connectedComponent: DiagnosisModal,
});

/**
 * 医嘱选择弹窗
 */
const [DoctorOrderModalRender, doctorOrderModalApi] = useVbenModal({
  connectedComponent: DoctorOrderModal,
});

// ==================== 响应式数据 ====================

const userStore = useUserStore();

/**
 * 表单数据
 */
const formData = ref({
  id: 0,
  name: '',
  clinical_diagnose: '',
  doctor_order: '',
});

/**
 * 常用方类型
 * west-西药，chinese-中药，granular-颗粒药
 */
const prescriptionType = ref<'west' | 'chinese' | 'granular'>('west');

/**
 * 药品列表（可编辑）
 */
const drugList = ref<any[]>([]);

/**
 * 是否正在保存
 */
const isSaving = ref(false);

/**
 * 药品使用方式数据
 */
const drugUseData = ref<{
  drug_use_num: any[];
  drug_use_frequency: any[];
  drug_use_type: any[];
  drug_unit: any[];
  drug_time: any[];
  drug_use_way: any[];
}>({
  drug_use_num: [],
  drug_use_frequency: [],
  drug_use_type: [],
  drug_unit: [],
  drug_time: [],
  drug_use_way: [],
});

/**
 * 中药剂量/天数
 */
const dosage = ref(7);

/**
 * 中药每日次数
 */
const dayDosage = ref(2);

/**
 * 规则类型：1=自制剂，2=委托调剂
 */
const ruleType = ref(1);

/**
 * 包装方式ID（自制剂时使用）
 */
const packageMethodId = ref(2);

/**
 * 加工规则ID（委托调剂时使用）
 */
const processRuleId = ref<number | null>(null);

/**
 * 子加工规则ID（委托调剂时使用）
 */
const childProcessRuleId = ref<number | null>(null);

/**
 * 加工规则备注ID（委托调剂时使用）
 */
const processRuleNoteId = ref<number | null>(null);

/**
 * 委托调剂选项列表
 */
const processRuleList = ref<any[]>([]);
const childProcessRuleList = ref<any[]>([]);
const processRuleNoteList = ref<any[]>([]);

/**
 * 保存成功后的回调函数
 */
let onSaveCallback: (() => void) | null = null;

/**
 * 中药搜索结果列表
 */
const chineseSearchResults = ref<any[]>([]);

/**
 * 新药品输入数据
 */
const newDrugInfo = ref<{
  id?: number;
  name?: string;
  number?: number;
  price?: number;
  way_id?: number;
}>({});

// ==================== 计算属性 ====================

/**
 * 获取类型标签颜色
 */
const typeTagColor = computed(() => {
  switch (prescriptionType.value) {
    case 'west':
      return 'blue';
    case 'chinese':
      return 'green';
    case 'granular':
      return 'orange';
    default:
      return 'default';
  }
});

/**
 * 获取类型名称
 */
const typeName = computed(() => {
  switch (prescriptionType.value) {
    case 'west':
      return '西药';
    case 'chinese':
      return '中药';
    case 'granular':
      return '颗粒药';
    default:
      return '';
  }
});

/**
 * 是否为中药/颗粒药类型
 */
const isChineseType = computed(() => {
  return prescriptionType.value === 'chinese' || prescriptionType.value === 'granular';
});

// ==================== Modal 配置 ====================

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  title: '编辑常用方',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    await handleSave();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 获取传入的参数
      const data = modalApi.getData<{
        prescription: any;
        recipes: any[];
        type: 'west' | 'chinese' | 'granular';
        onSave?: () => void;
      }>();

      if (data) {
        // 初始化表单数据
        formData.value = {
          id: data.prescription.id,
          name: data.prescription.name || '',
          clinical_diagnose: data.prescription.clinical_diagnose || '',
          doctor_order: data.prescription.doctor_order || '',
        };
        prescriptionType.value = data.type;

        // 初始化药品列表
        drugList.value = (data.recipes || []).map((item, index) => ({
          ...item,
          _key: Date.now() + index, // 添加唯一标识
        }));

        // 初始化规则类型相关数据（中药）
        if (data.type === 'chinese') {
          dosage.value = data.prescription.dosage || 7;
          dayDosage.value = data.prescription.day_dosage || 2;
          ruleType.value = data.prescription.rule_type || 1;
          packageMethodId.value = data.prescription.package_method_id || 2;
          processRuleId.value = data.prescription.process_rule_id || null;
          childProcessRuleId.value = data.prescription.child_process_rule_id || null;
          processRuleNoteId.value = data.prescription.process_rule_note_id || null;
        }

        onSaveCallback = data.onSave || null;

        // 加载药品使用方式数据
        loadDrugUseData();
        // 加载委托调剂选项（第一级：制剂）
        await loadProcessRuleData(0, 0);
        
        // 如果有已保存的委托调剂配置，需要级联加载（顺序执行）
        if (processRuleId.value) {
          await loadProcessRuleData(processRuleId.value, 0);
        }
        if (childProcessRuleId.value) {
          await loadProcessRuleData(0, childProcessRuleId.value);
        }
      }
    }
  },
});

// ==================== 方法定义 ====================

/**
 * 加载药品使用方式数据
 */
async function loadDrugUseData() {
  try {
    const res = await getDrugUseList();
    drugUseData.value = {
      drug_use_num: res.drug_use_num || [],
      drug_use_frequency: res.drug_use_frequency || [],
      drug_use_type: res.drug_use_type || [],
      drug_unit: res.drug_unit || [],
      drug_time: res.drug_time || [],
      drug_use_way: res.drug_use_way || [],
    };
  } catch (error) {
    console.error('加载药品使用方式数据失败:', error);
  }
}

/**
 * 加载委托调剂选项数据
 */
async function loadProcessRuleData(pid = 0, ruleId = 0) {
  try {
    const data = ruleId === 0 ? { pid } : { rule_id: ruleId };
    const res = await getProcessRuleList(data);
    if (ruleId !== 0) {
      processRuleNoteList.value = res;
    } else if (pid === 0) {
      processRuleList.value = res;
    } else {
      childProcessRuleList.value = res;
    }
  } catch (error) {
    console.error('加载委托调剂选项失败:', error);
  }
}

/**
 * 制剂选择变化
 */
function handleProcessRuleChange(id: number) {
  childProcessRuleId.value = null;
  processRuleNoteId.value = null;
  childProcessRuleList.value = [];
  processRuleNoteList.value = [];
  if (id) {
    loadProcessRuleData(id, 0);
  }
}

/**
 * 煎法选择变化
 */
function handleChildProcessRuleChange(id: number) {
  processRuleNoteId.value = null;
  processRuleNoteList.value = [];
  if (id) {
    loadProcessRuleData(0, id);
  }
}

/**
 * 打开诊断选择弹窗
 */
function openDiagnosisModal() {
  diagnosisModalApi.setData({
    values: formData.value.clinical_diagnose,
    updateDiagnosis: (value: string) => {
      formData.value.clinical_diagnose = value;
    },
  });
  diagnosisModalApi.open();
}

/**
 * 搜索中药（防抖）
 * @param keyword 搜索关键词
 */
const searchChineseDrugs = debounce(async (keyword: string) => {
  if (!keyword || keyword.length < 1) {
    chineseSearchResults.value = [];
    return;
  }

  try {
    const res = await getProductListDoctorReception({
      name: keyword,
      type: 1, // 中药类型
      store_id: userStore.userInfo?.store_id || 2,
    });

    if (Array.isArray(res)) {
      chineseSearchResults.value = res;
    } else {
      chineseSearchResults.value = [];
    }
  } catch (error) {
    console.error('搜索中药失败:', error);
    chineseSearchResults.value = [];
  }
}, 300);

/**
 * 选择新药品
 * @param drugId 药品ID
 */
function selectNewDrug(drugId: number) {
  // 检查是否已存在
  const exists = drugList.value.some(
    (item) => item.id === drugId || item.drug_id === drugId,
  );

  if (exists) {
    message.warning('该药品已在列表中');
    newDrugInfo.value.id = undefined;
    return;
  }

  // 找到选中的药品信息
  const selectedItem = chineseSearchResults.value.find(
    (item) => item.drug?.id === drugId || item.drug_id === drugId,
  );

  if (selectedItem) {
    newDrugInfo.value.name = selectedItem.drug?.drug_name || '';
    newDrugInfo.value.price = selectedItem.price || 0;
    newDrugInfo.value.way_id = 0;

    // 聚焦到克数输入框
    nextTick(() => {
      const numberInput = document.querySelector('.edit-new-chinese-number input') as HTMLInputElement;
      if (numberInput) {
        numberInput.focus();
      }
    });
  }
}

/**
 * 添加中药到列表
 */
function addChineseDrug() {
  if (!newDrugInfo.value.id) {
    message.warning('请先选择药品');
    return;
  }

  if (!newDrugInfo.value.number || newDrugInfo.value.number <= 0) {
    message.warning('请输入正确的克数');
    return;
  }

  // 检查是否已存在
  const exists = drugList.value.some(
    (item) => item.id === newDrugInfo.value.id || item.drug_id === newDrugInfo.value.id,
  );

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

  // 添加到列表
  drugList.value.push({
    _key: Date.now(),
    id: newDrugInfo.value.id,
    drug_id: newDrugInfo.value.id,
    drug_name: newDrugInfo.value.name,
    number: newDrugInfo.value.number,
    price: newDrugInfo.value.price || 0,
    way_id: newDrugInfo.value.way_id || 0,
  });

  // 清空并准备下一次输入
  newDrugInfo.value = {};
  chineseSearchResults.value = [];

  message.success('已添加药品');

  // 聚焦到新药品输入框
  nextTick(() => {
    const nameInput = document.querySelector('.edit-new-chinese-name input') as HTMLInputElement;
    if (nameInput) {
      nameInput.focus();
    }
  });
}

/**
 * 修改已有中药（切换药品）
 * @param index 药品索引
 * @param drugId 新药品ID
 */
function changeChineseDrug(index: number, drugId: number) {
  // 检查是否已存在（排除当前正在修改的）
  const exists = drugList.value.some(
    (item, i) => i !== index && (item.id === drugId || item.drug_id === drugId),
  );

  if (exists) {
    message.warning('该药品已在列表中');
    // 恢复原来的值
    const drug = drugList.value[index];
    if (drug) {
      drug.id = drug.drug_id;
    }
    return;
  }

  // 找到选中的药品信息
  const selectedItem = chineseSearchResults.value.find(
    (item) => item.drug?.id === drugId || item.drug_id === drugId,
  );

  if (selectedItem) {
    const drug = drugList.value[index];
    if (drug) {
      drug.id = drugId;
      drug.drug_id = drugId;
      drug.drug_name = selectedItem.drug?.drug_name || '';
      drug.price = selectedItem.price || 0;
    }

    // 聚焦到克数输入框
    nextTick(() => {
      const numberInput = document.querySelector(`.edit-chinese-number-${index} input`) as HTMLInputElement;
      if (numberInput) {
        numberInput.focus();
      }
    });
  }
}

/**
 * 处理回车键
 * @param event 键盘事件
 * @param isNew 是否是新药品输入框
 */
function handleChineseKeydown(event: KeyboardEvent, isNew: boolean) {
  if (event.key === 'Enter') {
    event.preventDefault();
    if (isNew) {
      addChineseDrug();
    }
  }
}

/**
 * 打开医嘱选择弹窗
 */
function openDoctorOrderModal() {
  doctorOrderModalApi.setData({
    values: formData.value.doctor_order,
    updateDoctorOrder: (value: string) => {
      formData.value.doctor_order = value;
    },
  });
  doctorOrderModalApi.open();
}

/**
 * 添加药品（从DrugSearchSelect组件回调）
 * @param drug 药品信息（包含完整数据和默认用法）
 * @description 自动填充药品的默认用法数据
 */
function handleDrugSelect(drug: any) {
  const drugId = drug._drugId || drug.drug_id || drug.id;
  const drugName = drug._drugName || drug.drug?.drug_name || drug.drug_name || '';
  const drugPrice = drug._price || drug.price || 0;
  const drugImage = drug._image || drug.drug?.image || '';

  // 检查是否已存在
  const exists = drugList.value.some(
    (item) => (item.drug_id || item.id) === drugId,
  );

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

  // 根据类型构建药品数据，自动填充默认用法
  if (prescriptionType.value === 'west') {
    drugList.value.push({
      _key: Date.now(),
      drug_id: drugId,
      id: drugId,
      drug_name: drugName,
      // 自动填充默认用量
      number: drug._number || drug.drug?.number || 1,
      select_number: 1,
      price: drugPrice,
      image: drugImage,
      // 自动填充默认用法ID
      time_id: drug._timeId || drug.drug?.time_id || 0,
      type_id: drug._typeId || drug.drug?.type_id || 0,
      frequency_id: drug._frequencyId || drug.drug?.frequency_id || 0,
      unit_id: drug._unitId || drug.drug?.unit_id || 0,
      // 自动填充用法名称对象
      use_num: drug._useNum || drug.drug?.useNum || null,
      use_type: drug._useType || drug.drug?.useType || null,
      use_frequency: drug._useFrequency || drug.drug?.useFrequency || null,
      unit: null,
    });
  } else {
    drugList.value.push({
      _key: Date.now(),
      drug_id: drugId,
      id: drugId,
      drug_name: drugName,
      number: 10,
      price: drugPrice,
      way_id: 0,
    });
  }

  message.success('已添加药品');
}

/**
 * 删除药品
 * @param index 药品索引
 */
function removeDrug(index: number) {
  drugList.value.splice(index, 1);
}

/**
 * 更新西药用量
 * @param index 药品索引
 * @param delta 增减值
 */
function updateWestQuantity(index: number, delta: number) {
  const drug = drugList.value[index];
  if (drug) {
    const newValue = (drug.select_number || 1) + delta;
    if (newValue >= 1) {
      drug.select_number = newValue;
    }
  }
}

/**
 * 保存常用方
 */
async function handleSave() {
  // 验证名称
  if (!formData.value.name.trim()) {
    message.warning('请输入常用方名称');
    return;
  }

  // 验证药品
  if (drugList.value.length === 0) {
    message.warning('请至少添加一种药品');
    return;
  }

  isSaving.value = true;

  try {
    // 根据类型调用不同的更新接口
    switch (prescriptionType.value) {
      case 'west': {
        // 构建西药药品数据
        const drugs = drugList.value.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 updateWestCommonPrescriptionApi({
          id: formData.value.id,
          name: formData.value.name.trim(),
          clinical_diagnose: formData.value.clinical_diagnose,
          doctor_order: formData.value.doctor_order,
          drugs,
        });
        break;
      }
      case 'chinese': {
        // 构建中药药品数据
        const drugs = drugList.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 updateChineseCommonPrescriptionApi({
          id: formData.value.id,
          name: formData.value.name.trim(),
          clinical_diagnose: formData.value.clinical_diagnose,
          doctor_order: formData.value.doctor_order,
          drugs,
          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,
        });
        break;
      }
      case 'granular': {
        // 构建颗粒药药品数据
        const drugs = drugList.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 updateGranularCommonPrescriptionApi({
          id: formData.value.id,
          name: formData.value.name.trim(),
          clinical_diagnose: formData.value.clinical_diagnose,
          doctor_order: formData.value.doctor_order,
          drugs,
          dosage: dosage.value,
          day_dosage: dayDosage.value,
        });
        break;
      }
    }

    message.success('保存成功');

    // 调用回调刷新列表
    if (onSaveCallback) {
      onSaveCallback();
    }

    modalApi.close();
  } catch (error) {
    console.error('保存常用方失败:', error);
    message.error('保存失败，请稍后重试');
  } finally {
    isSaving.value = false;
  }
}
</script>

<template>
  <Modal class="w-[900px]">
    <Spin :spinning="isSaving">
      <div class="p-4">
        <!-- 类型标签 -->
        <div class="mb-4">
          <Tag :color="typeTagColor">{{ typeName }}常用方</Tag>
        </div>

        <!-- 编辑表单 -->
        <Form layout="vertical">
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="常用方名称" required>
                <Input
                  v-model:value="formData.name"
                  placeholder="请输入常用方名称"
                  :maxlength="50"
                  allow-clear
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="临床诊断">
                <Input
                  v-model:value="formData.clinical_diagnose"
                  placeholder="点击选择诊断"
                  :maxlength="200"
                  readonly
                  @click="openDiagnosisModal"
                >
                  <template #suffix>
                    <EditOutlined class="cursor-pointer text-gray-400 hover:text-primary" />
                  </template>
                </Input>
              </FormItem>
            </Col>
          </Row>

          <FormItem label="医嘱">
            <Input
              v-model:value="formData.doctor_order"
              placeholder="点击选择医嘱"
              :maxlength="500"
              readonly
              @click="openDoctorOrderModal"
            >
              <template #suffix>
                <EditOutlined class="cursor-pointer text-gray-400 hover:text-primary" />
              </template>
            </Input>
          </FormItem>

          <!-- 中药/颗粒药剂量设置 -->
          <Row v-if="isChineseType" :gutter="16" class="mb-4">
            <Col :span="12">
              <FormItem label="剂量（天/剂）">
                <InputNumber
                  v-model:value="dosage"
                  :min="1"
                  :max="100"
                  style="width: 100%"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="频次（次/天）">
                <InputNumber
                  v-model:value="dayDosage"
                  :min="1"
                  :max="10"
                  style="width: 100%"
                />
              </FormItem>
            </Col>
          </Row>

          <!-- 中药规则类型选择 -->
          <Row v-if="prescriptionType === 'chinese'" :gutter="16" class="mb-4">
            <Col :span="24">
              <FormItem label="调配方式">
                <RadioGroup v-model:value="ruleType" button-style="solid">
                  <RadioButton :value="1">自制剂</RadioButton>
                  <RadioButton :value="2">委托调剂</RadioButton>
                </RadioGroup>
              </FormItem>
            </Col>
          </Row>

          <!-- 自制剂包法选择 -->
          <Row v-if="prescriptionType === 'chinese' && ruleType === 1" :gutter="16" class="mb-4">
            <Col :span="12">
              <FormItem label="包法">
                <Select v-model:value="packageMethodId" style="width: 100%">
                  <SelectOption :value="1">袋包</SelectOption>
                  <SelectOption :value="2">剂包</SelectOption>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <!-- 委托调剂选择 -->
          <Row v-if="prescriptionType === 'chinese' && ruleType === 2" :gutter="16" class="mb-4">
            <Col :span="8">
              <FormItem label="制剂">
                <Select
                  v-model:value="processRuleId"
                  placeholder="请选择制剂"
                  style="width: 100%"
                  @change="handleProcessRuleChange"
                >
                  <SelectOption
                    v-for="item in processRuleList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="煎法">
                <Select
                  v-model:value="childProcessRuleId"
                  placeholder="请选择煎法"
                  style="width: 100%"
                  @change="handleChildProcessRuleChange"
                >
                  <SelectOption
                    v-for="item in childProcessRuleList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </SelectOption>
                </Select>
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="备注">
                <Select
                  v-model:value="processRuleNoteId"
                  placeholder="请选择备注"
                  style="width: 100%"
                >
                  <SelectOption
                    v-for="item in processRuleNoteList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.note }}
                  </SelectOption>
                </Select>
              </FormItem>
            </Col>
          </Row>

          <!-- 西药搜索 -->
          <FormItem v-if="prescriptionType === 'west'" label="添加药品">
            <DrugSearchSelect
              :type="2"
              :placeholder="`输入${typeName}名称搜索（显示图片、供应商、规格、价格）`"
              @select="handleDrugSelect"
            />
          </FormItem>

          <!-- 西药列表 -->
          <FormItem v-if="prescriptionType === 'west'" label="药品列表">
            <div v-if="drugList.length === 0" class="text-center py-8 text-gray-400">
              暂无药品，请搜索添加
            </div>

            <div v-else class="space-y-3">
              <Card
                v-for="(drug, index) in drugList"
                :key="drug._key"
                size="small"
                class="drug-card"
              >
                <div class="flex items-center gap-4">
                  <!-- 药品图片 -->
                  <div class="w-16 h-16 flex-shrink-0">
                    <Image
                      v-if="drug.image"
                      :src="drug.image"
                      :width="64"
                      :height="64"
                      class="rounded"
                    />
                    <div
                      v-else
                      class="w-16 h-16 bg-gray-100 rounded flex items-center justify-center text-gray-400"
                    >
                      无图
                    </div>
                  </div>

                  <!-- 药品信息 -->
                  <div class="flex-1">
                    <div class="font-medium mb-1">{{ drug.drug_name }}</div>
                    <div class="text-sm text-gray-500">
                      单价: ¥{{ drug.price }}
                    </div>
                  </div>

                  <!-- 用法选择 -->
                  <div class="flex gap-2">
                    <Select
                      v-model:value="drug.type_id"
                      placeholder="用法"
                      style="width: 100px"
                      size="small"
                      @change="(val) => drug.use_type = drugUseData.drug_use_type.find(i => i.id === val)"
                    >
                      <SelectOption
                        v-for="item in drugUseData.drug_use_type"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                    <Select
                      v-model:value="drug.frequency_id"
                      placeholder="频率"
                      style="width: 100px"
                      size="small"
                      @change="(val) => drug.use_frequency = drugUseData.drug_use_frequency.find(i => i.id === val)"
                    >
                      <SelectOption
                        v-for="item in drugUseData.drug_use_frequency"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                  </div>

                  <!-- 每次用量 -->
                  <div class="flex items-center gap-1">
                    <span class="text-sm text-gray-500">每次</span>
                    <InputNumber
                      v-model:value="drug.number"
                      :min="1"
                      size="small"
                      style="width: 60px"
                    />
                    <Select
                      v-model:value="drug.unit_id"
                      placeholder="单位"
                      style="width: 70px"
                      size="small"
                      @change="(val) => drug.unit = drugUseData.drug_unit.find(i => i.id === val)"
                    >
                      <SelectOption
                        v-for="item in drugUseData.drug_unit"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </SelectOption>
                    </Select>
                  </div>

                  <!-- 数量控制 -->
                  <div class="flex items-center gap-2">
                    <Button
                      size="small"
                      @click="updateWestQuantity(index, -1)"
                    >
                      <MinusOutlined />
                    </Button>
                    <span class="w-8 text-center">{{ drug.select_number || 1 }}</span>
                    <Button
                      size="small"
                      @click="updateWestQuantity(index, 1)"
                    >
                      <PlusOutlined />
                    </Button>
                  </div>

                  <!-- 删除按钮 -->
                  <Button
                    type="text"
                    danger
                    size="small"
                    @click="removeDrug(index)"
                  >
                    <DeleteOutlined />
                  </Button>
                </div>
              </Card>
            </div>
          </FormItem>

          <!-- 中药/颗粒药卡片式布局 -->
          <FormItem v-if="isChineseType" label="药品列表">
            <Row :gutter="[12, 12]">
              <!-- 已添加的药品卡片 -->
              <Col
                v-for="(drug, index) in drugList"
                :key="drug._key"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="8"
              >
                <Card size="small" class="chinese-drug-card">
                  <div class="chinese-drug-content">
                    <span class="chinese-drug-index">{{ index + 1 }}、</span>
                    <div class="chinese-drug-form">
                      <Select
                        v-model:value="drug.id"
                        show-search
                        :filter-option="false"
                        placeholder="药名"
                        class="chinese-drug-name"
                        @search="searchChineseDrugs"
                        @change="(val) => changeChineseDrug(index, val)"
                      >
                        <SelectOption
                          v-if="chineseSearchResults.length === 0"
                          :value="drug.id"
                        >
                          {{ drug.drug_name }}
                        </SelectOption>
                        <SelectOption
                          v-for="item in chineseSearchResults"
                          v-else
                          :key="item.drug?.id || item.id"
                          :value="item.drug?.id || item.id"
                        >
                          {{ item.drug?.drug_name || item.drug_name }}
                        </SelectOption>
                      </Select>
                      <span class="chinese-drug-comma">，</span>
                      <InputNumber
                        v-model:value="drug.number"
                        :class="`edit-chinese-number-${index}`"
                        :controls="false"
                        :min="1"
                        style="width: 60px"
                      />
                      <span class="chinese-drug-unit">g</span>
                      <span class="chinese-drug-comma">，</span>
                      <Select
                        v-model:value="drug.way_id"
                        placeholder="用法"
                        style="width: 70px"
                      >
                        <SelectOption :value="0">煎服</SelectOption>
                        <SelectOption
                          v-for="item in drugUseData.drug_use_way"
                          :key="item.id"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </SelectOption>
                      </Select>
                    </div>
                    <div class="chinese-drug-price">
                      ￥{{ ((drug.price || 0) * (drug.number || 1)).toFixed(2) }}
                    </div>
                    <Button
                      type="link"
                      class="chinese-drug-delete"
                      @click="removeDrug(index)"
                    >
                      <DeleteTwoTone two-tone-color="#ff4d4f" />
                    </Button>
                  </div>
                </Card>
              </Col>

              <!-- 新药品添加卡片 -->
              <Col :xs="24" :sm="12" :md="8" :lg="8">
                <Card size="small" class="chinese-drug-card chinese-drug-card-new">
                  <div class="chinese-drug-content">
                    <span class="chinese-drug-index">{{ drugList.length + 1 }}、</span>
                    <div class="chinese-drug-form">
                      <Select
                        v-model:value="newDrugInfo.id"
                        show-search
                        :filter-option="false"
                        placeholder="药名"
                        class="chinese-drug-name edit-new-chinese-name"
                        @search="searchChineseDrugs"
                        @change="selectNewDrug"
                      >
                        <SelectOption
                          v-for="item in chineseSearchResults"
                          :key="item.drug?.id || item.id"
                          :value="item.drug?.id || item.id"
                        >
                          {{ item.drug?.drug_name || item.drug_name }}
                        </SelectOption>
                      </Select>
                      <span class="chinese-drug-comma">，</span>
                      <InputNumber
                        v-model:value="newDrugInfo.number"
                        class="edit-new-chinese-number"
                        :controls="false"
                        :min="1"
                        style="width: 60px"
                        @keydown="(e) => handleChineseKeydown(e, true)"
                      />
                      <span class="chinese-drug-unit">g</span>
                      <span class="chinese-drug-comma">，</span>
                      <Select
                        v-model:value="newDrugInfo.way_id"
                        placeholder="用法"
                        style="width: 70px"
                        @keydown="(e) => handleChineseKeydown(e, true)"
                      >
                        <SelectOption :value="0">煎服</SelectOption>
                        <SelectOption
                          v-for="item in drugUseData.drug_use_way"
                          :key="item.id"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </SelectOption>
                      </Select>
                    </div>
                    <div class="chinese-drug-price">
                      ￥{{ ((newDrugInfo.price || 0) * (newDrugInfo.number || 1)).toFixed(2) }}
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </FormItem>
        </Form>
      </div>
    </Spin>

    <!-- 诊断选择弹窗 -->
    <DiagnosisModalRender />

    <!-- 医嘱选择弹窗 -->
    <DoctorOrderModalRender />
  </Modal>
</template>

<style lang="scss" scoped>
:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

.drug-card {
  transition: all 0.2s;
}

/* 中药卡片样式 */
.chinese-drug-card {
  position: relative;
  min-height: 80px;

  :deep(.ant-card-body) {
    padding: 12px;
  }
}

.chinese-drug-card-new {
  border-style: dashed;
}

.chinese-drug-content {
  position: relative;
}

.chinese-drug-index {
  position: absolute;
  left: 0;
  top: 0;
  font-size: 16px;
  font-weight: bold;
  @apply text-primary;
}

.chinese-drug-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  padding-left: 28px;
}

.chinese-drug-name {
  min-width: 80px;
  max-width: 120px;
}

.chinese-drug-comma {
  @apply text-muted-foreground;
}

.chinese-drug-unit {
  @apply text-muted-foreground text-xs;
}

.chinese-drug-price {
  position: absolute;
  right: 24px;
  bottom: 0;
  @apply text-destructive font-medium;
}

.chinese-drug-delete {
  position: absolute;
  right: -8px;
  top: -8px;
  padding: 4px;
}
</style>
