<template>
  <view class="dict-select" @click="openPicker">
    <text :class="['select-text', { placeholder: !displayText }]">
      {{ displayText || placeholder }}
    </text>
    <text class="select-arrow">▼</text>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import dictUtil from '../../utils/dict.js'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  type: {
    type: String,
    required: true
  },
  dataRange: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

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

const options = computed(() => {
  if (props.dataRange && props.dataRange.length > 0) {
    return props.dataRange
  }
  return dictUtil.getDictOptions(props.type)
})

const displayText = computed(() => {
  const opt = options.value.find(k => k.value == props.modelValue)
  return opt ? opt.label : ''
})

const openPicker = () => {
  if (props.disabled) return
  if (options.value.length === 0) {
    uni.showToast({ title: '暂无选项', icon: 'none' })
    return
  }

  const range = options.value.map(k => k.label)
  const currentIndex = options.value.findIndex(k => k.value == props.modelValue)

  uni.showActionSheet({
    itemList: range,
    success: (res) => {
      const selected = options.value[res.tapIndex]
      emit('update:modelValue', selected.value)
      emit('change', selected.value)
    }
  })
}
</script>

<style scoped>
.dict-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 20rpx;
  background: #F5F7FA;
  border: 2rpx solid #E8E8E8;
  border-radius: 16rpx;
  font-size: 28rpx;
}
.select-text {
  color: #1A1A1A;
}
.select-text.placeholder {
  color: #CCCCCC;
}
.select-arrow {
  font-size: 20rpx;
  color: #999999;
}
</style>
