<template>
  <div class="dialog-container">
    <el-dialog
      :visible.sync="visible"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      :show-close="false"
      custom-class="custom-dialog"
      title="接收单位"
    >
      <el-input v-model="treeFilter" placeholder="输入关键字进行过滤" />
      <el-tree
        ref="tree"
        class="filter-tree"
        :data="treeData"
        :props="treeProps"
        :node-key="nodeKey"
        :default-expanded-keys="defaultExpandedKeys"
        show-checkbox
        :expand-on-click-node="false"
        check-strictly
        check-on-click-node
        :filter-node-method="filterNode"
      />
      <div slot="footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isNull } from '@/utils/convert'

export default {
  name: 'EmbeddedTree',
  props: {
    checkedKeys: {
      type: Array,
      default() {
        return []
      }
    },
    treeData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      visible: false,
      // tree
      treeProps: {
        children: 'children',
        label: 'shortName'
      },
      treeFilter: '',
      nodeKey: 'orgCode',
      defaultExpandedKeys: [],
      // others
      loading: false
    }
  },
  watch: {
    treeFilter(val) {
      this.$refs['tree'].filter(val)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data[this.treeProps.label].indexOf(value) !== -1
    },
    open() {
      this.visible = true
      if (!isNull(this.treeData)) {
        this.defaultExpandedKeys = [this.treeData[0][this.nodeKey]]
      }
      if (!isNull(this.checkedKeys)) {
        this.$refs['tree'].setCheckedKeys(this.checkedKeys)
      }
    },
    save() {
      const checkedNodes = this.$refs['tree'].getCheckedNodes()
      if (!isNull(checkedNodes)) {
        this.$emit('updateValue', checkedNodes)
        this.visible = false
      } else {
        this.$message({
          type: 'warning',
          message: '请选择接收单位!'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-container {
  ::v-deep {
    .custom-dialog {
      width: 500px !important;
    }
  }
}
</style>
