<template>
  <!-- <el-form-item label="归属机构" class="tree-select" prop="deptTree" :rules="rules"> -->
  <div class="tree-select-border">
    <el-input size="mini" v-model="filterText" clearable placeholder="请输入关键字进行过滤"></el-input>
    <el-tree
      :data="deptOptions"
      :filter-node-method="filterNode"
      show-checkbox
      :check-strictly="false"
      ref="deptTree"
      node-key="id"
      empty-text="加载中，请稍候"
      :default-checked-keys="defaultCheckedKeys"
      :default-expanded-keys="defaultCheckedKeys"
      :props="defaultDeptProps"
      @check-change="handleCheckChange"
    >
    </el-tree>
  </div>
  <!-- </el-form-item> -->
</template>

<script>
import { getDeptTree } from '@/api/grid/address/tree.js'
export default {
  props: {
    defaultCheckedKeys: {
      type: Array,
      default: []
    },
    tagIndex: {
      type: Number,
      default: 0
    }
  },
  watch: {
    filterText(val) {
      this.$refs.deptTree.filter(val)
    }
  },
  data() {
    return {
      defaultDeptProps: {
        children: 'children',
        label: 'label',
        disabled: (data) => !['head', 'branch', 'outlet'].includes(data.level)
      },
      deptOptions: [],
      filterText: '',
      rules: [
        {
          validator: (rule, value, callback) => {
            const checkedKeys = this.$refs.deptTree.getCheckedKeys()
            if (checkedKeys.length === 0) {
              callback(new Error('机构不能为空'))
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }
      ]
    }
  },
  created() {
    this.getDeptTreeSelect()
  },
  methods: {
    handleCheckChange(obj, has, node) {
      this.$emit('onTreeChange', {
        checkedKeys: this.$refs.deptTree.getCheckedKeys(),
        tagIndex: this.tagIndex
      })
    },
    orgValidator() {},
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        this.deptOptions = response.data
      })
    },
    filterNode(value, data) {
      console.log(value, data, '=======')
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getCheckedKeys() {
      return this.$refs.deptTree.getCheckedKeys()
    }
  }
}
</script>

<style lang="scss" scoped>
@import './../../created/component/create-style.scss';
</style>