<template>
  <div class="departmentManagement">
    <el-row :gutter="10">
      <el-col :span="8" style="overflow-x: auto;min-width: 100px;" class="treeCard">
        <el-card class="left" style="font-size: 14px;overflow-x: auto!important;padding: 0!important;min-width: 200px;">
          <el-button type="primary" size="small" v-if="treeData.length==[]" @click="addDepartment()">请添加部门</el-button>
          <Tree id="tree" style="overflow-x: auto!important; height: calc(100vh - 106px);" v-else ref="tree" node-key="id" :tree-data="treeData" :add-form-arr="addFormArr" :add-form="addForm" @treeDelChange="treeDelChange" :default-props="defaultProps" :default-expand-all="true" :is-add-del="true" @treeSubmitChange="treeSubmitChange" @treeUpdateChange="treeUpdateChange" @treeEditChange="treeEditChange"></Tree>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="right">
          <div class="button">
          <el-button type="primary" size="small" :disabled="isDisabled" @click="addDepartmentUser">编辑部门人员</el-button>
          </div>
          <el-table :data="departmentUserList" border style="width: 100%" height="700">
            <el-table-column prop="username" label="用户名称" width="120">
            </el-table-column>
            <el-table-column prop="" label="职位" width="120">
              <template slot-scope="scope">
                <div v-show="scope.row.id==depleaderid">主管</div>
                <div v-show="scope.row.id==depviceid">副主管</div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="地址"  width="120"> </el-table-column>
            <el-table-column prop="mobile" label="手机号" width="150"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div style="display:flex;flex-direction:row;overflow-x: auto">
                  <el-button size="small" type="primary" @click="addCharge(scope.row)" :disabled="scope.row.id==depleaderid||scope.row.id==depviceid">设置为主管</el-button>
                  <el-button size="small" type="primary" @click="addChargeSon(scope.row)" :disabled="scope.row.id== depleaderid||scope.row.id==depviceid">设置为副主管</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加根节点的弹窗 -->
    <el-dialog  :visible.sync="dialogFormVisible" width="65%" title="请添加部门" :append-to-body="true"  custom-class="treeCreatePeople">
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="110px">
        <div v-for="(item,index) in addFormArr" :key="index">
          <el-form-item :label="item.label+`:`" :prop="item.prop">
            <el-input v-model="addForm[item.prop]" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="btnGroup">
        <el-button size="small" @click="resetForm('addForm')">取消</el-button>
        <el-button type="primary" size="small" @click="submitForm('addForm')">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加部门人员的弹窗 -->
    <el-dialog :title="'请为'+addUserTitle+'添加人员'" :visible.sync="addUserDialog" width="60%" :append-to-body="true" custom-class="addBySales" >
      <Tree :default-props="defaultProps1" id="addUserid" ref="addUserTree" node-key="id" :treeData="orgTreeDate" :default-expand-all="true" :show-checkbox="true"></Tree>
      <div style="display:flex;justify-content:center">
        <el-button size="small" @click="cancelAdd">取消添加</el-button>
        <el-button type="primary" size="small" @click="depSubmit">确定添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Tree from "@/components/TreeControl/index.vue";
