<template>
  <div class="selected_user">
    <p class="selected_title">目标用户：</p>
    <div class="selected_list" ref="selectedList">
      <template v-for="(item, index) in selectedList">
        <span
          class="selected_more"
          v-if="index + 1 === selectedList.length && showSelectedMore"
          :key="'last_' + index"
          >...</span
        >
        <span class="selected_item" :key="item.id">
          <span v-text="item.label"></span>
          <i class="el-icon-close" @click="deleteItem(item)"></i>
        </span>
      </template>
    </div>
    <div class="user_list apass_checkbox">
      <el-input
        v-model="search"
        placeholder="请输入内容"
        @input="searchAction"
      ></el-input>
      <div class="user_tree apaas_scroll">
        <!-- check-strictly -->
        <el-tree
          ref="userTree"
          :data="targetUserList"
          :default-expand-all="true"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          @check="selectedAction"
        ></el-tree>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: "",
      timer: null,
      targetUserList: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      selectedList: [],
      showSelectedMore: false,
    };
  },
  created() {
    this.getTargetUserList();
  },
  mounted() {
    this.selectedListResize();
    window.addEventListener("resize", this.selectedListResize);
  },
  destroyed() {
    window.removeEventListener("resize", this.selectedListResize);
  },
  methods: {
    getTargetUserList() {
      this.$http
        .get("/apaas/backmgt/center/targetUserList", {
          params: {
            search: this.search,
          },
        })
        .then(({ data }) => {
          if (data.success == 1) {
            this.targetUserList = [
              {
                id: "apaas-all",
                label: "全选",
                level: 0, // 全选
                children: (data.data || []).map((item) => ({
                  id: item.department_id,
                  label: item.department_name,
                  level: 1, // 组织
                  children: (item.userList || []).map((v) => ({
                    id: v.user_id,
                    label: v.user_name,
                    level: 2, // 用户
                    parent_id: item.department_id,
                  })),
                })),
              },
            ];

            if (this.selectedList.length > 0) {
              this.$nextTick(() => {
                this.selectedList.forEach((node) => {
                  this.setChecked(node, true, true);
                });
              });
            }
          } else {
            this.$message({
              message: data.errMsg || "获取用户列表失败",
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.log(error);

          this.$message({
            message: "获取用户列表失败",
            type: "warning",
          });
        });
    },
    searchAction() {
      if (this.timer) {
        clearTimeout(this.timer);
      }

      this.timer = setTimeout(this.getTargetUserList, 200);
    },
    setChecked(item, checked, deep) {
      this.$refs.userTree.setChecked(item, checked, deep);
    },
    selectedAction(dataObj, checkedInfo) {
      let checkedNodes = checkedInfo.checkedNodes.filter((node) => {
        return node.id !== "apaas-all"; // 把自定义的全选节点移除
      });
      let selectedList = [];

      checkedNodes.forEach((node) => {
        if (node.level === 1) {
          selectedList.push(node);
        } else if (node.level === 2) {
          if (selectedList.find((v) => v.id === node.parent_id)) {
            // 父节点已被选中
          } else {
            selectedList.push(node);
          }
        }
      });

      this.selectedList = selectedList;

      this.upSelected();
    },
    deleteItem(item) {
      this.setChecked(item, false, true);

      this.selectedList = this.selectedList.filter((node) => {
        return node.id !== item.id;
      });

      this.upSelected();
    },
    upSelected() {
      // console.log(this.selectedList.map((node) => node.label));

      let users = [];

      this.selectedList.forEach((node) => {
        if (node.level === 1) {
          users.push(...node.children);
        } else if (node.level === 2) {
          users.push(node);
        }
      });

      this.selectedListResize();

      // console.log(users);

      this.$emit("change", users);
    },
    selectedListResize() {
      this.$nextTick(() => {
        let container = this.$refs.selectedList;
        let containerWidth = container.getBoundingClientRect().width - 10;
        let items = container.querySelectorAll(".selected_item");
        let itemsLength = items.length;
        let itemsWidth = [];
        let totalWidth = 0;

        if (items.length < 1) {
          return;
        }

        this.showSelectedMore = false;

        for (let i = 0; i < itemsLength; i++) {
          let item = items[i];
          let itemWidth = 0;

          item.style.display = "inline-block";

          itemWidth = Math.ceil(item.getBoundingClientRect().width) + 10;

          itemsWidth.push(itemWidth);

          totalWidth += itemWidth;

          if (totalWidth > containerWidth) {
            this.showSelectedMore = true;
          }
        }

        if (this.showSelectedMore) {
          let showItemWidth = itemsWidth[itemsLength - 1] + 30; // 最后一个元素的宽度 + 省略号的宽度

          for (let i = 0; i < itemsLength - 1; i++) {
            let item = items[i];

            showItemWidth += itemsWidth[i];

            if (showItemWidth > containerWidth) {
              item.style.display = "none";
            }
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.selected_user {
  max-width: 1024px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
}
.selected_title {
  flex-shrink: 0;
  padding: 0 15px;
  font-size: 14px;
  line-height: 30px;
  color: #58617a;
  margin-top: 10px;
}
.selected_list {
  flex-shrink: 0;
  height: 44px;
  padding: 4px;
  border: 1px solid #e3e5ef;
  box-sizing: border-box;
  border-radius: 7px;
  overflow: hidden;
  margin-top: 10px;
  font-size: 0;
}
.selected_list .selected_item {
  display: inline-block;
  vertical-align: middle;
  background-color: #e6ebfe;
  border-radius: 3px;
  overflow: hidden;
  padding: 0 5px;
  box-sizing: border-box;
  min-width: 20px;
  margin: 5px;
  font-size: 12px;
  line-height: 24px;
  color: #0f2683;
}
.selected_more {
  display: inline-block;
  vertical-align: middle;
  width: 20px;
  margin: 5px;
  font-size: 12px;
  line-height: 24px;
  color: #0f2683;
  text-align: center;
}
.selected_list .selected_item > i {
  cursor: pointer;
  font-weight: bold;
}
.user_list {
  flex-grow: 1;
  background-color: #f8f9fd;
  padding: 10px;
  box-sizing: border-box;
  border-radius: 7px;
  margin-top: 10px;
  position: relative;
}
.user_list .user_tree {
  position: absolute;
  top: 60px;
  right: 10px;
  bottom: 10px;
  left: 10px;
  overflow-x: hidden;
  overflow-y: auto;
}
.user_tree .el-tree {
  background-color: transparent;
}
</style>

<style>
.selected_user .el-tree-node__content {
  height: 32px;
}
</style>
