<template>
  <u-popup
      v-model="show"
      mode="bottom"
      :closeable="true"
      @close="handleClose"
      :safe-area-inset-bottom="true"
      :mask-close-able="true"
      z-index="10078"
      height="80%"
  >
    <view class="chinese-medicine-modal page-bg">
      <view class="modal-header white">
        <d-text text="选择中药" className="fs-32 font-bold color-title"></d-text>
      </view>

      <view class="modal-content">
        <!-- 搜索框 -->
        <view class="search-box m-b-24">
          <u-search
              v-model="searchKey"
              placeholder="请输入药品名称搜索"
              @input="handleSearch"
              @custom="searchKey = ''; handleSearch()"
              :show-action="false"
              bg-color="#fff"
          />
        </view>

        <!-- 已选药材（横向滑动） -->
        <view v-if="selectedDrugs.length > 0" class="selected-strip-wrap m-b-24">
          <scroll-view class="selected-strip-scroll" scroll-x enable-flex>
            <view class="selected-strip-inner flex-row">
              <view
                  v-for="sel in selectedDrugs"
                  :key="sel._wxKey"
                  class="selected-chip flex-row flex-ali-center"
              >
                <view
                    class="selected-chip-main flex-row flex-ali-center"
                    :data-wx-key="sel._wxKey"
                    @click="handleSelectedChipSearch"
                >
                  <text class="selected-chip-name">{{ sel.drug_name || sel.name || '—' }}</text>
                  <text class="selected-chip-dose">{{ String(sel.number || 0) }}{{ sel.unit && sel.unit.name ? sel.unit.name : 'g' }}</text>
                  <text v-if="getWayLabel(sel)" class="selected-chip-way">{{ getWayLabel(sel) }}</text>
                </view>
                <view class="selected-chip-close" :data-wx-key="sel._wxKey" @click.stop="handleSelectedChipRemove">
                  <u-icon name="close" size="22" color="#8A92A3"></u-icon>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 药品列表（可滚动，支持触底加载） -->
        <scroll-view
            class="drug-list-scroll"
            scroll-y
            @scrolltolower="loadMore"
            :lower-threshold="100"
        >
          <view class="drug-list" v-if="drugList.length > 0">
            <view
                class="medicine-card"
                v-for="(item, index) in drugList"
                :key="index"
                :class="{ 'is-selected': isInSelected(item) }"
            >
              <view class="drug-header flex-row flex-jus-sp flex-ali-center m-b-16">
                <view class="flex-row flex-ali-center">
                  <view class="selected-indicator" v-if="isInSelected(item)"></view>
                  <d-text :text="getDrugName(item)" className="fs-32 font-bold color-title"></d-text>
                  <text v-if="Number(item.has_delivery_warehouse) === 1" class="multi-wh-tag m-l-12">多仓</text>
                </view>
                <d-text
                    v-if="showDrugPrice"
                    :text="`￥${parseFloat(item.price || 0).toFixed(2)}/${getUnitName(item)}`"
                    className="fs-32 font-bold color-price"
                ></d-text>
                <d-text v-else text="价格不可见" className="fs-26 color-sub"></d-text>
              </view>
              <view class="drug-info">
                <view class="specification-row flex-row flex-jus-sp flex-ali-center m-b-24">
                  <d-text :text="`规格：${getSpecification(item)}`" className="fs-26 color-sub"></d-text>
                  <view class="usage-capsule" v-if="isInSelected(item)">已加处方</view>
                </view>

                <!-- 常用用量快捷标签 -->
                <view class="common-quantity-tags m-b-24" v-if="commonQuantities.length > 0">
                  <view
                      class="modern-tag"
                      v-for="(qty, qix) in commonQuantities"
                      :key="qix"
                      @click.stop="handleSelectCommonQuantity"
                      :data-index="index"
                      :data-quantity="qty"
                  >
                    快捷 {{ qty }}{{ getUnitName(item) }}
                  </view>
                </view>

                <!-- 先煎/后下：气泡标签卡片点选（不用 ActionSheet，选项超过 6 个会失败） -->
                <view v-if="drugUseWayList.length" class="way-block m-b-16">
                  <view
                      class="way-row flex-row flex-ali-center flex-jus-sp"
                      @click.stop="toggleWayPanel"
                      :data-index="index"
                  >
                    <d-text text="煎法：" className="fs-28 color-title"></d-text>
                    <view class="way-picker flex-row flex-ali-center">
                      <text class="fs-26" :class="getWayLabel(item) ? 'color-way' : 'color-sub'">
                        {{ getWayDisplayName(item) }}
                      </text>
                      <u-icon
                          :name="wayPanelDrugIndex === index ? 'arrow-up' : 'arrow-right'"
                          size="24"
                          color="#8A92A3"
                          class="m-l-8"
                      ></u-icon>
                    </view>
                  </view>
                  <view
                      v-if="wayPanelDrugIndex === index"
                      class="way-bubble-card"
                      @click.stop
                  >
                    <view
                        v-for="w in drugUseWayList"
                        :key="w.id"
                        class="way-bubble-tag"
                        :class="{ active: isWayActive(item, w) }"
                        @click.stop="selectWayTag"
                        :data-index="index"
                        :data-way-id="w.id"
                    >{{ w.name }}</view>
                  </view>
                </view>

                <view class="quantity-input-row flex-row flex-ali-center flex-jus-sp pt-20 border-t-dashed">
                  <view class="quantity-input-left flex-row flex-ali-center">
                    <d-text text="用量：" className="fs-28 color-title"></d-text>

                    <!-- 现代精致步进器 -->
                    <view class="modern-stepper flex-row flex-ali-center">
                      <view class="stepper-btn" @click.stop="handleDecreaseQuantity" :data-index="index">-</view>
                      <input
                          class="stepper-input fs-28 font-bold"
                          type="number"
                          :value="getQuantity(item)"
                          @input="handleQuantityInput"
                          :data-index="index"
                          placeholder="0"
                      />
                      <view class="stepper-btn" @click.stop="handleIncreaseQuantity" :data-index="index">+</view>
                    </view>
                    <text class="fs-26 color-sub m-l-12">{{ getUnitName(item) }}</text>
                  </view>

                  <view
                      v-if="isInSelected(item)"
                      class="action-btn-text danger"
                      @click.stop="handleRemoveDrug"
                      :data-index="index"
                  >
                    <u-icon name="trash" size="32" class="m-r-8"></u-icon> 移除
                  </view>
                  <view
                      v-else
                      class="action-btn-ghost primary"
                      @click.stop="handleAddDrug"
                      :data-index="index"
                  >
                    <u-icon name="plus" size="24" class="m-r-8"></u-icon> 添加
                  </view>
                </view>
              </view>
            </view>

            <!-- 加载更多 -->
            <view class="load-more" v-if="loading">
              <u-loading mode="circle" color="#6ACDBB"></u-loading> <text class="load-more-text m-l-16">加载中...</text>
            </view>
            <view class="load-more" v-else-if="!hasMore && drugList.length > 0">
              <text class="load-more-text">没有更多了</text>
            </view>
          </view>

          <!-- 空状态 -->
          <view class="empty-state" v-else>
            <d-empty text="暂无药品"></d-empty>
          </view>
        </scroll-view>
      </view>

      <!-- 底部按钮 -->
      <view class="modal-footer flex-jus-center flex-ali-center white shadow-up">
        <u-button
            :throttle-time="0"
            @click="handleClose"
            shape="circle"
            :custom-style="{
            backgroundColor: '#00A88A',
            color: '#fff',
            height: '88rpx',
            width: '670rpx',
            fontWeight: 'bold',
            fontSize: '32rpx',
            boxShadow: '0 8rpx 20rpx rgba(0, 168, 138, 0.25)',
            border: 'none'
          }"
        >关闭</u-button>
      </view>
    </view>
  </u-popup>
