<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="simple-product-modal page-bg">
      <view class="modal-header white">
        <d-text :text="getModalTitle()" 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="product-list" v-if="productList.length > 0">
            <view
                class="medicine-card"
                v-for="item in productList"
                :key="item.id"
            >
              <view class="flex-row">
                <image
                    v-if="(item.drug && item.drug.image) || item.image"
                    :src="(item.drug && item.drug.image) || item.image"
                    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">
                    <view class="flex-row flex-ali-center w-70">
                      <text class="fs-30 font-bold color-title line-clamp-2">{{item.drug.drug_name || item.drug.name}}</text>
                      <text v-if="Number(item.has_delivery_warehouse) === 1" class="multi-wh-tag m-l-8">多仓</text>
                    </view>
                    <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="product-action m-t-24">
                    <view class="action-btn-ghost primary" @click.stop="handleSelectProduct(item)">
                      <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: 'SimpleProductModal',
  props: {
    /**
     * 弹窗显示状态
     */
    value: {
      type: Boolean,
      default: false
    },
    /**
     * 产品类型：3=保健食品，5=产品服务包，6=非药品，7=医疗器械
     */
    productType: {
      type: Number,
      default: 3
    },
    /**
     * 当前已选中的产品列表
     */
    currentProducts: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      show: false,
      searchKey: '',
      productList: [],
      loading: false,
      searchTimer: null
    };
  },
  watch: {
    value(newVal) {
      this.show = newVal;
      if (newVal) {
        this.loadProductList();
      }
    },
    show(newVal) {
      if (!newVal) {
        this.$emit('input', false);
      }
    }
  },
  methods: {
    /**
     * 获取弹窗标题
     * @returns {string} 弹窗标题
     */
    getModalTitle() {
      const titles = {
        3: '选择保健食品',
        5: '选择产品服务包',
        6: '选择非药品',
        7: '选择医疗器械'
      };
      return titles[this.productType] || '选择产品';
    },

    /**
     * 加载产品列表
     * @param {string} keyword - 搜索关键词
     * 职责：调用接口获取产品列表
     */
    async loadProductList(keyword = '') {
      this.loading = true;
      try {
        const storeId = uni.getStorageSync('store_id') || 11001;
        const res = await getProductListDoctorReception({
          store_id: storeId,
          type: this.productType,
          name: keyword
        });

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

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

    /**
     * 选择产品
     * @param {Object} product - 产品数据
     * 职责：触发select事件，传递选中的产品
     */
    handleSelectProduct(product) {
      this.$emit('select', product);
      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; }

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

/* 底部防遮挡边距（避免最后一行被底部按钮遮挡） */
.product-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;
}

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

.product-action {
  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;
  }
}

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

/* 配送仓绑定药品标识 */
.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>