<template>
  <div v-loading="loading || isLoading" :element-loading-background="elementLoadingBackground" style="width: 100%;">
    <el-select
        style="width: 100%;"
        v-bind="$attrs"
        v-model="paramVal"
        :placeholder="$attrs.placeholder ? $attrs.placeholder : `请选择`"
        clearable
        filterable
        @change="handleChange"
        :popper-append-to-body="false"
        :title="optionsMapCpt.get(paramVal)?.[labelKey]"
    >
      <slot v-if="$slots.default">
        <el-option
            v-for="item in options"
            :key="item[valueKey]"
            :label="item[labelKey]"
            :value="item[valueKey]"
            :title="item[labelKey]"
        />
      </slot>
    </el-select>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick, onBeforeMount, inject
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'

export default defineComponent({
  name: '',
  components: {},
  props: {
    param: {},
    label: {},
    options: { type: Array, default: () => [] },
    labelKey: { type: String, default: 'dictLabel' },
    valueKey: { type: String, default: 'dictValue' },
    static: { default: false },
    isLoading: { default: false }
  },
  setup(props, { emit }) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({
      paramVal: props.param,
      loading: true,
      elementLoadingBackground: inject('element-loading-background', null)
    })
    watch(() => state.paramVal, (n) => {
      emit('emitParam', n)
    })
    watch(() => props.param, (n) => {
      state.paramVal = n
    })
    watch(() => [props.options, props.static], () => {
      state.loading = false
    })
    const optionsMapCpt = computed(() => {
      const map = new Map()
      props.options?.forEach((v: any) => {
        map.set(v[props.valueKey], v)
      })
      return map
    })
    const handleChange = (val: any) => {
      emit('getObject', optionsMapCpt.value.get(val))
    }
    onMounted(() => {
      if (props.static !== false || props.options?.length > 0) {
        state.loading = false
      }
    })
    return {
      ...toRefs(state),
      handleChange,
      optionsMapCpt
    }
  },
})
</script>

<style scoped lang="scss">
</style>
