<!--
 * @Author: micky
 * @Date: 2024-08-11 16:47:50
 * @LastEditors: micky
 * @LastEditTime: 2024-10-27 16:18:13
 * @FilePath: \chargingpile-uniapp\src\components\design-picker-field.vue
-->
<template>
    <view class="design-field">
        <text class="field" :class="required ? 'field-required' : ''" :style="labelStyle">
            {{ label }}
        </text>
        <view @click="toggleShow" class="placeholder">
            <text :class="{ light: isSetValue }">
                {{ selectName || placeholder }}
            </text>
            <TIcon name="icon-right" :size="24" color="#7C7E82" />
        </view>
        <root-portal>
            <u-picker
                :show="show"
                :columns="columns"
                :closeOnClickOverlay="true"
                @confirm="confirm"
                :keyName="keyName"
                @cancel="show = false"
                @close="show = false"
                ref="picker"
                :defaultIndex="defaultIndex"
            ></u-picker>
        </root-portal>
    </view>
</template>

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

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    label: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: '请选择'
    },
    columns: {
        type: Array,
        default: () => []
    },
    required: {
        type: Boolean,
        default: true
    },
    keyName: {
        type: String,
        default: 'label'
    },
    disabled: {
        type: Boolean,
        default: false
    },
    labelWidth: {
        type: Number,
        default: 120
    }
})
const picker = ref()
const show = ref(false)
const selectName = ref('')
const emit = defineEmits(['update:modelValue'])
const defaultIndex = ref([0])
const isSetValue = computed(() => selectName.value.length === 0)
const labelStyle = computed(() => {
    const { labelWidth } = props
    return {
        width: `${labelWidth * 2}rpx`
    }
})

const toggleShow = () => {
    if (props.disabled) return
    show.value = true
}

const confirm = ({ value }) => {
    selectName.value = value[0]?.[props.keyName]
    emit('update:modelValue', value[0]?.id)
    show.value = false
}
// 设置当前选中的
const setActive = (id: number) => {
    const column = props.columns[0] as any[]
    const ind = column.findIndex(i => i.id == id) || 0
    defaultIndex.value = [ind]
    selectName.value = column[ind][props.keyName]
}

defineExpose({
    setActive
})
</script>

<style lang="scss" scoped>
.design-field {
    @include flex-align;
    padding: 24rpx 32rpx;
    border-bottom: 1px solid $gray-3;

    .field {
        // width: 240rpx;
    }
    .placeholder {
        flex: 1;
        text-align: right;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .light {
            color: $gray-2;
        }
    }
}
</style>
