<template>
  <div>
    <el-popover
      popper-class="selectTree"
      v-clickoutside="replyOutside"
      placement="bottom-start"
      :width="popoverWidth"
      trigger="manual"
      v-model="isShowSelect"
      @hide="popoverHide"
    >
      <div class="pdlr_1">
        <el-input
          class="mb_5"
          v-if="filterable"
          v-model="filterText"
          placeholder="鎼滅储"
        ></el-input>
      </div>

      <el-tree
        class="common-tree"
        :indent="multiple ? 10 : 10"
        :width="width"
        ref="tree"
        :data="treeData"
        :props="obj"
        :filter-node-method="filterNode"
        :show-checkbox="multiple"
        :node-key="obj.id"
        :check-strictly="checkStrictly"
        :default-expanded-keys="defaultKey"
        :default-expand-all="defaulexpand"
        :expand-on-click-node="multiple && expandClickNode"
        :check-on-click-node="checkClickNode"
        :highlight-current="true"
        @check-change="nodeClick"
        @node-click="nodeClick"
      ></el-tree>

      <el-select
        slot="reference"
        ref="select"
        :size="size"
        v-model="returnDataKeys"
        :multiple="multiple"
        :clearable="clearable"
        :collapse-tags="collapseTags"
        @click.native="selectClick"
        @remove-tag="removeTag"
        @clear="clean"
        class="tree-select"
        :placeholder="placeholder"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <div class="mt_5" v-if="selectAll">
        <el-checkbox
          v-model="checkedAll"
          :indeterminate="returnDataKeys.length == 0 ? false : !checkedAll"
          @change="selectedAll"
          >鍏ㄩ€�</el-checkbox
        >
      </div>
    </el-popover>
  </div>
</template>

