<template>
  <view>
    <picker :value="selectedIndex" :range="options" range-key="dictLabel" @change="onChange">
      <view class="picker">
        {{ selectedLabel || placeholder }}
      </view>
    </picker>
  </view>
</template>

<script>
import { getDicts } from '@/api/oa/dict.js'

export default {
  name: 'DictSelect',
  props: {
    dictType: {
      type: String,
      required: true
    },
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      options: [],
      selectedIndex: -1
    }
  },
  computed: {
    selectedLabel() {
      const item = this.options[this.selectedIndex]
      return item ? item.dictLabel : ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.setSelectedIndex(val)
      }
    },
    dictType: {
      immediate: true,
      handler() {
        this.fetchOptions()
      }
    }
  },
  methods: {
    async fetchOptions() {
      if (!this.dictType) return
      const res = await getDicts(this.dictType)
      this.options = res.data || []
      this.setSelectedIndex(this.value)
    },
    setSelectedIndex(val) {
      const idx = this.options.findIndex(item => item.dictValue == val)
      this.selectedIndex = idx
    },
    onChange(e) {
      const idx = e.detail.value
      this.selectedIndex = idx
      const value = this.options[idx]?.dictValue
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style scoped>
.picker {
  padding: 10rpx 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  background: #fff;
  min-height: 60rpx;
  display: flex;
  align-items: center;
}
</style>
