<template>
  <view>
    <!-- #ifdef MP-WEIXIN -->
    <!-- 用 page-container 防止右滑误退出开方页 -->
    <page-container
      v-if="show"
      :show="show"
      :overlay="false"
      @leave="handleClose"
    />
    <!-- #endif -->
    <u-popup
      v-model="show"
      mode="bottom"
      :closeable="true"
      @close="handleClose"
      :safe-area-inset-bottom="true"
      :mask-close-able="true"
      z-index="10080"
      height="75%"
    >
      <view class="warehouse-select-drawer page-bg">
        <view class="modal-header white">
          <d-text text="选择配送仓库" className="fs-32 font-bold color-title"></d-text>
        </view>
        <scroll-view class="scroll-container" scroll-y>
          <view v-if="currentRow" class="step-body">
            <view class="step-progress">第 {{ stepIndex + 1 }} / {{ localRows.length }} 个药品</view>
            <!-- 当前药品：图 / 名 / 规格 -->
            <view class="drug-info flex-row flex-ali-start">
              <image
                v-if="currentRow.image"
                class="drug-img"
                :src="currentRow.image"
                mode="aspectFill"
              />
              <view v-else class="drug-img drug-img-placeholder">暂无图</view>
              <view class="drug-meta">
                <view class="drug-name">{{ currentRow.drug_name }}</view>
                <view class="drug-spec">规格：{{ currentRow.specification || '--' }}</view>
              </view>
            </view>
            <view class="card-list">
              <view
                v-for="opt in currentRow.options"
                :key="opt.warehouse_id"
                class="wh-card"
                :class="{ 'is-active': currentRow.warehouse_id === opt.warehouse_id }"
                @click="selectWarehouse(opt.warehouse_id)"
              >
                <view class="wh-name">{{ opt.warehouse_name }}</view>
                <view class="wh-meta">
                  供货价 {{ opt.quote }} · 库存 {{ opt.available_stock }}
                </view>
              </view>
            </view>
          </view>
          <view v-else class="empty-tip">当前药品无需选择配送仓库</view>
        </scroll-view>
        <!-- 底部：外包 flex 半宽，避免 u-button custom-style 的 flex 在小程序被忽略 -->
        <view class="modal-footer white shadow-up">
          <view class="footer-btn-wrap">
            <u-button
              :throttle-time="0"
              @click="onLeftClick"
              shape="circle"
              :custom-style="leftBtnStyle"
            >{{ leftBtnText }}</u-button>
          </view>
          <view class="footer-btn-wrap">
            <u-button
              :throttle-time="0"
              @click="onRightClick"
              shape="circle"
              :custom-style="rightBtnStyle"
            >{{ rightBtnText }}</u-button>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
/**
 * 在线复诊开方：按药分步卡片选配送仓
 * 默认选中每药 options[0]（与 auto 最低 quote 一致）
 */
export default {
  name: 'WarehouseSelectDrawer',
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    /** [{ drug_id, drug_name, image, specification, options, warehouse_id? }] */
    rows: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      localRows: [],
      stepIndex: 0,
    };
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(v) {
        this.$emit('input', v);
      },
    },
    currentRow() {
      return this.localRows[this.stepIndex] || null;
    },
    isFirstStep() {
      return this.stepIndex <= 0;
    },
    isLastStep() {
      return this.stepIndex >= Math.max(this.localRows.length - 1, 0);
    },
    leftBtnText() {
      return this.isFirstStep ? '取消' : '上一步';
    },
    rightBtnText() {
      return this.isLastStep ? '确认' : '下一步';
    },
    leftBtnStyle() {
      return {
        width: '100%',
        height: '88rpx',
        margin: '0',
        background: '#F5F6F8',
        color: '#333',
        border: 'none',
        fontSize: '30rpx',
        fontWeight: 'bold',
      };
    },
    rightBtnStyle() {
      return {
        width: '100%',
        height: '88rpx',
        margin: '0',
        background: '#2B6DE5',
        color: '#fff',
        border: 'none',
        fontSize: '30rpx',
        fontWeight: 'bold',
      };
    },
  },
  watch: {
    value(val) {
      if (val) {
        // 打开时默认选中每药最低价仓（options[0]）；规格/图/名可从 option 回退
        this.localRows = (this.rows || []).map((row) => {
          const first =
            Array.isArray(row.options) && row.options[0] ? row.options[0] : null;
          return {
            ...row,
            warehouse_id:
              row.warehouse_id ||
              (first && first.warehouse_id) ||
              0,
            options: Array.isArray(row.options) ? row.options : [],
            drug_name: row.drug_name || (first && first.drug_name) || '',
            image: row.image || (first && first.image) || '',
            specification:
              row.specification || (first && first.specification) || '',
          };
        });
        this.stepIndex = 0;
      }
    },
  },
  methods: {
    /** 点击卡片选中当前步骤的仓 */
    selectWarehouse(warehouseId) {
      if (!this.currentRow) return;
      this.$set
        ? this.$set(this.currentRow, 'warehouse_id', warehouseId)
        : (this.currentRow.warehouse_id = warehouseId);
    },
    onLeftClick() {
      if (this.isFirstStep) {
        this.handleClose();
        return;
      }
      this.stepIndex -= 1;
    },
    onRightClick() {
      if (!this.currentRow || !this.currentRow.warehouse_id) {
        uni.showToast({ title: '请先选择配送仓库', icon: 'none' });
        return;
      }
      if (!this.isLastStep) {
        this.stepIndex += 1;
        return;
      }
      this.handleConfirm();
    },
    handleClose() {
      this.show = false;
      this.$emit('cancel');
    },
    handleConfirm() {
      const map = {};
      for (const row of this.localRows) {
        if (!row.warehouse_id) {
          uni.showToast({ title: `请为【${row.drug_name}】选择配送仓库`, icon: 'none' });
          return;
        }
        map[row.drug_id] = row.warehouse_id;
      }
      this.show = false;
      this.$emit('confirm', map);
    },
  },
};
</script>

<style lang="scss" scoped>
.warehouse-select-drawer {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.modal-header {
  padding: 32rpx 32rpx 16rpx;
}
.scroll-container {
  flex: 1;
  height: 0;
  padding: 0 24rpx 24rpx;
  box-sizing: border-box;
}
.step-progress {
  font-size: 24rpx;
  color: #8a92a3;
  margin-bottom: 20rpx;
}
.drug-info {
  padding: 20rpx;
  border-radius: 16rpx;
  background: #f5f6f8;
  margin-bottom: 24rpx;
}
.drug-img {
  width: 112rpx;
  height: 112rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  background: #e5e6eb;
}
.drug-img-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22rpx;
  color: #8a92a3;
}
.drug-meta {
  flex: 1;
  min-width: 0;
}
.drug-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2329;
}
.drug-spec {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #8a92a3;
}
.card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
.wh-card {
  min-width: 280rpx;
  flex: 1;
  max-width: 48%;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  border: 2rpx solid #e5e6eb;
  background: #fff;
  box-sizing: border-box;
}
.wh-card.is-active {
  border-color: #2b6de5;
  background: rgba(43, 109, 229, 0.06);
}
.wh-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #1f2329;
}
.wh-meta {
  margin-top: 8rpx;
  font-size: 22rpx;
  color: #8a92a3;
}
.empty-tip {
  padding: 48rpx 0;
  text-align: center;
  color: #8a92a3;
  font-size: 26rpx;
}
.modal-footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 24rpx;
  padding: 20rpx 32rpx calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
}
.footer-btn-wrap {
  flex: 1;
  min-width: 0;
}
.shadow-up {
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}
</style>
