<template>
  <el-select ref="select" :value="modelValue"
             v-bind="selectProps"
             @change="onChange"
             @visible-change="onVisibleChange">
    <el-tree ref="tree"
             v-bind="treeProps"
             @check="onCheck"
             @node-click.self="onNodeClick">
    </el-tree>
  </el-select>
</template>

<script>
import {SelectProps, TreeProps} from "./Props"
import treeMixins               from "./mixins/tree-mixins";
import selectMixins             from "./mixins/select-mixins";
import * as utils               from "./hooks/utils";
import _                        from "lodash"

export default {
  name: "EdTreeSelect",
  mixins: [treeMixins, selectMixins],
  model: {
    prop: "modelValue",
    event: "input"
  },
  props: {
    ...SelectProps,
    ...TreeProps,
    /**
     * @description The cached data of the lazy node, the structure is the same as the data, used to get the label of the unloaded data
     */
    cacheData: {
      type: Array,
      default: () => [],
    }
  },
  watch: {
    modelValue: {
      handler(nVal, oVal) {
        if (nVal) {
          this.$nextTick(() => {
            const treeInstance = this.$refs.tree
            if (this.showCheckbox) {
              if (treeInstance && !_.isEqual(treeInstance.getCheckedKeys(), utils.toValidArray(this.modelValue))) {
                treeInstance.setCheckedKeys(utils.toValidArray(this.modelValue))
              }
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    dataKey() {
      return this.nodeKey || this.valueKey || 'value'
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-select-dropdown__item {
    padding: 0;
    height: 24px;
    line-height: 24px;
  }
}
</style>