</template>

<script>
// 保留所有原有逻辑代码与注释
import { getProductListDoctorReception, getChineseMedicineQuickGramsApi } from '@/api/reception.js';
import { getClinicSalespersonChineseDrugList, getClinicSalespersonChineseMedicineQuickGrams } from '@/api/clinicSalesperson.js';
import { withWxKey } from '@/utils/wxListKey.js';

export default {
  name: 'ChineseMedicineModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 当前已选中的药品列表
     */
    currentDrugs: {
      type: Array,
      default: () => []
    },
    /** 打开时预填搜索关键词（如标签长按「编辑」） */
    initialSearchKey: {
      type: String,
      default: ''
    },
    /** 挂号 ID（取价门店） */
    registerId: {
      type: [String, Number],
      default: ''
    },
    /** 是否可查看毛利率 0/1 */
    seeRate: {
      type: [String, Number],
      default: 0
    },
    /** 推广员传方模式：使用推广员中药列表接口 */
    salespersonTransferMode: {
      type: Boolean,
      default: false
    },
    /** 是否展示药品单价（传方 see_price=0 时为 false） */
    showDrugPrice: {
      type: Boolean,
      default: true
    },
    /** 药材级先煎/后下选项（父页 drugUseList.drug_use_way） */
    drugUseWayList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      show: false,
      searchKey: '',
      drugList: [],
      selectedDrugs: [],
      loading: false,
      searchTimer: null,
      page: 1,
      pageSize: 20,
      hasMore: false,
      // 常用克数（后端全局配置，每次打开抽屉拉取）
      commonQuantities: [],
      /** 当前展开煎法气泡的药材下标，-1 表示收起 */
      wayPanelDrugIndex: -1
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.wayPanelDrugIndex = -1;
        this.selectedDrugs = this.mapSelectedDrugs(JSON.parse(JSON.stringify(this.currentDrugs)));
        this.fetchQuickGrams();
        const kw = (this.initialSearchKey || '').trim();
        if (kw) {
          clearTimeout(this.searchTimer);
          this.searchKey = kw;
          this.page = 1;
          this.hasMore = true;
          this.loadDrugList(kw);
        } else {
          this.resetList();
        }
      } else {
        this.wayPanelDrugIndex = -1;
      }
    },
    show(newVal) {
      if (!newVal) {
        this.wayPanelDrugIndex = -1;
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 拉取全局中药快捷克数（每次打开抽屉一次）
     */
    async fetchQuickGrams() {
      try {
        let data = {};
        if (this.salespersonTransferMode) {
          const wrap = await getClinicSalespersonChineseMedicineQuickGrams();
          if (wrap && wrap.ok) {
            data = wrap.data || {};
          }
        } else {
          const res = await getChineseMedicineQuickGramsApi();
          if (res && (res.code === 0 || res.errcode === 0)) {
            data = res.data || res.result || {};
          }
        }
        const list = Array.isArray(data.grams) ? data.grams : (Array.isArray(data) ? data : []);
        this.commonQuantities = list
          .map((v) => parseFloat(v))
          .filter((n) => !Number.isNaN(n) && n > 0);
      } catch (e) {
        console.error('获取中药快捷克数失败:', e);
        this.commonQuantities = [];
      }
    },
    /**
     * 点击已选 chip：用药名搜索列表（小程序端勿在 @click 传对象，用 data-six + dataset）
     */
    mapSelectedDrugs(list) {
      return withWxKey(list || [], 'index_id', 'sch');
    },
    findSelectedChipIndex(wxKey) {
      return this.selectedDrugs.findIndex((s) => s._wxKey === wxKey);
    },
    handleSelectedChipSearch(e) {
      const wxKey = e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.wxKey;
      const six = this.findSelectedChipIndex(wxKey);
      if (six < 0) return;
      const sel = this.selectedDrugs[six];
      if (!sel) return;
      const name = String(sel.drug_name || sel.name || '').trim();
      if (!name) return;
      clearTimeout(this.searchTimer);
      this.searchKey = name;
      this.page = 1;
      this.hasMore = true;
      this.loadDrugList(name);
    },
    /**
     * 从已选条移除一味（不同步二次确认）
     */
    handleSelectedChipRemove(e) {
      const wxKey = e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.wxKey;
      const six = this.findSelectedChipIndex(wxKey);
      if (six < 0 || six >= this.selectedDrugs.length) return;
      this.selectedDrugs.splice(six, 1);
      this.emitSelect();
      const name = (this.searchKey || '').trim();
      if (name) {
        this.page = 1;
        this.loadDrugList(name);
      }
    },
    resetList() {
      this.searchKey = '';
      this.drugList = [];
      this.page = 1;
      this.hasMore = false;
      this.wayPanelDrugIndex = -1;
    },
    /**
     * 加载药品列表
     * @param {string} keyword - 搜索关键词
     * 职责：调用接口获取中药列表
     */
    async loadDrugList(keyword = '') {
      const name = (keyword || '').trim();
      if (!name) {
        this.drugList = [];
        this.loading = false;
        this.hasMore = false;
        return;
      }
      if (this.loading) {
        return;
      }
      this.loading = true;
      try {
        let list = [];
        if (this.salespersonTransferMode) {
          const wrap = await getClinicSalespersonChineseDrugList({ name });
          if (wrap && wrap.ok) {
            list = Array.isArray(wrap.data) ? wrap.data : [];
          }
          this.hasMore = false;
        } else {
          const storeId = uni.getStorageSync('store_id') || 11001;
          const params = {
            store_id: storeId,
            type: 1,
            name: name,
            page: this.page,
            page_size: this.pageSize
          };
          if (this.registerId) {
            params.register_id = this.registerId;
          }
          const res = await getProductListDoctorReception(params);
          if (res && (res.code === 0 || res.errcode === 0)) {
            list = res.data || res.result || [];
            this.hasMore = list.length >= this.pageSize;
          }
        }

        const merged = list.map(drug => {
          const entityId = (drug.drug && drug.drug.id) || drug.id;
          const selected = this.selectedDrugs.find(item => {
            const matchByIndexId = (item.index_id !== undefined && item.index_id !== null) && item.index_id === drug.id;
            const matchByEntityId = (item.id !== undefined && item.id !== null) && item.id === entityId;
            const matchByDrugId = (item.drug_id !== undefined && item.drug_id !== null) && item.drug_id === entityId;
            return matchByIndexId || matchByEntityId || matchByDrugId;
          });
          this.$set(drug, '_quantity', selected ? selected.number : 0);
          // 恢复已选煎法（先煎/后下）
          const wayId = selected
            ? Number(selected.way_id ?? selected.use_ways?.id ?? 0)
            : Number(drug.way_id || (drug.drug && drug.drug.way_id) || 0);
          this.$set(drug, '_way_id', wayId || 0);
          return drug;
        });
        if (this.page > 1) {
          this.drugList = this.drugList.concat(merged);
        } else {
          // 重新搜索/首屏加载后列表下标变化，收起煎法气泡
          this.wayPanelDrugIndex = -1;
          this.drugList = merged;
        }
        this.drugList.forEach(drug => {
          if (typeof drug._quantity === 'undefined') {
            this.$set(drug, '_quantity', 0);
          }
          if (typeof drug._way_id === 'undefined') {
            this.$set(drug, '_way_id', Number(drug.way_id || (drug.drug && drug.drug.way_id) || 0));
          }
        });
      } catch (error) {
        console.error('获取药品列表失败:', error);
        this.$toast('获取药品列表失败');
        if (this.page === 1) {
          this.drugList = [];
        }
        this.hasMore = false;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 搜索药品
     * 职责：防抖搜索，调用加载药品列表
     */
    handleSearch() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        const name = (this.searchKey || '').trim();
        this.wayPanelDrugIndex = -1;
        if (!name) {
          this.page = 1;
          this.hasMore = false;
          this.drugList = [];
          return;
        }
        this.page = 1;
        this.hasMore = true;
        this.loadDrugList(this.searchKey);
      }, 300);
    },

    /**
     * 获取药品数量
     * @param {Object} drug - 药品数据
     * @returns {number} 数量
     */
    getQuantity(drug) {
      return drug._quantity || 0;
    },

    /**
     * 获取药品名称
     * @param {Object} drug - 药品数据
     * @returns {string} 药品名称
     */
    getDrugName(drug) {
      if (drug.drug && drug.drug.drug_name) {
        return drug.drug.drug_name;
      }
      if (drug.drug_name) {
        return drug.drug_name;
      }
      if (drug.name) {
        return drug.name;
      }
      return '';
    },

    /**
     * 获取单位名称：优先接口返回的 unit，再回退 g
     * @param {Object} item 选药列表项
     * @returns {string}
     */
    getUnitName(item) {
      if (!item) return 'g';
      const unit =
        (item.unit && item.unit.name) ||
        (item.drug && item.drug.unit && item.drug.unit.name) ||
        '';
      return unit || 'g';
    },

    /**
     * 获取规格文案：有规格用规格，否则用真实单位名
     * @param {Object} item 选药列表项
     * @returns {string}
     */
    getSpecification(item) {
      if (!item) return 'g';
      const spec =
        (item.specification) ||
        (item.drug && item.drug.specification) ||
        '';
      if (spec) return spec;
      return this.getUnitName(item);
    },

    /**
     * 从列表项解析单位对象与 unit_id，供写入处方行
     * @param {Object} drug
     * @returns {{ unit: Object|null, unit_id: number }}
     */
    resolveDrugUnit(drug) {
      if (!drug) return { unit: null, unit_id: 0 };
      const unitObj =
        drug.unit ||
        (drug.drug && drug.drug.unit) ||
        null;
      const unitId =
        (unitObj && unitObj.id) ||
        drug.unit_id ||
        (drug.drug && drug.drug.unit_id) ||
        0;
      return {
        unit: unitObj || (unitId ? { id: unitId, name: 'g' } : null),
        unit_id: Number(unitId) || 0,
      };
    },

    /**
     * 判断是否已选中该中药（基于父组件传入的 currentDrugs，初始展示用）
     * @param {Object} drug
     * @returns {boolean}
     */
    isSelected(drug) {
      if (!this.currentDrugs || !drug) return false;
      const id = drug.id || drug.drug_id;
      return this.currentDrugs.some(item => (item.id || item.drug_id) === id);
    },

    /**
     * 判断是否已加入本次会话的处方（基于实时 selectedDrugs）
     * @param {Object} drug
     * @returns {boolean}
     */
    isInSelected(drug) {
      return this.findSelectedIndex(drug) !== -1;
    },

    /**
     * 在 selectedDrugs 中查找当前 drug 对应的索引
     * 匹配优先级：index_id === drug.id；否则 id === drug.drug?.id || drug.id
     * @param {Object} drug
     * @returns {number} 找到返回索引，未找到返回 -1
     */
    findSelectedIndex(drug) {
      if (!drug || !Array.isArray(this.selectedDrugs)) return -1;
      const listId = drug.id;
      const entityId = (drug.drug && drug.drug.id) || drug.id;
      return this.selectedDrugs.findIndex(item => {
        const matchByIndexId = (item.index_id !== undefined && item.index_id !== null) && item.index_id === listId;
        const matchByEntityId = (item.id !== undefined && item.id !== null) && item.id === entityId;
        const matchByDrugId = (item.drug_id !== undefined && item.drug_id !== null) && item.drug_id === entityId;
        return matchByIndexId || matchByEntityId || matchByDrugId;
      });
    },

    /**
     * 把 drugList 中某个药品转成 selectedDrugs 的标准条目
     * 字段与原 handleConfirm 中保持一致
     * @param {Object} drug
     * @returns {Object}
     */
    buildSelectedItem(drug) {
      let drugName = '';
      if (drug.drug && drug.drug.drug_name) {
        drugName = drug.drug.drug_name;
      } else if (drug.drug_name) {
        drugName = drug.drug_name;
      } else if (drug.name) {
        drugName = drug.name;
      }
      const indexId = drug.id;
      const entityId = (drug.drug && drug.drug.id) || drug.id;
      const wxKeyBase = indexId != null && indexId !== '' ? String(indexId) : String(entityId || '');
      const wayId = Number(
        drug._way_id ?? (drug.drug && drug.drug.way_id) ?? drug.way_id ?? 0
      );
      const wayHit = (this.drugUseWayList || []).find((w) => Number(w.id) === wayId);
      // 写入真实单位，保证父页标签云与提交后展示一致
      const { unit, unit_id: unitId } = this.resolveDrugUnit(drug);
      return {
        index_id: indexId,
        id: entityId,
        drug_name: drugName,
        number: drug._quantity,
        price: drug.price || 0,
        buy_price: drug.buy_price ?? 0,
        way_id: wayId || 0,
        use_ways: wayHit || null,
        unit,
        unit_id: unitId,
        select_number: 1,
        _wxKey: wxKeyBase ? `sch-${wxKeyBase}` : `sch${this.selectedDrugs.length}`,
      };
    },

    /**
     * 展示非默认煎法文案；煎服/0 不展示（chip）或用「煎服（默认）」在选择行
     */
    getWayLabel(drugOrSel) {
      if (!drugOrSel) return '';
      const wayId = Number(
        drugOrSel._way_id ?? drugOrSel.way_id ?? drugOrSel.use_ways?.id ?? 0
      );
      if (!wayId) return '';
      const hit = (this.drugUseWayList || []).find((w) => Number(w.id) === wayId);
      const name =
        (hit && hit.name) ||
        (drugOrSel.use_ways && drugOrSel.use_ways.name) ||
        '';
      if (!name || name === '煎服') return '';
      return name;
    },

    /**
     * 煎法行展示文案：有先煎/后下等显示标签名，否则「煎服（默认）」
     */
    getWayDisplayName(drugOrSel) {
      return this.getWayLabel(drugOrSel) || '煎服（默认）';
    },
    /**
     * 判断气泡标签是否为当前药材选中煎法
     */
    isWayActive(drug, wayItem) {
      if (!drug || !wayItem) return false;
      const wayId = Number(drug._way_id ?? drug.way_id ?? 0);
      return wayId > 0 && wayId === Number(wayItem.id);
    },
    /**
     * 展开/收起当前药材的煎法气泡卡片（同时只开一行）
     */
    toggleWayPanel(event) {
      const index = Number(event.currentTarget.dataset.index);
      if (Number.isNaN(index)) return;
      if (!(this.drugUseWayList || []).length) {
        this.$toast('暂无煎法选项');
        return;
      }
      this.wayPanelDrugIndex = this.wayPanelDrugIndex === index ? -1 : index;
    },
    /**
     * 气泡标签点选煎法：写入 _way_id 并同步已选处方后收起
     */
    selectWayTag(event) {
      const ds = event.currentTarget.dataset || {};
      const index = Number(ds.index);
      const wayId = Number(ds.wayId ?? ds['way-id'] ?? 0);
      const drug = this.drugList[index];
      if (!drug || Number.isNaN(index)) return;
      const picked = (this.drugUseWayList || []).find((w) => Number(w.id) === wayId) || null;
      this.$set(drug, '_way_id', wayId || 0);
      this.$set(drug, 'way_id', wayId || 0);
      const existIndex = this.findSelectedIndex(drug);
      if (existIndex !== -1) {
        this.$set(this.selectedDrugs[existIndex], 'way_id', wayId || 0);
        this.$set(this.selectedDrugs[existIndex], 'use_ways', picked);
        this.emitSelect();
      } else if (drug._quantity > 0) {
        this.tryAutoAddDrug(drug, { showToast: false });
      }
      this.wayPanelDrugIndex = -1;
    },

    /**
     * emit select 事件，传出当前完整的 selectedDrugs（深拷贝）
     */
    emitSelect() {
      const payload = JSON.parse(JSON.stringify(this.selectedDrugs));
      this.$emit('select', payload);
    },

    /**
     * 自动添加药品：快捷克数/输入克数时若尚未加入处方则自动添加
     * @param {Object} drug 搜索列表中的药品
     * @param {{ showToast?: boolean }} options showToast 仅首次添加时提示
     */
    tryAutoAddDrug(drug, options = {}) {
      if (!drug || !drug._quantity || drug._quantity <= 0) {
        return;
      }
      const existIndex = this.findSelectedIndex(drug);
      const isNew = existIndex === -1;
      if (existIndex !== -1) {
        this.$set(this.selectedDrugs[existIndex], 'number', drug._quantity);
        // 保持煎法与列表一致
        const wayId = Number(drug._way_id ?? drug.way_id ?? 0);
        this.$set(this.selectedDrugs[existIndex], 'way_id', wayId);
        const wayHit = (this.drugUseWayList || []).find((w) => Number(w.id) === wayId);
        this.$set(this.selectedDrugs[existIndex], 'use_ways', wayHit || null);
      } else {
        this.selectedDrugs.push(this.buildSelectedItem(drug));
      }
      this.emitSelect();
      if (isNew && options.showToast) {
        this.$toast(`已将${this.getDrugName(drug)}添加到处方`);
      }
    },

    /**
     * 添加药品到处方
     * @param {Event} event - 点击事件对象
     */
    handleAddDrug(event) {
      const index = event.currentTarget.dataset.index;
      if (index === undefined || index === null) {
        console.error('handleAddDrug: index is undefined');
        return;
      }
      const drug = this.drugList[index];
      if (!drug) {
        console.error('handleAddDrug: drug not found at index', index);
        return;
      }

      // 用量为空或 0 时，默认设为 1
      if (!drug._quantity || drug._quantity <= 0) {
        this.$set(drug, '_quantity', 1);
      }

      this.tryAutoAddDrug(drug, { showToast: true });
    },

    /**
     * 从处方中移除药品
     * @param {Event} event - 点击事件对象
     */
    handleRemoveDrug(event) {
      const index = event.currentTarget.dataset.index;
      if (index === undefined || index === null) {
        console.error('handleRemoveDrug: index is undefined');
        return;
      }
      const drug = this.drugList[index];
      if (!drug) {
        console.error('handleRemoveDrug: drug not found at index', index);
        return;
      }

      const existIndex = this.findSelectedIndex(drug);
      if (existIndex !== -1) {
        this.selectedDrugs.splice(existIndex, 1);
      }
      this.$set(drug, '_quantity', 0);
      this.emitSelect();
    },

    /**
     * 把 drug 的最新 _quantity 同步到 selectedDrugs 中（如果已加入处方）
     * 用于 +/-、输入、点击常用克数后实时同步
     * @param {Object} drug
     */
    syncQuantityToSelected(drug) {
      const existIndex = this.findSelectedIndex(drug);
      if (existIndex === -1) return;
      const newNumber = drug._quantity || 0;
      if (newNumber <= 0) {
        // 数量被改为 0，从处方中移除
        this.selectedDrugs.splice(existIndex, 1);
      } else {
        this.$set(this.selectedDrugs[existIndex], 'number', newNumber);
      }
      this.emitSelect();
    },

    /**
     * 增加数量
     * @param {Event} event - 点击事件对象
     * 职责：增加药品数量
     */
    handleIncreaseQuantity(event) {
      const index = event.currentTarget.dataset.index;
      console.log('handleIncreaseQuantity called', { index, drugListLength: this.drugList.length });

      if (index === undefined || index === null) {
        console.error('handleIncreaseQuantity: index is undefined');
        return;
      }

      const drug = this.drugList[index];
      console.log('drug found', drug);

      if (!drug) {
        console.error('handleIncreaseQuantity: drug not found at index', index);
        return;
      }

      // 确保 _quantity 属性存在
      if (typeof drug._quantity === 'undefined') {
        this.$set(drug, '_quantity', 0);
      }
      this.$set(drug, '_quantity', (drug._quantity || 0) + 1);
      this.tryAutoAddDrug(drug, { showToast: !this.isInSelected(drug) });
    },

    /**
     * 减少数量
     * @param {Event} event - 点击事件对象
     * 职责：减少药品数量，如果为0则从选中列表移除
     */
    handleDecreaseQuantity(event) {
      const index = event.currentTarget.dataset.index;
      console.log('handleDecreaseQuantity called', { index, drugListLength: this.drugList.length });

      if (index === undefined || index === null) {
        console.error('handleDecreaseQuantity: index is undefined');
        return;
      }

      const drug = this.drugList[index];
      console.log('drug found', drug);

      if (!drug) {
        console.error('handleDecreaseQuantity: drug not found at index', index);
        return;
      }

      // 确保 _quantity 属性存在
      if (typeof drug._quantity === 'undefined') {
        this.$set(drug, '_quantity', 0);
        return;
      }
      if (drug._quantity > 0) {
        this.$set(drug, '_quantity', drug._quantity - 1);
        this.syncQuantityToSelected(drug);
      }
    },

    /**
     * 处理数量输入
     * @param {Event} event - 输入事件对象
     * 职责：更新药品数量
     */
    handleQuantityInput(event) {
      const index = event.currentTarget.dataset.index;
      console.log('handleQuantityInput called', { index, drugListLength: this.drugList.length });

      if (index === undefined || index === null) {
        console.error('handleQuantityInput: index is undefined');
        return;
      }

      const drug = this.drugList[index];
      console.log('drug found', drug);

      if (!drug) {
        console.error('handleQuantityInput: drug not found at index', index);
        return;
      }

      if (!event || !event.detail) {
        console.error('handleQuantityInput: event or event.detail is undefined');
        return;
      }

      const value = event.detail.value;
      const numValue = parseFloat(value);

      // 确保 _quantity 属性存在
      if (typeof drug._quantity === 'undefined') {
        this.$set(drug, '_quantity', 0);
      }

      if (!isNaN(numValue) && numValue >= 0) {
        this.$set(drug, '_quantity', numValue);
        if (numValue > 0) {
          this.tryAutoAddDrug(drug, { showToast: !this.isInSelected(drug) });
        } else {
          this.syncQuantityToSelected(drug);
        }
      } else if (value === '') {
        this.$set(drug, '_quantity', 0);
        this.syncQuantityToSelected(drug);
      }
    },

    /**
     * 选择常用克数
     * @param {Event} event - 点击事件对象
     * 职责：将常用克数写入到药品数量
     */
    handleSelectCommonQuantity(event) {
      const index = event.currentTarget.dataset.index;
      const quantity = parseFloat(event.currentTarget.dataset.quantity);
      console.log('handleSelectCommonQuantity called', { index, quantity, drugListLength: this.drugList.length });

      if (index === undefined || index === null) {
        console.error('handleSelectCommonQuantity: index is undefined');
        return;
      }

      if (isNaN(quantity)) {
        console.error('handleSelectCommonQuantity: quantity is NaN', event.currentTarget.dataset.quantity);
        return;
      }

      const drug = this.drugList[index];
      console.log('drug found', drug);

      if (!drug) {
        console.error('handleSelectCommonQuantity: drug not found at index', index);
        return;
      }

      // 确保 _quantity 属性存在
      if (typeof drug._quantity === 'undefined') {
        this.$set(drug, '_quantity', 0);
      }
      // 设置数量并自动添加到处方
      this.$set(drug, '_quantity', quantity);
      this.tryAutoAddDrug(drug, { showToast: !this.isInSelected(drug) });
    },

    /**
     * 触底加载更多
     */
    loadMore() {
      const name = (this.searchKey || '').trim();
      if (this.loading || !this.hasMore || !name) {
        return;
      }
      this.page += 1;
      this.loadDrugList(this.searchKey);
    },

    /**
     * 关闭弹窗
     * 职责：关闭弹窗，触发input事件
     * 注：由于 add/remove/调用量都是实时 emit，关闭无需额外提交
     */
    handleClose() {
      this.show = false;
      this.$emit('input', false);
    }
  }
};
</script>

