<template>
  <div class="dept-select">
    <el-cascader
      ref="cascader"
      :value="value"
      :options="treeItems"
      :props="created"
      :size="size"
      @change="handleChange"
      @visible-change="handleVisibleChange"
      :placeholder="placeholder"
      clearable
    ></el-cascader>
  </div>
</template>

<script>
export default {
  name: 'dept-select',
  props: {
    props: Object,
    size: { type: String, default: 'small' },
    navItems: Array,
    dataItems: Array,
    value: { required: false },
    placeholder: { type: String, default: '请选择用户部门' },
  },
  data() {
    return {
      cascaderProps: {
        multiple: false,
        checkStrictly: true,
        emitPath: false,
        children: 'children',
        label: 'name',
        value: 'id',
      },
      selectedValue: this.value,
      panelVisible: false,
    };
  },
  computed: {
    treeItems() {
      if (this.navItems) return this.navItems;
      const items = this.dataItems || [];
      const root = items.filter(a => !items.some(b => b.id === a.pid));
      const fetchChildren = item => {
        if (!item.path) item.path = [item.name];
        const children = items.filter(p => p.pid === item.id).map(p => fetchChildren({ ...p, parent: item, path: item.path.concat(p.name) }));
        if (children && children.length > 0) return { ...item, children };
        return { ...item, leaf: true };
      };
      return root.map(p => fetchChildren(p));
    },
    created() {
      const cascaderProps = { ...this.cascaderProps, ...(this.props || {}) };
      return cascaderProps;
    },
  },
  methods: {
    handleChange(payload) {
      this.selectedValue = payload;
      this.$emit('input', payload);
      this.$emit('change', payload);
      if (!this.panelVisible) {
        this.$emit('select', this.selectedValue);
      }
    },
    handleVisibleChange(visible) {
      this.panelVisible = visible;
      if (visible === false) {
        this.$emit('select', this.selectedValue);
      }
    },
    toggleDropDownVisible(visible) {
      this.$refs.cascader.toggleDropDownVisible(visible);
    },
  },
};
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
