<template>
    <div style="width: 100%" v-if="data.updateMultiple">
        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
            <el-select v-model="data.modelValue" clearable filterable @change="changeModelValue"
                       remote :remote-method="remoteMethod" :reserve-keyword="false"
                       :multiple="props.multiple" :disabled="props.disabled">
                <el-option v-for="(item, index) in dicData.users" :key="index" :label="item.name"
                           :value="item.userId"></el-option>
            </el-select>
        </el-tooltip>
    </div>
</template>

<script setup lang="ts" name="UserRolePickerIndex">
    // 定义字典
    import {onFormLoadedUrl, onLoadDicUrl, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    import {validateNull} from "/@/utils/validate";
    import {handlePrintValue} from "/@/flow/components/form-create";

    const props = defineProps({
        formCreateInject: {
            type: Object,
            default: {},
        },
        modelValue: {
            type: [Number, String, Array],
            default: null,
        },
        multiple: {
            type: Boolean,
            default: false,
        },
        disabled: {
            type: Boolean,
            default: false,
        },
    });

    const emits = defineEmits(['update:modelValue']);

    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "users", field: "modelValue"});
    onMounted(async () => {
        data.modelValue = props.modelValue
        await onFormLoaded(dicData, data);
        changePrintValue()
    });

    const data = reactive({
        modelValue: null,
        updateMultiple: true
    })

    function remoteMethod(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "users")
    }

    // 注入打印设计的内容，该逻辑非必须
    const changePrintValue = () => {
        if (!validateNull(data.modelValue)) {
            let printValue = handlePrintValue(dicData.users, data.modelValue, 'userId', 'name');
            if (printValue) props.formCreateInject.printValue = printValue
            else props.formCreateInject.printValue = ""
        } else {
            props.formCreateInject.printValue = ""
        }
    }

    const changeModelValue = (value) => {
        data.modelValue = value
        emits('update:modelValue', value);
        changePrintValue()
    }

    // 监听双向绑定
    watch(
        () => props.multiple,
        (val) => {
            data.updateMultiple = false
            changeModelValue(null)
            setTimeout(()=>{
                // 防止切换时报错
                data.updateMultiple = true
            })
        }
    );

</script>
