<template>
    <div class="el-form-item--col">
        <el-select ref="selectRef" v-model="selectedValue" :empty-values="[null, undefined, 0]" :loading="loading"
            :placeholder="placeholder" :remote-method="remoteMethod" @change="onChange" remote filterable clearable>
            <el-option v-for="item in dataList" :key="item.accountid" :label="item.accountid" :value="item.accountid">
                <div style="display: flex;justify-content: space-between;">
                    <span>{{ item.accountid }}</span>
                    <span>{{ item.relatedname }}</span>
                </div>
            </el-option>
        </el-select>
        <el-button icon="Plus" link @click="onPlus" />
    </div>
</template>

<script lang="ts" setup>
import { shallowRef, computed, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { useRequest } from '@/hooks/request'
import { queryTAAccountChildrenSelect } from '@/services/api/report'

const props = defineProps({
    modelValue: [Number, String],
    placeholder: {
        type: String,
        default: '请输入'
    }
})

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

const selectRef = shallowRef()

const selectedValue = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const { dataList, loading, runAsync } = useRequest(queryTAAccountChildrenSelect, {
    manual: true
})

const onPlus = () => {
    if (!loading.value) {
        loading.value = true
        runAsync().then((res) => {
            if (res.data.length) {
                selectRef.value.toggleMenu()
            } else {
                ElMessage.warning('暂无数据')
            }
        }).catch((err) => {
            ElMessage.error(err)
        }).finally(() => {
            loading.value = false
        })
    }
}

const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        runAsync({
            searchcode: query
        }).finally(() => {
            loading.value = false
        })
    }
}

const onChange = (id?: number) => {
    const item = dataList.value.find((e) => e.accountid === id)
    dataList.value = []
    emit('change', toRaw(item))
}
</script>