import { getDepartmentAPI, addDepartmentAPI, delDepartmentAPI, addUserDepartmentAPI, getUserDepartmentAPI, upDepartmentAPI } from '@/api/admin/departmentManagement'
import { myOrganizationAPI } from  '@/api/superAdministrator/management'
export default {
  name: "departmentManagement",
  components: {
    Tree
  },
  data() {
    return {
      isDisabled: true,
      dialogFormVisible: false,
      addUserDialog: false,
      treeData: [],
      orgTreeDate: [],
      departmentUserList: [],//部门下已有的人员
      userid: sessionStorage.getItem('userId'),
      departmendid: null,//部门id
      addUserTitle: '',
      addUserList: [],
      treeNode: null,
      depleaderid: null,//部门正领导
      depviceid: null,//部门副领导
      addForm: {
        depname: ''
      },
      form: {
        depname: ''
      },
      addFormArr: [{
        label: '部门名称',
        prop: 'depname'
      }],
      rules: {
        depname: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
      },
      defaultProps: {
        children: "son",
        label: "depname",
      },
      defaultProps1: {
        children: "son",
        label: "username",
      },
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    getDepartment() {//获取所有部门
      getDepartmentAPI({ userid: this.userid }).then(res => {
        // console.log(res);
        this.treeData = res.data;
      })
    },
    addDepartment() {
      this.dialogFormVisible = true
    },
    treeSubmitChange(form) {//添加部门
      // console.log(form);
      let params = {
        ...form,
        userid: this.userid
      }
      const fromdata = this.getFormData(params);
      addDepartmentAPI(fromdata).then(res => {
        if (res.status == true) {
          this.$message({
            message: '部门添加成功',
            type: 'success'
          })
          this.getDepartment()
          this.$refs.tree.resetForm('addForm');
          this.$refs.tree.dialogFormVisible = false;
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }

      })
    },
    submitForm(formName) {//点击确定添加部门
      let params = {
        depname: this.addForm.depname,
        userid: this.userid
      }
      const fromdata = this.getFormData(params);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addDepartmentAPI(fromdata).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "添加部门成功",
                type: "success",
              });
              this.dialogFormVisible = false;
              this.$refs.addForm.resetFields();
              this.getDepartment()
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          })
        }
      })
    },
    treeUpdateChange(obj) {//点击树结构触发的事件
      // console.log(obj);
      this.isDisabled = false
 this.depleaderid = null
            this.depviceid = null
      this.departmendid = obj.data.data.id
      this.addUserTitle = obj.data.data.depname
      this.getUserDepartment()

    },
    treeEditChange(obj) {//编辑

    },
    getUserDepartment() {//获取部门下已有的人员
      getUserDepartmentAPI({ depid: this.departmendid }).then(res => {
        if (res.status == true) {
           this.depleaderid = null
            this.depviceid = null
          this.departmentUserList = null
          if (res.users.length) {
            res.users.map(item => {
              if (item.depleaderid) {
                this.depleaderid = item.depleaderid
              }
              if (item.depviceid) {
                this.depviceid = item.depviceid
              }
            })
          }
          this.departmentUserList = res.data.map(item => {
            let xitem = {
              username: item.user.username,
              id: item.user.id,
              address: item.user.address,
              email: item.user.email,
              mobile: item.user.mobile,
            }
            return xitem
          })
        }
      })
    },

    addDepartmentUser() {//获取机构下的全部人员
      this.addUserDialog = true
      myOrganizationAPI({ id: this.userid }).then(res => {
        if (res.status == true) {
          this.orgTreeDate = res.users
          this.$nextTick(() => {
            this.$refs.addUserTree.setCheckedNodes(this.departmentUserList)
            this.getUserDepartment()
          })
        }
      })
    },

    depSubmit() {//点击确定添加部门人员
      const persons = this.$refs.addUserTree.getCheckedKeys();
      let params = {
        depid: this.departmendid,
        userid: JSON.stringify(persons),
      }
      const adduser = this.getFormData(params)
      addUserDepartmentAPI(adduser).then(res => {
        if (res.status == true) {
          this.$message({
            message: '人员添加成功',
            type: 'success'
          })
          this.getUserDepartment()
          // this.addDepartmentUser()
          this.addUserDialog = false
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    addCharge(row) {//设置为主管
    // console.log(row);
      this.$confirm("确定设置为主管?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          upDepartmentAPI({ id: this.departmendid, depleaderid: row.id }).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "主管设置成功",
                type: "success",
              });
              this.getUserDepartment()
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },
    addChargeSon(row) {//设置为副主管
      this.$confirm("确定设置为副主管?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          upDepartmentAPI({ id: this.departmendid, depviceid: row.id }).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "副主管设置成功",
                type: "success",
              });
              this.getUserDepartment()
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },
    cancelAdd() {
      this.addUserDialog = false
    },
    treeDelChange(obj) {//删除部门
      // console.log(obj);
      delDepartmentAPI({ id: obj.data.id }).then(res => {
        if (res.status == true) {
          this.$message({
            message: '部门删除成功',
            type: 'success'
          })
          this.getDepartment()
          this.$refs.tree.dialogFormVisible = false;
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }

      })
    },
    resetForm(formName) {//取消添加部门
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },
    getFormData(object) {//转换参数为formdata格式
      const formData = new FormData();
      Object.keys(object).forEach(key => {
        const value = object[key];
        if (Array.isArray(value)) {
          value.forEach((subValue, i) => {
            formData.append(key + `[${i}]`, subValue)
          })
        } else {
          formData.append(key, object[key])
        }
      })
      return formData;
    },
  }
}
</script>

<style lang="scss" scoped>
.el-button{
  margin-bottom: 10px;
}
.departmentManagement {
  height: 90vh;
  .left {
    height:90vh;
  }
  .right {
    .button{
      display:flex;
    }
    height: 90vh;
    .userdeparment {
      // font-size: 18px;
    }
  }
}
.el-card__body{
  padding: 0;
}
.treeCard{
padding: 0;
  margin:0;
 ::v-deep .el-card__body{
    padding: 0;
   overflow-x: auto;
  }
}
</style>
