<template>
  <div v-loading="loading" :element-loading-background="elementLoadingBackground" style="width: 100%;">
    <el-tree-select
        style="width: 100%;"
        v-bind="$attrs"
        v-model="paramVal"
        :placeholder="$attrs.placeholder ? $attrs.placeholder : `请选择${label}`"
        :data="optionsCpt"
        :clearable="$util.isValue($attrs.clearable) ? $attrs.clearable : true"
        :filterable="$util.isValue($attrs.filterable) ? $attrs.filterable : true"
        :check-strictly="checkStrictly"
        node-key="deptId"
        :props="{
          label: 'deptName',
        }"
        :disabled="$util.isValue($attrs.disabled) ? $attrs.disabled : formView"
    />
  </div>
</template>

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

export default defineComponent({
  name: '',
  components: {},
  props: {
    param: {},
    label: {},
    all: { default: false },
    checkStrictly: { default: true }
  },
  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),
      formView: inject('form-view', false),
    })
    watch(() => state.paramVal, (n: any) => {
      emit('emitParam', n)
      let val = null
      if (n) {
        if (typeof n === 'object' && n?.length > 0) {
          val = n.map(v => store.state.app.deptAllTreeMap.get(v))
        } else {
          val = store.state.app.deptAllTreeMap.get(n)
        }
      }
      emit('getObject', val)
    })
    watch(() => props.param, (n) => {
      state.paramVal = n
    })
    const optionsCpt = computed(() => {
      return props.all === false ? store.state.app.deptTree : store.state.app.deptAllTree
    })
    onMounted(() => {
      Promise.all([
        store.dispatch('app/LOAD_DEPT_TREE'),
        store.dispatch('app/LOAD_DEPT_ALL_TREE')
      ]).then(() => {
        state.loading = false
        emit('emitDefault', optionsCpt.value[0])
      })
    })
    return {
      ...toRefs(state),
      optionsCpt
    }
  },
})
</script>

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