<template>
  <!-- 搜索栏 -->
  <view class="search-bar" id="searchBar" :style="{ paddingTop: statusBarHeight + 'px' }">
    <view class="search-input-wrap">
      <text class="search-icon">🔍</text>
      <input
        class="search-input"
        placeholder="搜索商品"
        placeholder-class="search-placeholder"
        :value="keyword"
        @input="onInput"
        @blur="onBlur"
      />
    </view>
    <view class="filter-btn" @tap="onFilter">
      <text class="filter-icon">⚙</text>
      <text class="filter-text">筛选</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'SearchBar',
  props: {
    keyword: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      statusBarHeight: 20
    }
  },
  created() {
    try {
      const sysInfo = uni.getSystemInfoSync()
      this.statusBarHeight = sysInfo.statusBarHeight || 20
    } catch (e) {
      this.statusBarHeight = 20
    }
  },
  mounted() {
    // 测量自身高度并 emit 给父组件（小程序端无法跨组件查询 DOM，必须自测量）
    this.$nextTick(() => this.emitHeight())
  },
  methods: {
    emitHeight() {
      const query = uni.createSelectorQuery().in(this)
      query.select('#searchBar').boundingClientRect()
      query.exec((res) => {
        if (res && res[0]) {
          this.$emit('height-change', res[0].height)
        }
      })
    },
    onInput(e) {
      this.$emit('input', e.detail.value)
    },
    onBlur() {
      this.$emit('blur')
    },
    onFilter() {
      this.$emit('filter')
    }
  }
}
</script>

<style scoped>
.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 32rpx;
  background: #ffffff;
  border-bottom: 2rpx solid #f5f5f5;
  box-sizing: border-box;
}
.search-input-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  height: 72rpx;
  padding: 0 24rpx;
  background: #f5f5f5;
  border-radius: 36rpx;
}
.search-icon {
  font-size: 28rpx;
  margin-right: 12rpx;
}
.search-input {
  flex: 1;
  font-size: 26rpx;
  color: #333333;
}
.search-placeholder {
  color: #999999;
}
.filter-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 20rpx;
  font-size: 26rpx;
  color: #666666;
}
.filter-icon {
  font-size: 28rpx;
}
.filter-text {
  font-size: 26rpx;
}
</style>
