<template>
  <el-dialog
    title="部门组织架构"
    :visible.sync="dialogVisible"
    v-dialogDrag
    @close="dialogClose(false)"
    class="common-dialog"
    :close-on-click-modal="false"
    append-to-body
  >
  <div class="search">
    <el-input
      placeholder="请输入内容"
      size="small"
      v-model="filterText"
      prefix-icon="el-icon-search"
    />
  </div>
    <div class="content">
      <el-row>
        <el-col :span="12" class="treeContent">
          <div class="tree">
            <el-tree
              :data="data"
              :check-strictly="true"
              show-checkbox
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              :filter-node-method="filterNode"
              @check="nodeCheck"
              @check-change="selectTreeNode"
              ref="tree"
            ></el-tree>
          </div>
        </el-col>
        <el-col :span="12" class="tags">
          <el-tag
            style="margin: 5px"
            v-for="tag in tags"
            :key="tag.id"
            closable
            @close="tagClose(tag)"
          >
            {{ tag.label }}</el-tag
          >
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="warning"@click="dialogClose(true)" size="mini">确 定</el-button>
      <el-button @click="dialogClose(false)" type="info" plain size="mini">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  name: "orgTree",
  props: {
    isOneSelect: Boolean, //是否单选
    initTreeData: Array, //初始化数据，json格式:[{id:null,label:""}]，新增传[]
  },
  data() {
    return {
      userInfo:[],
      dialogVisible: true,
      data: [],
      defaultExpandedKeys: ["0b0a2709-48b7-4d70-8ebb-07d1e9183400"], //默认展开的节点
      filterText: "",
      tags: [],
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getDepartments();
  },
  methods: {
    initData(initTreeData) {
      let defualtCheckeds = [];
      if (initTreeData!=null&&initTreeData.length > 0) {
        initTreeData.forEach((v) => {
          defualtCheckeds.push(v.id);
        });
        this.$refs.tree.setCheckedKeys(defualtCheckeds, true);
        this.defaultExpandedKeys = defualtCheckeds;
        this.tags = initTreeData;
      }
    },
    //查询岗位列表
    getDepartments() {
      this.$ajax.post({
        domain: "crmUrl",
        url: "reportSubmitTending.queryDepartments",
        data: {},
        dataType: "form",
        success: function (res) {
          if (res.errorCode==200) {
            let data = res.data || [];
            this.data = this.handleData(data);
            this.initData(this.initTreeData);
          }
        }.bind(this),
      });
    },
    //关闭tag标签
    tagClose(tag) {
      let tree = this.$refs.tree;
      let tags = [];
      this.tags.forEach((v) => {
        if (v.id !== tag.id) {
          tags.push(v);
        }
      });
      tree.setCheckedNodes(tags);
      this.tags = tags;
    },

    //选中树形节点
    nodeCheck(node) {
      if (!this.isOneSelect) {
        //多选
        let tree = this.$refs.tree;
        let checkNodes = tree.getCheckedNodes();
        let nodes = this.filterChildNodes(checkNodes, node);
        nodes = this.filterParentNodes(nodes, node);
        this.tags = nodes;
        tree.setCheckedNodes(nodes);
      }
    },
    selectTreeNode(node, checked, tree) {
      if (this.isOneSelect) {
        //单选
        let tree = this.$refs.tree;
        if (checked) {
          let nodes = this.filterChildNodes([node], node);
          nodes = this.filterParentNodes(nodes, node);
          this.tags = nodes;
          tree.setCheckedNodes(nodes);
        }
      }
    },
    //递归，取消子节点
    filterChildNodes(selNodes, currentNode) {
      if (currentNode.children.length > 0) {
        currentNode.children.forEach((v) => {
          selNodes.forEach((m, j) => {
            if (m.id === v.id) {
              selNodes.splice(j, 1);
            }
          });
          if (v.children.length > 0) {
            this.filterChildNodes(selNodes, v);
          }
        });
      }
      return selNodes;
    },
    //递归，取消父节点
    filterParentNodes(selNodes, currentNode) {
      selNodes.forEach((v, i) => {
        if (v.id === currentNode.parentDepartmentId) {
          selNodes.splice(i, 1);
        }
      });
      return selNodes;
    },
    //过滤树形节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //整理数据符合树形结构格式
    handleData(json) {
      json = this.JsonSort(json, "layer");
      var ret = [],
        o = {};
      function add(arr, data) {
        var obj = {
          id: data.id,
          deptSuperiorId:data.pathIdOfCache,
          deptSuperiorName:data.pathNameOfCache,
          parentDepartmentId: data.parentDepartmentId,
          label: data.name,
          children: [],
        };
        o[data.id] = obj;
        arr.push(obj);
      }
      json.forEach((x) => {
        if (o[x.parentDepartmentId]) {
          add(o[x.parentDepartmentId].children, x);
        } else {
          add(ret, x);
        }
      });
      return ret;
    },
    /*
    @function JsonSort 对json排序
    @param  json     用来排序的json
    @param  key      排序的键值
 */
    JsonSort(json, key) {
      for (var j = 1, jl = json.length; j < jl; j++) {
        var temp = json[j],
          val = temp[key],
          i = j - 1;
        while (i >= 0 && json[i][key] > val) {
          json[i + 1] = json[i];
          i = i - 1;
        }
        json[i + 1] = temp;
      }
      return json;
    },
    //关闭对话框
    dialogClose(status) {
      this.$emit("close", status ? this.tags : null);
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  border: 1px solid #e9e9e9;
  height: 400px;
  .treeContent {
    border-right: 1px solid #e9e9e9;
    padding: 5px;
    height: 400px;
    .search {
      margin: 5px;
    }
    .tree {
      max-height: 380px;
      overflow-y: auto;
    }
  }
  .tags {
    max-height: 400px;
    overflow-y: auto;
  }
}
/deep/.dialog-footer {
  text-align: center;
}
</style>
