<template>
    <el-select :id="keyname" v-model="selectVal" :keyname="keyname" :placeholder="placeholder" clearable filterable
               @change="formRemoteChange">
        <el-option v-for="item in selectDatas" :label="item.label" :value="item.value"/>
    </el-select>
</template>

<script setup>
import {nextTick, ref} from 'vue'
import {getDapSiteData} from "~api/other"
import {ElSelect, ElOption} from 'z-element-plus'
import {getObjValue, getObjVal, arrIndex} from "js-fast-way"

const props = defineProps({
    val: {
        type: [Number, String],
        default: ''
    },
    type: {
        type: [Number, String],
        default: ''
    },
    keyname: {
        type: [Number, String],
        default: ''
    },
    placeholder: {
        type: [Number, String],
        default: '搜索'
    },
    contractId: {
        type: [Number, String],
        default: ''
    },
    pkeyId: {
        type: [Number, String],
        default: ''
    },
})

//变量
const selectVal = ref(props.val)

//加载完成
nextTick(() => {
    if (props.keyname && props.type) {
        setTableFormRemoteMethod(props.keyname, props.type)
    }
})

//获取下拉框测站点筛选数据
const setTableFormRemoteMethod = async (key, type) => {
    if (type === 'dap_site_data') {
        await getDapSiteDataApi(key)
    }
}

//获取数据源
const selectDatas = ref([])
const getDapSiteDataApi = async (key) => {
    const datas = selectDatas.value
    if (datas.length > 0) {
        return datas
    } else {
        const {error, code, data} = await getDapSiteData({
            contractId: props.contractId,
            pkId: props.pkeyId,
            key: key
        }, false)
        //处理数据
        const resData = getObjVal(data)
        if (!error && code === 200 && resData) {
            selectDatas.value = await objToArr(resData, key)
        } else {
            selectDatas.value = []
        }
    }
}

//对象转数组
const objToArr = async (obj) => {
    let newArr = [];
    Object.keys(obj).forEach(key => {
        newArr.push({
            label: key,
            value: key,
            data: {
                ...obj[key]
            }
        })
    })
    return newArr
}

//事件
const emit = defineEmits(['change'])

//当前被选中的事件
const formRemoteChange = (val) => {
    const datas = selectDatas.value
    const index = arrIndex(datas, 'value', val)
    if (index >= 0) {
        emit('change', getObjValue(datas[index].data))
    }
}
</script>