<style lang="scss" scoped>
/* 使用与 index.vue 统一的设计风格与变量 */
.page-bg { background-color: #F4F6F8; }
.white { background: #fff; }
.color-title { color: #2A2E35; }
.color-sub { color: #8A92A3; }
.color-price { color: #F53F3F; }
.color-way { color: #5b8ff9; }
.fs-26 { font-size: 26rpx; }
.fs-28 { font-size: 28rpx; }
.fs-32 { font-size: 32rpx; }
.font-bold { font-weight: bold; }
.m-b-16 { margin-bottom: 16rpx; }
.m-b-24 { margin-bottom: 24rpx; }
.m-r-8 { margin-right: 8rpx; }
.m-l-12 { margin-left: 12rpx; }
.m-l-16 { margin-left: 16rpx; }
.pt-20 { padding-top: 20rpx; }
.border-t-dashed { border-top: 1px dashed #E2E8F0; }
.shadow-up { box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.04); }

.flex-row { display: flex; flex-direction: row; }
.flex-jus-sp { justify-content: space-between; }
.flex-jus-center { justify-content: center; }
.flex-ali-center { align-items: center; }

.chinese-medicine-modal {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.modal-header {
  padding: 32rpx;
  text-align: center;
  border-bottom: 1px solid #F0F2F5;
}

.modal-content {
  flex: 1;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.selected-strip-wrap {
  width: 100%;
  flex-shrink: 0;
}

.selected-strip-scroll {
  width: 100%;
  white-space: nowrap;
}

.selected-strip-inner {
  display: inline-flex;
  flex-direction: row;
  flex-wrap: nowrap;
  padding-bottom: 4rpx;
}

.selected-chip {
  flex-shrink: 0;
  margin-right: 16rpx;
  background: #fff;
  border-radius: 32rpx;
  padding: 8rpx 8rpx 8rpx 20rpx;
  border: 1rpx solid #E2E8F0;
  box-shadow: 0 2rpx 8rpx rgba(42, 46, 53, 0.06);
}

.selected-chip-main {
  max-width: 280rpx;
}

.selected-chip-name {
  font-size: 26rpx;
  font-weight: bold;
  color: #2A2E35;
  max-width: 180rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selected-chip-dose {
  font-size: 24rpx;
  color: #00A88A;
  margin-left: 8rpx;
}
.selected-chip-way {
  font-size: 22rpx;
  color: #5b8ff9;
  margin-left: 8rpx;
  font-weight: 500;
}
.way-block {
  width: 100%;
}
.way-row {
  padding: 8rpx 0;
}
.way-picker {
  padding: 8rpx 16rpx;
  background: #F7F8FA;
  border-radius: 8rpx;
  border: 1rpx solid #E2E8F0;
}
/* 煎法气泡卡片：标签直接点选，不限 ActionSheet 6 项 */
.way-bubble-card {
  margin-top: 12rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  border: 1rpx solid #E2E8F0;
  box-shadow: 0 8rpx 24rpx rgba(42, 46, 53, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
.way-bubble-tag {
  padding: 10rpx 24rpx;
  background-color: #F4F6F8;
  color: #6C7380;
  border-radius: 30rpx;
  font-size: 24rpx;
  line-height: 1.4;
}
.way-bubble-tag.active {
  background-color: #00A88A;
  color: #fff;
}

.selected-chip-close {
  padding: 8rpx 12rpx 8rpx 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drug-list-scroll {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

/* 底部防遮挡边距 */
.drug-list {
  padding-bottom: 24rpx;
}

/* 底部防遮挡边距 */
.drug-list {
  padding-bottom: 120rpx;
}

/* 现代卡片样式 */
.medicine-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(42, 46, 53, 0.04);
  position: relative;
  overflow: hidden;
  border: 2rpx solid transparent;
  transition: all 0.2s;

  &.is-selected {
    border-color: #00A88A;
    background-color: #F8FDFB;
  }
}

.selected-indicator {
  width: 8rpx;
  height: 32rpx;
  background-color: #00A88A;
  border-radius: 4rpx;
  margin-right: 12rpx;
}

.usage-capsule {
  display: inline-flex;
  align-items: center;
  background: #E8F6F4;
  color: #00A88A;
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.common-quantity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.modern-tag {
  padding: 10rpx 24rpx;
  background-color: #F4F6F8;
  color: #6C7380;
  border-radius: 30rpx;
  font-size: 24rpx;
  cursor: pointer;
  transition: all 0.2s;
  &:active {
    background-color: #00A88A;
    color: #fff;
  }
}

/* 现代精致步进器 */
.modern-stepper {
  background: #F7F8FA;
  border-radius: 8rpx;
  overflow: hidden;
  border: 1px solid #E2E8F0;

  .stepper-btn {
    width: 60rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6C7380;
    font-size: 36rpx;
    font-weight: bold;
    background: #fff;
    cursor: pointer;
  }

  .stepper-input {
    width: 80rpx;
    height: 56rpx;
    text-align: center;
    color: #2A2E35;
    background: #F7F8FA;
    border-left: 1px solid #E2E8F0;
    border-right: 1px solid #E2E8F0;
  }
}

.action-btn-ghost {
  padding: 10rpx 28rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  &.primary {
    color: #00A88A;
    background: #E8F6F4;
  }
}

.action-btn-text {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  font-weight: bold;
  &.danger { color: #8A92A3; }
}

.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32rpx 0;
  .load-more-text {
    font-size: 24rpx;
    color: #999;
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  text-align: center;
}

.modal-footer {
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  background-color: #fff;
}

/* 配送仓绑定药品标识 */
.multi-wh-tag {
  flex-shrink: 0;
  padding: 0 10rpx;
  height: 32rpx;
  line-height: 30rpx;
  font-size: 20rpx;
  color: #2b6de5;
  background: rgba(43, 109, 229, 0.08);
  border: 1rpx solid rgba(43, 109, 229, 0.45);
  border-radius: 999rpx;
}
</style>