<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 : `请选择${label}`"
        :clearable="$util.isValue($attrs.clearable) ? $attrs.clearable : true"
        :filterable="$util.isValue($attrs.filterable) ? $attrs.filterable : true"
        @change="handleChange"
        :popper-append-to-body="false"
        :title="optionsMapCpt.get(paramVal)?.[labelKey]"
        :disabled="$util.isValue($attrs.disabled) ? $attrs.disabled : formView"
    >
      <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 attrs = (getCurrentInstance() as ComponentInternalInstance).attrs
    const state = reactive({
      paramVal: props.param,
      loading: true,
      elementLoadingBackground: inject('element-loading-background', null),
      formView: inject('form-view', false),
    })
    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', attrs.multiple === undefined ? optionsMapCpt.value.get(val) : val.map(v => optionsMapCpt.value.get(v)))
    }
    onMounted(() => {
      if (props.static !== false || props.options?.length > 0) {
        state.loading = false
      }
    })
    return {
      ...toRefs(state),
      handleChange,
      optionsMapCpt
    }
  },
})
</script>

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