<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="western-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>

        <scroll-view class="list-scroll" scroll-y>
          <!-- 药品列表 -->
          <view class="drug-list" v-if="drugList.length > 0">
            <view
                class="medicine-card"
                v-for="(item, index) in drugList"
                :key="index"
                :class="{ 'is-selected': isSelected(item) }"
                @click="!isSelected(item) && handleSelectDrug(item)"
            >
              <view class="flex-row">
                <image
                    v-if="getDrugImage(item)"
                    :src="getDrugImage(item)"
                    class="drug-image-modern"
                    mode="aspectFill"
                ></image>
                <view class="flex-1 m-l-24 flex-col">
                  <view class="flex-row flex-jus-sp flex-ali-start">
                    <text class="fs-30 font-bold color-title line-clamp-2 w-70">{{item.drug.drug_name || item.drug.name}}</text>
                    <text class="fs-32 font-bold color-price">￥{{parseFloat(item.price || 0).toFixed(2)}}</text>
                  </view>
                  <view class="flex-row flex-jus-sp flex-ali-center m-t-12">
                    <text class="fs-24 color-sub">规格：{{item.drug.specification || '--'}}</text>
                  </view>
                  <view class="drug-status m-t-24">
                    <view v-if="isSelected(item)" class="action-btn-ghost disabled">
                      已添加处方
                    </view>
                    <view v-else class="action-btn-ghost primary">
                      <u-icon name="plus" size="24" class="m-r-8"></u-icon> 选用此药
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>

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

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

<script>
// 保留所有原有逻辑代码与注释
import { getProductListDoctorReception } from '@/api/reception.js';

export default {
  name: 'WesternMedicineModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 当前已选中的药品列表
     */
    currentDrugs: {
      type: Array,
      default: () => []
    },
    /** 打开时预填搜索关键词（如接诊聊天「加入处方」） */
    initialSearchKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      show: false,
      searchKey: '',
      drugList: [],
      loading: false,
      searchTimer: null
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        const kw = (this.initialSearchKey || '').trim();
        this.searchKey = kw;
        this.loadDrugList(kw);
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 加载药品列表
     * @param {string} keyword - 搜索关键词
     * 职责：调用接口获取西药列表
     */
    async loadDrugList(keyword = '') {
      this.loading = true;
      try {
        const storeId = uni.getStorageSync('store_id') || 11001;
        const res = await getProductListDoctorReception({
          store_id: storeId,
          type: 2, // 西药
          name: keyword
        });

        if (res && (res.code === 0 || res.errcode === 0)) {
          this.drugList = res.data || res.result || [];
        } else {
          this.drugList = [];
        }
      } catch (error) {
        console.error('获取药品列表失败:', error);
        this.$toast('获取药品列表失败');
        this.drugList = [];
      } finally {
        this.loading = false;
      }
    },

    /**
     * 搜索药品
     * 职责：防抖搜索，调用加载药品列表
     */
    handleSearch() {
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.loadDrugList(this.searchKey);
      }, 300);
    },

    /**
     * 获取药品图片
     * @param {Object} item - 药品数据
     * @returns {string} 图片URL
     */
    getDrugImage(item) {
      if (item.drug && item.drug.image) {
        return item.drug.image;
      }
      if (item.image) {
        return item.image;
      }
      return '';
    },

    /**
     * 判断药品是否已在当前处方中
     * @param {Object} drug
     * @returns {boolean}
     */
    isSelected(drug) {
      if (!this.currentDrugs || !drug) return false;
      const drugId = drug.drug_id || (drug.drug && drug.drug.id) || drug.id;
      return this.currentDrugs.some(item => (item.id || item.drug_id) === drugId);
    },

    /**
     * 选择药品
     * @param {Object} drug - 药品数据
     * 职责：触发select事件，传递选中的药品
     */
    handleSelectDrug(drug) {
      if (this.isSelected(drug)) {
        return;
      }
      this.$emit('select', drug);
      this.handleClose();
    },

    /**
     * 关闭弹窗
     * 职责：关闭弹窗，触发input事件
     */
    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; }
.fs-24 { font-size: 24rpx; }
.fs-30 { font-size: 30rpx; }
.fs-32 { font-size: 32rpx; }
.font-bold { font-weight: bold; }
.m-b-24 { margin-bottom: 24rpx; }
.m-t-12 { margin-top: 12rpx; }
.m-t-24 { margin-top: 24rpx; }
.m-l-24 { margin-left: 24rpx; }
.m-r-8 { margin-right: 8rpx; }
.shadow-up { box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.04); }

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

.western-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;
  min-height: 0;
  padding: 32rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

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

/* 底部防遮挡边距（避免最后一行被底部按钮遮挡） */
.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: #E2E8F0;
    background-color: #F8FAFC;
    opacity: 0.8;
  }
}

.drug-image-modern {
  width: 140rpx;
  height: 140rpx;
  border-radius: 12rpx;
  background-color: #F7F8FA;
  flex-shrink: 0;
  border: 1px solid #F0F2F5;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.w-70 { width: 70%; }

.drug-status {
  display: flex;
  justify-content: flex-end;
}

.action-btn-ghost {
  padding: 8rpx 24rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  font-weight: bold;
  display: flex;
  align-items: center;

  &.primary {
    color: #00A88A;
    background: #E8F6F4;
  }
  &.disabled {
    color: #8A92A3;
    background: #F4F6F8;
    border: 1px solid #E2E8F0;
  }
}

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

.modal-footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  background-color: #fff;
}
</style>