<template>
  <view 
    class="simple-dropdown-box" 
    @click="show=true"
  >
    <picker @change="bindPickerChange" :value="selectedIndex" :range="columns" range-key="name">
      {{ dispayText }} ▼
    </picker>
  </view>
</template>

<script setup lang="ts">
import { computed, ref, type PropType } from 'vue';

export interface SimpleDropDownPickerItem {
  id: number,
  name: string,
}

const props = defineProps({	
  columns: {
    type: Object as PropType<SimpleDropDownPickerItem[]|null>,
    default: null,
  },
  modelValue: {
    type: Number,
    default: null,
  },
  defaultText: {
    type: String,
    default: '请选择',
  },
})

const emit = defineEmits([
  'update:modelValue', 
])

const show = ref(false);
const dispayText = computed(() => {
  if (props.columns)  {
    return props.columns.find(item => item.id == props.modelValue)?.name 
      || props.defaultText;
  }
  return props.defaultText;
});
const selectedIndex = computed(() => {
  let index = -1;
  if (props.columns) 
    index = props.columns.findIndex(item => item.id == props.modelValue);
  return index >= 0 ? index : 0;
});

function bindPickerChange(e:{ detail: { value: number }}) {
  show.value = false;
  emit('update:modelValue', props.columns?.[e.detail.value]?.id ?? null);
}
</script>

<style lang="scss">
.simple-dropdown-box {
  position: relative;
  padding: 16rpx 18rpx;
  border-radius: 30rpx;
  background: #FFFFFF;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>