<!--
 * @Description: 
 * @Author: ymz
 * @Date: 2021-12-13 10:24:45
 * @LastEditTime: 2021-12-17 17:03:42
 * @LastEditors: ymz
 * @Reference: 
-->
<template>
  <div class="add-team">
    <el-dialog
      :title="type === 0 ? '添加团队' : '编辑团队'"
      :visible.sync="dialogShow"
      width="60%"
      @close="closeDia"
    >
      <div class="add-content">
        <el-form ref="form" :model="data" label-width="120px" :rules="rules">
          <el-form-item label="团队名称：" prop="name" required>
            <el-input
              v-model="data.name"
              placeholder="请输入团队名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="团队成员：" prop="keyWords">
            <el-input
              placeholder="请输入姓名或手机号码"
              v-model="data.keyWords"
            >
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
        </el-form>

        <div class="select-info">
          <div class="list-info">
            <div class="title">
              选择负责人
            </div>
            <div class="content">
              <el-scrollbar style="height:100%;overflow-x: hidden;">
                <el-checkbox-group v-model="leadersSelID">
                  <el-checkbox
                    class="mb"
                    :label="item.userId"
                    @change="checked => change(checked, item)"
                    v-for="item in leaders"
                    :key="item.userId"
                  >
                    <span class="label">{{ getLabel(item) }}</span>
                  </el-checkbox>
                </el-checkbox-group>
              </el-scrollbar>
            </div>
          </div>
          <div class="list-info">
            <div class="title">
              选择组成人员
            </div>
            <div class="content tree">
              <el-scrollbar style="height:100%;overflow-x: hidden;">
                <el-tree
                  ref="tree"
                  :props="props"
                  :data="treeList"
                  node-key="userId"
                  show-checkbox
                  @check="handleCheckChange"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span class="label2">{{
                      node.label + " " + (data.phone ? data.phone : "")
                    }}</span>
                  </span>
                </el-tree>
              </el-scrollbar>
            </div>
          </div>
          <div class="list-info">
            <div class="title">
              已选择人员
            </div>
            <div class="content">
              <el-scrollbar style="height:100%;overflow-x: hidden;">
                <ul>
                  <li
                    class="sel-list"
                    v-for="(item, index) in getSelectList"
                    :key="index"
                  >
                    <i
                      class="el-icon-s-custom leader"
                      :class="{ hide: !item.isLeader }"
                    ></i>
                    <span>{{ item.realName + " " + item.phone }}</span>
                    <i
                      class="el-icon-circle-close close"
                      @click="remove(item)"
                    ></i>
                  </li>
                </ul>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  teamList,
  addTeam,
  editTeam,
  addTeamByDeptId,
  teamListSearch
} from "@/api/teamManagement/index";
import { debounce } from "@/util/util";

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    // 展示
    show: {
      type: Boolean,
      required: true,
      default: false
    },
    //  0 添加 1 编辑
    type: {
      type: Number,
      default: 0
    },
    // 编辑团队id
    editId: {
      required: false
    },
    // 管理员添加企业id
    deptId: {
      required: false
    }
  },
  data() {
    //这里存数据
    return {
      searchFlag: false,
      dialogShow: false,
      data: {
        name: "",
        keyWords: ""
      },
      // 可选择负责人
      leaders: [],
      // 已选择负责人数据
      leadersSel: [],
      // 已选择负责人ID
      leadersSelID: [],
      // 选择组成人员数据
      treeList: [],
      // 全部组成人员数据
      allList: [],
      // 已选择人员id
      treeListSelID: [],
      // 已选择组成人员数据
      checkList: [],
      props: {
        label: "realName",
        children: "children"
      },
      rules: {
        name: [{ required: true, message: "请输入团队名称", trigger: "blur" }]
      }
    };
  },
  //计算属性
  computed: {},
  //监控data中数据变化
  watch: {
    show: {
      handler(val) {
        this.dialogShow = val;
      },
      immediate: true
    },
    "data.keyWords": {
      handler(val) {
        this.search();
      }
    }
  },
  //方法
  methods: {
    async getList(type) {
      let obj = {
        teamId: this.editId,
        realNameOrPhone: this.data.keyWords,
        deptId: this.deptId
      };
      let res;
      if (type === 0) {
        res = await teamList(obj);
      } else {
        res = await teamListSearch(obj);
      }
      if (res.data.code == 0) {
        let data = res.data.data;
        this.leaders = data.leaders;
        let arr = [
          {
            realName: "未分配团队人员",
            disabled: data.notAssignedMembers.length === 0,
            children: data.notAssignedMembers
          },
          {
            realName: "已分配团队人员",
            disabled: data.assignedMembers.length === 0,
            children: data.assignedMembers
          }
        ];
        this.treeList = arr;
        this.allList = data.notAssignedMembers.concat(data.assignedMembers);
        if (this.searchFlag) {
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(this.treeListSelID);
          });
        }
        if (data.teamName) {
          this.data.name = data.teamName;
        }
        if (data.selectedLeaders.length > 0) {
          this.leadersSel = data.selectedLeaders;
          let arr = [];
          data.selectedLeaders.forEach(item => arr.push(item.userId));
          this.leadersSelID = arr;
        }
        if (data.selectedMembers.length > 0) {
          let arr = [];
          this.checkList = data.selectedMembers;
          data.selectedMembers.forEach(item => arr.push(item.userId));
          this.treeListSelID = arr;
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(arr);
          });
        }
      }
    },
    getLabel(item) {
      return item.realName + " " + item.phone;
    },
    change(checked, info) {
      let arr = [];
      this.leadersSelID.forEach(item => {
        this.leaders.forEach(iten => {
          if (item === iten.userId) {
            arr.push(iten);
          }
        });
      });
      this.leadersSel = arr;
    },
    handleCheckChange(info, data) {
      if (this.searchFlag) {
        let idList = data.checkedKeys;
        // 多选操作
        if (info.children) {
          let arr = info.children;
          if (idList.length > 0) {
            arr.forEach(item => {
              if (!this.treeListSelID.includes(item.userId)) {
                this.checkList.push(item);
                this.treeListSelID.push(item.userId);
              }
            });
          } else {
            arr.forEach(item => {
              this.remove(item);
            });
          }
        } else {
          // 选中
          if (idList.includes(info.userId)) {
            if (!this.treeListSelID.includes(info.userId)) {
              this.checkList.push(info);
              this.treeListSelID.push(info.userId);
            }
          } else {
            // 取消选中
            this.remove(info);
          }
        }
        return;
      }
      this.checkList = this.$refs.tree.getCheckedNodes(true);
      this.treeListSelID = this.$refs.tree.getCheckedKeys(true);
    },
    remove(info) {
      if (info.isLeader) {
        let index = this.leadersSel.findIndex(
          item => item.userId === info.userId
        );
        this.leadersSel.splice(index, 1);
        this.leadersSelID.splice(index, 1);
      } else {
        let index = this.checkList.findIndex(
          item => item.userId === info.userId
        );
        this.checkList.splice(index, 1);
        this.treeListSelID.splice(index, 1);
        this.$nextTick(() => {
          this.$refs.tree.setCheckedNodes(this.checkList);
        });
      }
    },
    confirmClick() {
      if (this.type === 0) {
        this.addTeam();
      } else {
        this.editTeam();
      }
    },
    async addTeam() {
      if (!this.data.name) {
        this.$message.info("请输入团队名称");
        return;
      }
      let res;
      let obj = {
        name: this.data.name,
        leader: this.leadersSelID,
        member: this.treeListSelID
      };
      if (this.deptId) {
        obj.deptId = this.deptId;
        res = await addTeamByDeptId(obj);
      } else {
        res = await addTeam(obj);
      }

      if (res.data.code === 0) {
        this.$message.success("添加团队成功");
        this.closeDia();
        this.$emit("Success", 1);
      }
    },
    async editTeam() {
      if (!this.data.name) {
        this.$message.info("请输入团队名称");
        return;
      }
      let obj = {
        id: this.editId,
        name: this.data.name,
        leader: this.leadersSelID,
        member: this.treeListSelID
      };
      let res = await editTeam(obj);
      if (res.data.code === 0) {
        this.$message.success("更新团队成功");
        this.closeDia();
        this.$emit("Success", 1);
      }
    },
    initForm() {
      this.$refs.form.resetFields();
    },
    closeDia() {
      this.initForm();
      this.$emit("update:show", false);
    },
    search: debounce(function() {
      this.searchFlag = true;
      let arr = [];
      this.checkList.forEach(item => arr.push(item.userId));
      this.treeListSelID = arr;
      this.getList(1);
    }, 1000)
  },
  computed: {
    getSelectList() {
      let str = this.leadersSel;
      let str2 = this.checkList;
      return str.concat(str2);
    }
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getList(0);
  }
};
</script>

