<template>
    <picker mode="selector" :range="getRange" @change="onChange" :disabled="disabled" :value="getPickerValue">
        <view class="picker placeholder" :class="{ placeholder: !!getVal }">
            <text>{{ getVal }}</text>
            <uni-icons type="right" size="18" color="#86909C"></uni-icons>
        </view>
    </picker>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import * as dictData from './dictData'
import { cloneDeep } from 'lodash'

const es = defineEmits(['update:modelValue', 'change'])
const ps = defineProps({
    dictkey: {
        type: String,
        default: ''
    },
    modelValue: {
        type: [String, Number],
        default: ''
    },
    options: {
        type: Array,
        default: () => []
    },
    labelField: {
        type: String,
        default: 'label'
    },
    valueField: {
        type: String,
        default: 'value'
    },
    placeholder: {
        type: String,
        default: '请选择'
    },
    disabled: {
        type: Boolean,
        default: false
    }
})
const selectedValue = ref()
//获取options
const getOptions = computed(() => {
    if (ps.dictkey) {
        return cloneDeep(dictData[ps.dictkey])
    } else {
        return ps.options
    }
})
const getRange = computed(() => {
    return getOptions.value.map((option) => option[ps.labelField])
})
const onChange = (event) => {
    const index = event.detail.value
    selectedValue.value = getOptions.value[index][ps.labelField]
    es('update:modelValue', getOptions.value[index][ps.valueField])
    es('change', getOptions.value[index][ps.valueField])
}
const getVal = computed(() => {
    return selectedValue.value || ps.placeholder
})
//获取初始值
const init = () => {
    const option = getOptions.value.find((option) => String(option[ps.valueField]) === String(ps.modelValue))
    if (option) {
        selectedValue.value = option[ps.labelField]
    }
}
const getPickerValue = computed(() => {
    const index = getOptions.value.findIndex((option) => String(option[ps.valueField]) === String(ps.modelValue))
    return index > 0 ? index : 0
})
onMounted(() => {
    init()
})
</script>
<style lang="scss" scoped>
.picker {
    display: flex;
    align-items: center;
    &.placeholder {
        color: #86909c;
    }
    uni-icons {
        margin-top: 6rpx;
    }
}
</style>
