<template>
  <div class="selected_user">
    <p class="selected_title">目标用户：</p>
    <div class="selected_list">
      <span class="selected_item" v-for="item in selectedList" :key="item.id">
        <span v-text="item.label"></span>
        <i class="el-icon-close" @click="deleteItem(item)"></i>
      </span>
    </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: [],
    };
  },
  created() {
    this.getTargetUserList();
  },
  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);
        }
      });

      // console.log(users);

      this.$emit("change", users);
    },
  },
};
</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;
  min-height: 44px;
  padding: 4px;
  border: 1px solid #e3e5ef;
  box-sizing: border-box;
  border-radius: 7px;
  overflow: hidden;
  margin-top: 10px;
}
.selected_list .selected_item {
  display: inline-block;
  vertical-align: middle;
  background-color: #e6ebfe;
  border-radius: 3px;
  overflow: hidden;
  padding: 0 5px;
  margin: 5px;
  font-size: 12px;
  line-height: 24px;
  color: #0f2683;
}
.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>
