<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="部门名称：">
        <el-cascader v-model="queryParams.deptId" :options="deptTreeList">
        </el-cascader>
      </el-form-item>
      <el-form-item label="岗位名称：">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入提交部门"
          clearable
        />
      </el-form-item>
      <el-form-item label="人员名称：">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入提交部门"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :xs="24" type="flex" style="margin: 10px 0" justify="space-between">
      <el-col :span="20">
        <div style="margin-bottom: 10px">
          组长：
          <el-tag
            v-for="tag in tags1"
            :key="tag.nickName"
            closable
            :disable-transitions="false"
            @close="handleClose1(tag)"
            style="margin-right: 10px"
            >{{ tag.nickName }}
          </el-tag>
        </div>
        <div>
          成员：
          <el-tag
            v-for="tag in tags2"
            :key="tag.nickName"
            closable
            :disable-transitions="false"
            style="margin-right: 10px"
            @close="handleClose2(tag)"
            >{{ tag.nickName }}
          </el-tag>
        </div>
      </el-col>
      <el-col :span="4">
        <div
          style="display: flex; justify-content: flex-end; margin-right: 20px"
        >
          <el-button
            @click="
              $router.push(
                '/postInspectionPlanning/teamManagement/personnelAllocation'
              )
            "
            >返回</el-button
          >
          <el-button type="primary" @click="addUserItem">确认添加</el-button>
        </div>
      </el-col>
    </el-row>
    <el-table
      border
      v-loading="loading"
      :data="userList"
      style="height: calc(100% - 180px)"
    >
      <el-table-column label="序号" align="center" type="index" width="80" />
      <!-- <el-table-column label="部门属性" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.checkedDeptTypeView || "--" }}</span>
          </template>
        </el-table-column> -->
      <el-table-column label="姓名" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.nickName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.deptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.postName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            :disabled="tags1.length >= 1"
            type="text"
            @click="addItem(scope.row, 1)"
            >设为组长</el-button
          >
          <el-button
            :disabled="isDisabled2(scope.row.userId)"
            type="text"
            @click="addItem(scope.row, 2)"
            >设为成员</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
  listGroupList,
  getTeamListByGroupId,
  listTeamUser,
  getTeamUser,
  delTeamUser,
  addTeamUser,
  updateTeamUser,
  getTeamUserByTeamId,
  getPostUserList,
  getDeptTree,
  addTeamDept,
  getTeamDept,
} from "@/api/postInspectionPlanning/teamManagement.js";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "TeamMembers",
  data() {
    return {
      deptTreeList: [],
      activeName: "1",
      path: "",
      tags: [],
      tags1: [],
      tags2: [],
      // 遮罩层
      loading: false,
      editDialog: false,
      treeForm: {
        name: "",
      },
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      treeData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: "",
        deptId: [],
        postName: "",
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    isDisabled() {
      return (id) => {
        return this.tags.some((item) => item.deptId === id);
      };
    },
    isDisabled2() {
      return (id) => {
        return this.tags2.some((item) => item.userId === id);
      };
    },
  },
  created() {
    this.getList();
    this.listTeam();
    this.getDeptTree();
    this.getTeamDept();
    this.getTeamUserByTeamId();
  },
  methods: {
    addDepItem() {
      addTeamDept(this.tags).then((data) => {
        this.$modal.msgSuccess("添加成功");
        // this.$router.push(
        //   "/postInspectionPlanning/teamManagement//personnelAllocation"
        // );
      });
    },
    addUserItem() {
      addTeamUser([...this.tags1, ...this.tags2]).then((data) => {
        this.$modal.msgSuccess("添加成功");
        // this.$router.push(
        //   "/postInspectionPlanning/teamManagement/personnelAllocation"
        // );
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      const deptId =
        this.queryParams.deptId[this.queryParams.deptId.length - 1];
      getPostUserList({ ...this.queryParams, deptId }).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    listTeam() {
      let data = [
        {
          id: 0,
          parentId: 0,
          name: "岗检领导小组",
          type: 0,
          children: [],
        },
      ];
      listTeam().then((response) => {
        data[0].children = response.rows;
        this.deptOptions = data;
      });
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    addItem(item, type) {
      const params = {
        nickName: item.nickName,
        userId: item.userId,
        postTeamId: this.$route.query.id,
        type,
      };
      if (type === 1) {
        const index = this.tags2.findIndex((r) => r.userId === item.userId);
        if (index !== -1) {
          this.tags2.splice(index, 1);
        }
        this.tags1.push(params);
      } else {
        const index = this.tags1.findIndex((r) => r.userId === item.userId);
        if (index !== -1) {
          this.tags1.splice(index, 1);
        }
        this.tags2.push(params);
      }
    },
    handleClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1);
    },
    handleClose1(tag) {
      this.tags1.splice(this.tags1.indexOf(tag), 1);
    },
    handleClose2(tag) {
      this.tags2.splice(this.tags2.indexOf(tag), 1);
    },
    getTeamUserByTeamId() {
      getTeamUserByTeamId(this.$route.query.id).then((res) => {
        this.tags1 = res.data.filter((item) => item.type === 1);
        this.tags2 = res.data.filter((item) => item.type === 2);
      });
    },
    getTeamDept() {
      getTeamDept({ postTeamId: this.$route.query.id }).then((res) => {
        this.tags = res.rows;
      });
    },
    handleCheck(row) {
      this.tags.push({
        deptId: row.id,
        postTeamId: this.$route.query.id,
        deptName: row.label,
        type: 2,
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.treeForm.name = "";
      this.resetForm("treeForm");
      this.editDialog = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["treeForm"].validate((valid) => {
        if (valid) {
          if (this.title === "修改") {
            updateTeam({ name: this.treeForm.name, id: this.treeData.id }).then(
              (response) => {
                this.$modal.msgSuccess("修改成功");
                this.editDialog = false;
                this.reset();
                this.getDeptTree();
              }
            );
          } else {
            const params = {
              name: this.treeForm.name,
              parentId: this.treeData.id,
              type: this.treeData.type + 1,
            };
            if (params.type === 3) {
              if (this.treeData.children.length === 0) {
                params.teamType = 1;
              } else {
                params.teamType = 2;
              }
            }
            addTeam(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.editDialog = false;
              this.getDeptTree();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.head-container {
  border: 1px solid #e5e5e5;
  margin-top: 10px;
  padding: 10px;
  width: 100%;
  height: 100%;
}
.card {
  margin-right: 10px; //下边距
  margin-top: 10px;
  padding: 10px;
  background: transparent;
  border: 2px solid;
  border-color: #e5e5e5;
  border-image: none;
  ::v-deep .el-card__body {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-avatar {
    width: 120px !important;
    height: 120px !important;
    margin: 14px 14px;
  }
  p {
    margin: 0;
    width: 100%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    line-height: 30px;
    font-size: 14px;
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-table__body-wrapper {
  height: calc(100% - 30px);
  overflow: auto;
}
</style>
