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

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

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 emit = defineEmits(['change'])

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

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

//获取下拉框设计强度筛选数据
const setTableFormRemoteMethod = async (key, type) => {
 if (type === 'strength_search') {
    console.log(key, 'key')
        await getDesignStrengthListApi(key)//设计强度搜索
        setStoreValue('strengthKeys', key)//存储设计强度值
    }
}

//获取数据源
const selectDatas = ref([])
const getDesignStrengthListApi = async (key) => {
    const datas = selectDatas.value
    if (datas.length > 0) {
        return datas
    } else {
        const { error, code, data } = await getDesignStrengthList({
            contractId: props.contractId,
            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 formRemoteChange = (val) => {
    const datas = selectDatas.value
    const index = arrIndex(datas, 'value', val)
    if (index >= 0) {
        emit('change', getObjValue(datas[index].data))
    }
}
</script>