<script>
//鐐瑰嚮澶栭儴鍏抽棴涓嬫媺妗�
import Clickoutside from "element-ui/src/utils/clickoutside";
import { StaffDepartmentListApi } from "@/api/staffApi.js";
export default {
  directives: { Clickoutside },
  props: {
    //鍏ㄩ€�
    selectAll: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 鏍戠粨鏋勬暟鎹�
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    obj: {
      type: Object,
      required: false,
      default: () => {
        return {
          id: "", // id
          label: "", // 鏄剧ず鍚嶇О
          children: "", //瀛愮骇瀛楁鍚�
        };
      },
    },
    //閰嶇疆鏄惁鍙互鎼滅储
    filterable: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //杈撳叆妗嗗崰浣嶅€�
    placeholder: {
      type: String,
      default() {
        return "璇烽€夋嫨";
      },
    },
    //閰嶇疆鏄惁鍙閫�
    multiple: {
      type: Boolean,
      default() {
        return false;
      },
    },
    renderAfterExpand: {
      type: Boolean,
      default() {
        return true;
      },
    },
    // 閰嶇疆鏄惁鍙竻绌洪€夋嫨
    clearable: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 閰嶇疆澶氶€夋椂鏄惁灏嗛€変腑鍊兼寜鏂囧瓧鐨勫舰寮忓睍绀�
    collapseTags: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 鏄剧ず澶嶉€夋鎯呭喌涓嬶紝鏄惁涓ユ牸閬靛惊鐖跺瓙涓嶄簰鐩稿叧鑱�
    checkStrictly: {
      type: Boolean,
      default() {
        return false;
      },
    },
    radioStrictly: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //澶氶€夋槸璁剧疆鐐瑰嚮鑺傜偣鏄惁鍙互閫変腑
    checkClickNode: {
      type: Boolean,
      default() {
        return true;
      },
    },
    //澶氶€夋椂锛氱偣鍑昏妭鐐瑰睍寮€杩樻槸鐐逛笁瑙掓爣
    expandClickNode: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //榛樿灞曞紑
    defaulexpand: {
      type: Boolean,
      default() {
        return true;
      },
    },
    // 榛樿閫変腑鐨勮妭鐐筴ey
    defaultKey: {
      type: [Number, String, Array, Object],
      default() {
        return [];
      },
    },
    size: {
      type: String,
      default() {
        return "small";
      },
    },
    width: {
      type: String,
      default() {
        return "100%";
      },
    },
    height: {
      type: String,
      default() {
        return "300px";
      },
    },
    curValue: {
      default() {
        return "";
      },
    },
    notParentcheckStrictlyChildcheckStrictly: {
      //瀛愰€変腑锛屽瓩璺熺潃閫変腑锛屼絾鐖朵笉閫変腑--銆�1浠h〃鐢ㄦ鏂规锛�0浠h〃涓嶇敤姝ゆ柟妗�
      default() {
        return 0;
      },
    },
  },

  //涓婇潰鏄埗缁勪欢鍙紶鍏ュ弬鏁�
  data() {
    return {
      popoverWidth: "0px", //涓嬫媺妗嗗ぇ灏�
      isShowSelect: false, // 鏄惁鏄剧ず鏍戠姸閫夋嫨鍣�
      options: [], //select option閫夐」
      returnDatas: [], //杩斿洖缁欑埗缁勪欢鏁扮粍瀵硅薄
      returnDataKeys: [], //杩斿洖鐖剁粍浠舵暟缁勪富閿€�
      filterText: "", //绛涢€夌粦瀹氬€�
      checkedAll: false, //鏄惁鏈夊叏閫夋寜閽�(鍙湁鍦ㄥ閫変笅鎵嶈兘閰嶇疆)
      treeArrId: [],
      DepartDataArr: [],
    };
  },

  mounted() {
    // var that = this; //this鐨勬寚鍚戦棶棰�
    // document.addEventListener("click", function (e) {
    //   console.log(e);
    //   that.isShowSelect = false; //杩欓噷that浠h〃缁勪欢锛宼his浠h〃document
    // });
    this.$nextTick(() => {
      if (this.curValue) {
        if (
          typeof this.curValue != "string" &&
          typeof this.curValue != "number"
        ) {
          this.setKeys(this.curValue);
        } else {
          this.setKey(this.curValue);
        }
      }
    });
  },

  computed: {
    treeData() {
      // 鑻ラ潪鏍戠姸缁撴瀯锛屽垯杞寲涓烘爲鐘剁粨鏋勬暟鎹�
      if (this.obj.children != "") {
        // return JSON.stringify(this.data).indexOf(this.obj.children) !== -1
        //   ? this.data
        //   : this.switchTree();
        return this.data;
      } else {
        return this.data;
      }
    },
  },
  watch: {
    returnDataKeys(newValue, oldValue) {
      if (newValue.length === this.treeArrId.length) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    },
    curValue(val) {
      //寮曠敤缁勪欢閲岀殑:curValue="defaulData" 灞炴€у氨鏄綋鍓嶅睍绀哄嬀閫夌殑鏁版嵁Id銆傚洖鏄炬暟鎹椂缁欒繖涓睘鎬ц祴鍊煎氨琛屼簡
      this.$nextTick(() => {
        if (val) {
          if (typeof val != "string" && typeof val != "number") {
            this.setKeys(val);
          } else {
            this.setKey(val);
          }
        }
      });
    },

    filterText(val) {
      this.$refs.tree.filter(val);
    },
    // eslint-disable-next-line no-unused-vars
    isShowSelect(val) {
      // 闅愯棌select鑷甫鐨勪笅鎷夋
      this.$refs.select.blur();
    },
    treeData() {
      //鐩戝惉tree鏁版嵁
      this.$nextTick(() => {
        this.init();
      });
    },
  },
  created() {
    this.treeArrId = [];
    this.originTree(this.treeData);
  },
  methods: {
    originTree(treeData) {
      treeData.forEach((item) => {
        this.treeArrId.push(item[this.obj.id]);
        if (item.children && item.children.length > 0) {
          this.originTree(item.children);
        }
      });
    },
    // 鐐瑰嚮澶栭儴鍏抽棴
    replyOutside(v) {
      let e = v || window.event;
      let elem = e.target;
      if (
        e.target.parentNode.querySelector(".selectTree *") ||
        e.target.parentNode.querySelector(".selectTree")
      ) {
        //querySelector() 鏂规硶杩斿洖鏂囨。涓尮閰嶆寚瀹� CSS 閫夋嫨鍣ㄧ殑涓€涓厓绱�
        return;
      } else if (this.isShowSelect) {
        this.isShowSelect = false;
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.obj.label].indexOf(value) !== -1;
    },

    init() {
      // debugger
      if (this.defaultKey != undefined && this.defaultKey.length > 0) {
        if (this.multiple) {
          // 澶氶€�
          if (
            Object.prototype.toString.call(this.defaultKey).indexOf("Array") !=
            -1
          ) {
            if (
              Object.prototype.toString
                .call(this.defaultKey[0])
                .indexOf("Object") != -1
            ) {
              //瀵硅薄
              this.setDatas(this.defaultKey);
            } else if (
              Object.prototype.toString
                .call(this.defaultKey[0])
                .indexOf("Number") != -1 ||
              Object.prototype.toString
                .call(this.defaultKey[0])
                .indexOf("String") != -1
            ) {
              this.setKeys(this.defaultKey);
            } else {
              console.log("澶氶€夛細浼犲叆鍙傛暟绫诲瀷涓嶅尮閰�");
              return;
            }
          } else {
            console.log("澶氶€夛細浼犲叆鍙傛暟绫诲瀷涓嶅尮閰�");
            return;
          }
        } else {
          // 鍗曢€�
          if (
            Object.prototype.toString.call(this.defaultKey).indexOf("Number") !=
              -1 ||
            Object.prototype.toString.call(this.defaultKey).indexOf("String") !=
              -1 ||
            Object.prototype.toString.call(this.defaultKey).indexOf("Object") !=
              -1
          ) {
            this.setKey(this.defaultKey);
          } else {
            console.log("鍗曢€夛細浼犲叆鍙傛暟绫诲瀷涓嶅尮閰�");
            return;
          }
        }
      }
    },
    //涓嬫媺妗唖elect鐐瑰嚮[鍏ュ彛]
    selectClick() {
      this.DepartPoptableDatalist(); //鐐瑰嚮閫夋嫨妗嗘煡璇㈤儴闂ㄥ垪琛�
      this.$nextTick(function () {
        //璁剧疆涓嬫媺妗嗚嚜閫傚簲瀹藉害
        this.popoverWidth = this.$refs.select.$el.clientWidth;
      });
      //鏄剧ず涓嬫媺妗�
      return (this.isShowSelect = !this.isShowSelect);
    },
    DepartPoptableDatalist() {
      if(this.data && this.data.length){
        this.DepartDataArr = this.data;
        this.$emit("selectClickT", this.DepartDataArr);
        this.sortTableData(this.DepartDataArr);
      }else{
        //鐐瑰嚮閫夋嫨妗嗘煡璇㈤儴闂ㄥ垪琛�
        let obj = { domainId: this.$route.query.domainId }; //鑾峰彇url鍩焏omainId
        StaffDepartmentListApi(obj).then((response) => {
          if (response.data) {
            this.DepartDataArr = response.data;
            this.$emit("selectClickT", this.DepartDataArr);
            this.sortTableData(this.DepartDataArr);
          }
        });
      }
    },
    sortTableData(arr) {
      //閫掑綊鎺掑簭
      if (arr?.length) {
        arr.forEach((item) => {
          item.displayOrderNumber = item.displayOrder;
          if (item.children?.length) {
            this.sortTableData(item.children);
          }
        });
      }
      console.log(this.tableData);
    },
    //鍗曢€�: 鏍戠偣鍑绘柟娉�
    nodeClick(data, node) {
      //data涓簅bj褰撳墠閮ㄩ棬鏁版嵁浠ュ強children鏁版嵁锛宯ode涓篵oolean鍊硷紝閫変腑涓簍rue锛屽彇娑堜负false
      //  debugger
      if (!this.multiple) {
        this.isShowSelect = false;
        //鍗曢€夌埗瀛愯妭鐐逛笉鍏宠仈
        if (this.radioStrictly) {
          this.setKey(node.key);
        } else {
          //   if (node.level != 1) {
          //     this.setKey(node.key);
          //   } else if (node.level == 1 && this.obj.children == "") {
          //     this.setKey(node.key);
          //   }
          if (node.level) {
            this.setKey(node.key);
          }
        }
      } else {
        //澶氶€�
        debugger;
        //鏂板鍔犲閫夋鐨勬柟妗�--//瀛愰€変腑锛屽瓩璺熺潃閫変腑锛屼絾鐖朵笉閫変腑--銆媙otParentcheckStrictlyChildcheckStrictly:1浠h〃鐢ㄦ鏂规锛�0浠h〃涓嶇敤姝ゆ柟妗�
        if (this.notParentcheckStrictlyChildcheckStrictly == 1) {
          //瀛愰€変腑--瀛欏瓩璺熺潃閫変腑锛屼絾鐖朵笉閫変腑
          Array.isArray(data.children) &&
            data.children.forEach((item) => {
              this.$refs.tree.setChecked(item, node);
              if (node) {
                //濡傛灉node涓簍rue閫変腑
                this.$set(item, "disabled", true);
              } else {
                //鍚﹀垯涓嶉€変腑
                this.$set(item, "disabled", false);
              }
              this.nodeClick(item, node); //閫掑綊寰幆閬嶅巻children
            });
        }

        var checkedKeys = this.$refs.tree.getCheckedKeys(); // 鎵€鏈夎閫変腑鐨勮妭鐐圭殑 key 鎵€缁勬垚鐨勬暟缁勬暟鎹�

        checkedKeys = checkedKeys.filter(function (s) {
          if (typeof s == "String") {
            return s && s.trim();
          } else {
            return s;
          }
        });
        var t = [];
        checkedKeys = this.unique(checkedKeys);
        this.options = checkedKeys.map((item) => {
          if (item !== undefined) {
            var node = this.$refs.tree.getNode(item); // 鎵€鏈夎閫変腑鐨勮妭鐐瑰搴旂殑node
            t.push(node.data);
          }
          //璁剧疆option閫夐」
          return { label: node.label, value: node.key };
        });

        this.returnDataKeys = this.options.map((item) => {
          return item.value;
        });
        this.returnDatas = t;
        this.popoverHide();
      }
    },
    unique(arr) {
      //鍘婚噸
      return arr.filter(function (item, index, arr) {
        return arr.indexOf(item, 0) === index;
      });
    },
    //鍗曢€�:娓呯┖閫変腑
    clean() {
      this.$refs.tree.setCurrentKey(null); //娓呴櫎鏍戦€変腑key
      this.returnDatas = null;
      this.returnDataKeys = "";
      this.popoverHide();
    },
    //鍗曢€�:璁剧疆銆佸垵濮嬪寲鍊� key
    setKey(thisKey) {
      this.$refs.tree.setCurrentKey(thisKey);
      var node = this.$refs.tree.getNode(thisKey);
      if (node) {
        this.setData(node.data);
      }
    },
    //鍗曢€夛細璁剧疆銆佸垵濮嬪寲瀵硅薄
    setData(data) {
      this.options = [];
      this.options.push({
        label: data[this.obj.label],
        value: data[this.obj.id],
      });
      this.returnDatas = data;
      this.returnDataKeys = data[this.obj.id];
    },
    //澶氶€�:璁剧疆銆佸垵濮嬪寲鍊� keys
    setKeys(thisKeys) {
      // debugger
      this.$refs.tree.setCheckedKeys(thisKeys);
      this.returnDataKeys = thisKeys;
      var t = [];
      thisKeys.map((item) => {
        //璁剧疆option閫夐」
        var node = this.$refs.tree.getNode(item); // 鎵€鏈夎閫変腑鐨勮妭鐐瑰搴旂殑node
        t.push(node.data);
        return { label: node.label, value: node.key };
      });
      this.returnDatas = t;
      this.popoverHide();
    },
    //澶氶€�:璁剧疆銆佸垵濮嬪寲瀵硅薄
    setDatas(data) {
      this.$refs.tree.setCheckedNodes(data);
      this.returnDatas = data;
      var t = [];
      data.map((item) => {
        //璁剧疆option閫夐」
        t.push(item[this.obj.id]);
      });
      this.returnDataKeys = t;
      this.popoverHide();
    },
    // 澶氶€�,鍒犻櫎浠讳竴select閫夐」鐨勫洖璋�
    removeTag(val) {
      this.$refs.tree.setChecked(val, false); //璁剧疆涓烘湭閫変腑
      var node = this.$refs.tree.getNode(val); //鑾峰彇鑺傜偣
      if (!this.checkStrictly && node.childNodes.length > 0) {
        this.treeToList(node).map((item) => {
          if (item.childNodes.length <= 0) {
            this.$refs.tree.setChecked(item, false);
          }
        });
      }
      this.nodeClick();
      this.popoverHide();
    },
    //涓嬫媺妗嗗叧闂墽琛�
    popoverHide() {
      this.$emit("getValue", this.returnDataKeys, this.returnDatas);
    },
    // 澶氶€夛紝娓呯┖鎵€鏈夊嬀閫�
    clearSelectedNodes() {
      var checkedKeys = this.$refs.tree.getCheckedKeys(); // 鎵€鏈夎閫変腑鐨勮妭鐐圭殑 key 鎵€缁勬垚鐨勬暟缁勬暟鎹�
      for (let i = 0; i < checkedKeys.length; i++) {
        this.$refs.tree.setChecked(checkedKeys[i], false);
      }
    },
    //澶氶€�  鍏ㄩ€�
    selectedAll(val) {
      if (val) {
        this.setKeys(this.treeArrId);
      } else {
        this.clearSelectedNodes();
      }
    },
    //鏍戝舰杞负闆嗗悎
    treeToList(tree) {
      var queen = [];
      var out = [];
      queen = queen.concat(tree);
      while (queen.length) {
        var first = queen.shift();
        if (first.childNodes) {
          queen = queen.concat(first.childNodes);
        }
        out.push(first);
      }
      return out;
    },
    switchTree() {
      return this.buildTree(this.data, this.defaultValue);
    },
    // 灏嗕竴缁寸殑鎵佸钩鏁扮粍杞崲涓哄灞傜骇瀵硅薄
    buildTree(data, id) {
      const fa = (id) => {
        const temp = [];
        for (let i = 0; i < data.length; i++) {
          const n = data[i];
          if (n[this.obj.pid] === id) {
            n[this.obj.children] = fa(n[this.obj.id]);
            temp.push(n);
          }
        }
        return temp;
      };
      return fa(id);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.common-tree {
  overflow: auto;
  max-height: 300px;
  height: auto;
}
.common-tree ::v-deep .el-tree-node__expand-icon.is-leaf {
  display: none !important;
}
// .common-tree ::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
//   padding: 0;
//   margin-left: 6px;
//   margin-right: 0px;
// }
.el-checkbox {
  margin-left: 10px !important;
}
.el-row {
  padding-top: 0px !important;
}
</style>