<template>
  <div>
    <van-popup v-model:show="innerShowPicker"
      destroy-on-close
      round
      position="bottom"
      @close="onPopupClose">
      <van-picker 
      :columns="columns"
        :cancel-button-text="searchShow ? '' : '取消'"
        @confirm="onConfirm">
        <template #title>
          <!-- 搜索框 -->
          <van-search v-if="searchShow"
            v-model="searchText"
            :placeholder="placeholder"
            shape="round"
            @update:model-value="onSearch" />
        </template>
        <template #empty>
          <van-empty image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
            image-size="40"
            description="暂无数据" />
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script setup>
const props = defineProps({
  // 控制弹窗显示隐藏
  modelValue: {
    type: Boolean,
    default: false
  },
  // 选择器列数据
  columns: {
    type: Array,
    default: () => []
  },
  // 占位提示文字
  placeholder: {
    type: String,
    default: '请输入搜索内容'
  },
  // 搜索是否显示
  searchShow: {
    type: Boolean,
    default: true
  }
});

// 定义向外触发的事件
const emit = defineEmits(['update:modelValue', 'confirm', 'search']);

// 内部显示状态
const innerShowPicker = ref(props.modelValue);
// 搜索文本
const searchText = ref('');

// 监听 props 变化更新内部状态
watch(() => props.modelValue, (newValue) => {
  innerShowPicker.value = newValue;
});

// 弹窗关闭时触发
const onPopupClose = () => {
  searchText.value = '';
  emit('update:modelValue', false);
};

/**
 * 选择器确认事件处理函数
 * @param values - 选中的值
 * @param indexes - 选中项的索引
 */
const onConfirm = (values) => {
  emit('confirm', values);
  emit('update:modelValue', false);

};

/**
 * 搜索事件处理函数
 * @param values - 搜索的值
 */
const onSearch = (values) => {
  emit('search', values);
}
</script>

<style scoped>
.van-search {
  flex: 1;
}

::v-deep(.van-picker__confirm) {
  width: 70px;
}
</style>