<style scoped lang="scss">
.select-info {
  height: 350px;
  border-bottom: 1px solid #ccc;
  display: flex;
  .list-info {
    flex: 1;
    border-right: 1px solid #ccc;
    &:last-child {
      border-right: none;
    }
    .title {
      height: 35px;
      text-align: center;
      line-height: 35px;
      font-size: 13px;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
    }
    .content {
      padding: 15px;
      height: 300px;
      overflow: auto;
      overflow-x: hidden;

      ul {
        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          span {
            font-size: 13px;
            flex: 1;
            line-height: 20px;
          }
          i {
            width: 30px;
            font-size: 18px;
            line-height: 20px;
            margin-bottom: 5px;
            &.leader {
              color: #81d3f8;
            }
            &.close {
              cursor: pointer;
            }
          }
          .hide {
            opacity: 0;
          }
        }
      }
    }
    .mb {
      margin-bottom: 7px;
      display: flex;
    }
  }
  .label {
    max-width: 250px;
    white-space: pre-wrap;
  }

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.tree {
  ::v-deep .el-tree-node {
    white-space: normal;
  }

  ::v-deep .el-tree-node__content {
    height: 100%;
    align-items: start;
  }
}


::v-deep .el-tree{
  height: 270px;
  &>.el-tree-node{
  height: 130px;
  overflow: hidden;
  &>.el-tree-node__content{
    height: 25px;
    }
  &>.el-tree-node__children{
    height: 105px;
    overflow: auto;
    &::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
    }
  }
}
</style>
