<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 v-if="isShowSelect"
        class="common-tree"
        :indent="multiple ? 10 : 10"
        :width="width"
        ref="tree"
        :data="filteredTreeData"
        :filter-node-method="filterNode"
        :show-checkbox="multiple"
        :check-strictly-rm="checkStrictly"
        :check-strictly="true"
        :props="treeBindProps"
         :node-key="treeBindProps.id"
        :default-expanded-keys="selectedExpandValues"
        :default-checked-keys="selectedOptionValues"
        :default-expand-all="defaulExpandAll"
        :expand-on-click-node="multiple && expandClickNode"
        :check-on-click-node="checkClickNode"
        :highlight-current="true"
        @check-change="treeChanged"
      ></el-tree>
      <el-select
        slot="reference"
        ref="select"
        :size="size"
         node-key="id"
        v-model="selectedOptionValues"
        :multiple="multiple"
        :clearable="clearable"
        :collapse-tags="collapseTags"
        @click.native="selectClick"
        @remove-tag="removeSelectedTag"
        @clear="clean"
        class="tree-select"
        reserve-keyword
        :placeholder="placeholder">
        <el-option
          v-for="(item,key) in selectedOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
        <template slot="empty">稍等, 数据加载中...</template>
      </el-select>
    </el-popover>
  </div>
</template>

<script>
//点击外部关闭下拉框
import Clickoutside from "element-ui/src/utils/clickoutside";
import { StaffDepartmentListApi } from "@/api/staffApi.js";

var calculatingSelected = false;
export default {
  directives: { Clickoutside },
  props: {
    //配置是否可以搜索
    filterable: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //输入框占位值
    placeholder: {
      type: String,
      default() {
        return "请选择";
      },
    },
    //配置是否可多选
    multiple: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 配置是否可清空选择
    clearable: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 配置多选时是否将选中值按文字的形式展示
    collapseTags: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 显示复选框情况下，是否严格遵循父子不互相关联
    checkStrictly: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //多选是设置点击节点是否可以选中
    checkClickNode: {
      type: Boolean,
      default() {
        return true;
      },
    },
    //多选时：点击节点展开还是点三角标
    expandClickNode: {
      type: Boolean,
      default() {
        return false;
      },
    },
    //默认展开
    defaulExpandAll: {
      type: Boolean,
      default() {
        return false;
      },
    },
    // 默认选中的节点key
    /*
    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";
      },
    },

    defaultSelectedValues: {
      type: Array,
      default() {
        return [];
      },
    },
    // 树结构数据
    treeData: {
      type: Array,
      default() {
        return [];
      },
    },
    treeBindProps: {
      type: Object,
      required: false,
      default: () => {
        return {
          id: "id", // id
          label: "name", // 显示名称
          children: "children", //子级字段名
        };
      },
    },
  },
  emits:["loadingTreeDataEventHandler"],
  //上面是父组件可传入参数
  data() {
    return {
      popoverWidth: "0px", //下拉框大小
      isShowSelect: false, // 是否显示树状选择器

      options: [], //select option选项
      returnDatas: [], //返回给父组件数组对象
      returnDataKeys: [], //返回父组件数组主键值
      filterText: "", //筛选绑定值
      checkedAll: false, //是否有全选按钮(只有在多选下才能配置)
      treeArrId: [],

      selectedExpandValues: this.defaultSelectedValues,
      selectedOptionValues: [],
      selectedOptions: {},
      selectedPlaceHolder: "稍等, 数据加载中..."
    };
  },

  mounted() {

  },

  computed: {
    filteredTreeData() {
      var self = this;
      // 若非树状结构，则转化为树状结构数据
      /*
      if (this.obj.children != "") {
        return this.data;
      } else {
        return this.data;
      }
        */

      self.refreshDefaultSelectedTreeValue();

      return self.treeData;
    },
  },
  watch: {
    returnDataKeys(newValue, oldValue) {
      if (newValue.length === this.treeArrId.length) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    },

    filterText(val) {
      this.$refs.tree.filter(val);
    },
    // eslint-disable-next-line no-unused-vars
    isShowSelect(val) {
      // 隐藏select自带的下拉框
      this.$refs.select.blur();
    },
    selectedExpandValues(newValue, oldValue) {
      //console.log("默认选中的数据：", newValue, oldValue, self.$refs?.tree?.getCheckedKeys());
    }
  },
  created() {
    this.treeArrId = [];
    //this.originTree(this.treeData);
  },
  methods: {
    removeSelectedTag() { },
    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;
      */
    },
    //下拉框select点击[入口]
    selectClick() {
      this.loadingDepartments(); //点击选择框查询部门列表
      this.$nextTick(function () {
        //设置下拉框自适应宽度
        this.popoverWidth = this.$refs.select.$el.clientWidth;
      });

      //显示下拉框
      (this.isShowSelect = !this.isShowSelect)

      if (this.isShowSelect) {
        //触发显式数据
        this.$emit("loadingTreeDataEventHandler", "");

        this.refreshDefaultSelectedTreeValue(true);
      }
    },
    loadingDepartments() {
      console.log("点击加载部门数据");
    },
    buildSelectedTreeNodes(data, selected, selectedDepartsResult) {
      var self = this;
      if (!data) {
        console.log("无效数据");
        console.log(data);
        return;
      }

      if (selected) {
        selectedDepartsResult.options.push(data);
        selectedDepartsResult.returnDataKeys.push(data.id);
      } else {
        selectedDepartsResult.options = selectedDepartsResult.options.filter(item => item.id != data.id)
        selectedDepartsResult.returnDataKeys = selectedDepartsResult.returnDataKeys.filter(item => item != data.id);
      }

      if (data.children?.length > 0) {
        for (var index = 0; index < data.children?.length; index++) {
          var item = data.children[index];
          self.buildSelectedTreeNodes(item, selected, selectedDepartsResult);
        }
      }
    },
    //单选:清空选中
    clean() {
      this.$refs.tree.setCurrentKey(null); //清除树选中key
      this.returnDatas = null;
      this.returnDataKeys = "";
      this.popoverHide();
    },
    //下拉框关闭执行
    popoverHide() {
      this.$emit("getValue", this.selectedOptionValues, this.returnDatas);
    },
    treeChanged(data, selected) {
      console.log("treeChanged", arguments);
      var self = this;
      if (selected) {
        if (!self.selectedOptions[data.id]) {
          self.selectedOptions[data.id] = data;
          self.selectedOptionValues.push(data.id);
        }
      } else {
        delete self.selectedOptions[data.id];
        self.selectedOptionValues = self.selectedOptionValues.filter(ii => ii != data.id);
      }


      console.log("选中后的数据为:", selected, self.selectedOptions, self.selectedOptionValues);
    },
    refreshDefaultSelectedTreeValue(isFromReloadTree) {
      var self = this;
      if (self.selectedExpandValues?.length == 0 && self.treeData.length > 0) {
        self.selectedExpandValues.push(self.treeData[0].id);
      } else {
        self.selectedExpandValues = [];
        for (var index = 0; index < self.selectedOptionValues.length; index++) {
          self.selectedExpandValues.push(self.selectedOptionValues[index]);
        }

        //self.$refs.tree?.setCheckedKeys(self.selectedExpandValues);
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.common-tree {
  overflow: auto;
  max-height: 300px;
  height: auto;
}
.common-tree /deep/ .el-tree-node__expand-icon.is-leaf {
  display: none !important;
}
// .common-tree /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>
