<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :width="width" :before-close="handleClose"
    @close="$emit('input', false)" append-to-body top="5.6vh">
    <div class="theContent">
      <div class="theContent-input">
        <el-input placeholder="请输入内容" ref="focusOnInput" v-model.trim="filterText" class="input-with-select"
          @keyup.enter.native="nameSearch()">
          <el-button slot="append" icon="el-icon-search" @click="nameSearch()"></el-button>
        </el-input>
      </div>
      <div class="theContent-tree">
        <el-tree :data="deptMembData" show-checkbox default-expand-all check-strictly node-key="id" ref="tree"
          highlight-current :props="defaultProps" @check-change="treeHandChange" :filter-node-method="filterNode" v-loading="selectPersonnelTreeLoading">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span v-if="user.userNameNeedTranslate == '1'">
              <span v-if="node.data.children">
                <TranslationOpenDataText type='departmentName' :openid='node.label'></TranslationOpenDataText>
              </span>
              <span v-else>
                <TranslationOpenDataText type='userName' :openid='node.label'></TranslationOpenDataText>
              </span>
            </span>
            <span v-if="user.userNameNeedTranslate != '1'">
              {{ node.label }}
            </span>
          </span>
        </el-tree>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'AbcdEfg',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '选择人员'
    },
    width: {
      type: String,
      default: '800px'
    }
  },
  data() {
    return {
      dialogVisible: this.value,
      filterText: '',
      deptMembData: [],
      user: JSON.parse(sessionStorage.getItem("user")),
      permissions: JSON.parse(sessionStorage.getItem("permissions")),
      filterNodePersonnel: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      selectPersonnelTreeLoading: false,
    }
  },
  watch: {
    value(newVal) {
      this.dialogVisible = newVal
      if(newVal) {
        this.$nextTick(() => {
          this.$refs.focusOnInput.focus()
        })
      }
    },
    filterText(val) {
      if (this.user.userNameNeedTranslate != 1) {
        this.$refs.tree.filter(val);
      }
    }
  },
  mounted() {
    this.getDepartment()
  },
  methods: {
    nameSearch() {
      if (this.user.userNameNeedTranslate != 1) {
        this.$refs.tree.filter(this.filterText);
      } else {
        if (this.filterText != '') {
          this.selectPersonnelTreeLoading = true
          this.http.post("/user/getEmployeeList", {
            keyword: this.filterText,
            cursor: '',
            departmentId: -1,
            pageIndex: 1,
            pageSize: 1000
          },
            res => {
              this.selectPersonnelTreeLoading = false
              if (res.code == "ok") {
                this.filterNodePersonnel = res.data.records.map(item => item.name)
                this.$refs.tree.filter(this.filterText);
              } else {
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            },
            error => {
              this.selectPersonnelTreeLoading = false
              this.$message({
                message: error,
                type: "error"
              });
            });
        } else {
          this.getDepartment()
        }
      }
    },
    filterNode(value, data) {
      let { userNameNeedTranslate } = this.user
      if (!value) return true;
      if (userNameNeedTranslate != '1') {
        return data.label.indexOf(value) !== -1;
      } else {
        return this.filterNodePersonnel.some(item => item.includes(data.label))
      }
    },
    treeHandChange(val, flag) {
      const { id } = val
      if (flag) {
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.tree.setCheckedKeys([id]);
      }
    },
    // 获取部门列表
    getDepartment() {
      this.selectPersonnelTreeLoading = true
      this.http.post("/department/listAllMemb", {},
        res => {
          this.selectPersonnelTreeLoading = false
          if (res.code == "ok") {
            var list = res.data;
            //设置员工到部门下面
            this.setUserToDept(list);
            this.deptMembData = list;
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        },
        error => {
          this.selectPersonnelTreeLoading = false
          this.$message({
            message: error,
            type: "error"
          });
        });
    },
    setUserToDept(list) {
      for (var i in list) {
        if (list[i].children != null) {
          this.setUserToDept(list[i].children);
        }

        if (list[i].userList != null) {
          if (list[i].children == null) {
            list[i].children = [];
          }
          list[i].userList.forEach(element => {
            var obj = { id: element.id, label: element.name, parentId: element.departmentId, isUser: 1 };
            list[i].children.push(obj);
          });
        }
      }
    },
    handleClose() {
      this.dialogVisible = false
      this.$emit('input', false)
    },

    // 确定控件
    handleConfirm() {
      const arr = this.$refs.tree.getCheckedNodes()
      const item = arr[0] || {}
      if(!item.isUser) {
        this.$message({
          message: '请选择人员',
          type: "error"
        });
        return
      }

      const row = { ...item, value: item.id, label: item.label }
      this.$emit('confirm', row)
      this.handleClose()
    },

    // 设置树形控件的选中项
    setTreeCheckedKeys(keys) {
      this.$refs.tree.setCheckedKeys(keys);
    },
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.theContent {
  height: 50vh;
  display: flex;
  flex-direction: column;

  .theContent-tree {
    flex: 1;
    padding-right: 15px;
    margin: 20px 0;
    overflow-y: auto;
  }
}
</style>
