<!--
 * @Author: zk
 * @Date: 2021-11-29 11:26:07
 * @LastEditTime: 2022-01-14 14:08:06
 * @LastEditors: Please set LastEditors
 * @Description:编辑职员
 * @FilePath: \Foshan4A2.0\src\views\authorityManagement\components\authorityPower.vue
-->
<template>
  <div class="authorityPower">
    <!--编辑职员-->
    <div class="addApp-form">
      <div class="addApp-form-title flex">
        <div class="title">编辑职员</div>
        <div class="btn">
          <el-button @click="saveBtn('form')" type="primary">保存</el-button>
        </div>
      </div>
      <div class="addApp-form-content dialog-public-background">
        <el-form :inline="true" ref="form" :rules="rules" class="form" :model="form">
          <el-form-item prop="name" label="职员名称">
            <el-input placeholder="请输入职员名称" maxlength="32" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item prop="loginName" label="职员登录名">
            <el-input placeholder="请输入职员登录名" maxlength="32" v-model="form.loginName"></el-input>
          </el-form-item>
          <el-form-item style="margin-right: 16px" label="登录密码">
            <el-input placeholder="*******" disabled maxlength="32" v-model="form.loginPwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="reSetPassWord">重置密码</el-button>
          </el-form-item>
          <el-form-item label="描述">
            <el-input style="width: 25.65vw" maxlength="200" placeholder="请输入描述" v-model="form.app"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="power-content flex-wrap">
      <div class="r24 flex1 part">
        <Organization :defaultProps="defaultProps" :lessData="lessData" :mainData="mainData" :vice="true" :data="data" @getTreeData="getOrgan" @getTreeindex="getTreeindex" @radioChange="radioChange" :checkedKeys="orgCheckedKeys" :checkBoxList="checkBoxList" :radioCheck="radioNum" @checkChange="lessChecks" nodekey="OrganId" title="所属组织及所属岗位" />
      </div>
      <!--有角色-->
      <template v-if="openRole">
        <div class="r24 flex1 part">
          <Rolelist @checkChange="checkChange" @checkClick="checkClick" :checkBoxList="roleCheckBoxs" :dataList="arrs" :active="true" class="hucRole" :number="8" title="角色列表" />
        </div>
        <div class="flex1 part">
          <Permissionlist style="height: 376" :imageSize="120" :RoleList="RoleList" :check="true" class="hucPower" title="权限列表" />
          <Loginpolicy style="margin-top: 24px; height: calc(100% - 24px - 376px)" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
        </div>
      </template>
      <!--有权限组列表-->
      <template v-else-if="OpenGroup">
        <div class="r24 flex1 part">
          <Rolelist @checkChange="checkChange" @checkClick="checkGroup" :checkBoxList="groupCheckBoxs" :dataList="arrs" :active="true" class="hucRole" :number="8" title="权限组列表" />
        </div>
        <div class="flex1 part">
          <Permissionlist style="height:376px;" :imageSize="120" :RoleList="RoleList" :check="true" class="hucPower" title="权限列表" />
          <Loginpolicy style="margin-top:24px;height:calc(100% - 376px - 24px);" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
        </div>
      </template>
      <!--无角色-->
      <template v-else>
        <div class="r24 flex1 part">
          <Permissiontree ref="Permissiontree" :queryType="queryType" :queryId="treeId" :checkedKeys="checkedBoxs" :isMainJob="isMainJob" @nodeClick="nodeClick" @getTreeData="getTreeData" title="权限树" />
        </div>
        <div class="flex1 part">
          <Rulesofcompetency style="height: 512px" class="hucPower" :authList="authList" :authTo="authTo" @getData="getData" title="权限规则" />
          <Loginpolicy style="margin-top: 24px; height: calc(100% - 24px - 512px)" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import Permissiontree from "@/components/permissiontree";
import Rulesofcompetency from "@/components/rulesofcompetency";
import Organization from "@/components/organization";
import Permissionlist from "@/components/permissionlist";
import Rolelist from "@/components/rolelist";
import Loginpolicy from "@/components/loginpolicy";
import treeData from "../minixs/treeData";
import { mapGetters } from "vuex";
import { RoleAuths } from "@/api/apiAuthority";
import { GetGroupByJob } from '@/api/authGroupApi'
import {
  newstaffmod,
  postList,
  organgitpost,
  jbdetpop,
  Staffdetails,
} from "@/api/postInterface";
import { pwdProduce } from "@/utils/validate";
export default {
  name: "AuthorityPower",
  mixins: [treeData],
  components: {
    Rulesofcompetency,
    Organization,
    Permissiontree,
    Permissionlist,
    Rolelist,
    Loginpolicy,
  },
  data () {
    return {
      Status: null,
      AppId: null,
      form: {
        //应用表单
        name: "",
        loginName: "",
        loginPwd: "",
        app: "",
      },
      title: "角色",
      rules: {
        //表单验证
        name: [{ required: true, message: "请输入职员名称", trigger: "blur" }],
        loginName: [
          { required: true, message: "请输入职员登录名", trigger: "blur" },
        ],
        loginPwd: [
          { required: true, message: "请输入职员登录密码", trigger: "blur" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "OrganName",
      },
      treeId: null, //根据组织获取权限树的组织ID
      checkedKeys: [], //上级组织选中
      RoleList: [],
      checkedBoxs: [],
      arrs: [],
      OfficerId: null,
      authId: [], //权限树默认选中ID
      authList: [],
      authTo: {},
      orgTypes: [],
      msgDatas: [],
      publicCheckBoxs: [],
      checkBoxList: [], //副岗默认选中
      checkedList: [], //登录策略默认选中的数据
      radioCheck: null, //主岗默认选中
      radioNum: null, //主岗已选中
      roleDatas: [], //接口详情返回的角色列表数据
      roleCheckBoxs: [], //角色列表默认选中数据
      groupCheckBoxs: [], //权限组列表默认选中数据
      orgCheckedKeys: [], //组织树默认选中
      loginCheckBoxs: [], //登录策略数据
      mainData: [], //主岗数据
      JobId: "", //主岗ID
      lessData: [], //副岗数据
      mainCheckData: [], //主岗切换时选中的数据
      lessCheckBoxs: [], //副岗选中数据联合主岗
      lessChecksData: [], //副岗选中数据
      lessCheckData: [], //副岗切换时数据
      queryType: null, //权限树类型
      openRole: null,
      dataObj: {}, //上级权限指定树数据
      data: [], //上级权限
      roleList: [], //角色
      checkRoles: [], //选中的角色
      checkTrees: [], //上级权限选中树数据
      rulesObj: {}, //权限规则数据
      isMainJob: true, //是否主岗
      oldOrganId: "",
      msgType: 'org'
    };
  },
  computed: {
    ...mapGetters(["systemSet"]),
  },
  watch: {
    //监听上级组织数据
    dataList: {
      handler (val) {
        this.data = [val];
      },
      deep: true,
    },
    arrs: {
      handler (arr, old) {
        this.orgTypes.push(old)
        if (this.orgTypes.length > 1) {
          this.groupCheckBoxs = [];
          this.roleCheckBoxs = [];
        } else {
          if (this.openRole) {
            this.defaultChecked(arr, 'RoleId')
          } else if (this.OpenGroup) {
            this.defaultChecked(arr, 'GroupId')
          }
        }
      },
      deep: true
    },
    msgDatas: {
      handler (arr) {
        const datas = []
        const checks = []
        const less = []
        if (this.publicCheckBoxs.length > arr.length) {
          this.publicCheckBoxs.forEach((item, index) => {
            arr.forEach(p => {
              if (item.GroupId == p.GroupId) {
                datas.push(index)
              }
            })
          })
        } else {
          arr.forEach((item, index) => {
            this.publicCheckBoxs.forEach(p => {
              if (item.GroupId == p.GroupId) {
                datas.push(index)
              }
            })
          })
        }
        if (this.mainCheckData.length > arr.length) {
          this.mainCheckData.forEach((item, index) => {
            arr.forEach(p => {
              if (item.GroupId == p.GroupId) {
                less.push(index)
              }
            })
          })
        } else {
          arr.forEach((item, index) => {
            this.mainCheckData.forEach(p => {
              if (item.GroupId == p.GroupId) {
                less.push(index)
              }
            })
          })
        }
        const nums = Array.from(new Set([...less, ...datas]))
        this.groupCheckBoxs = nums
        this.arrs.forEach((item, index) => {
          this.groupCheckBoxs.forEach(p => {
            if (index == p) {
              checks.push(item)
            }
          })
        })
        this.checkRoles = checks
      },
      deep: true
    },
    lessCheckData: {
      handler (val, old) {
        let num = null
        if (old.length > val.length) {
          for (let i = 0; i < old.length; i++) {
            for (let j = 0; j < val.length; j++) {
              if (old[i] == val[j]) {
                old.splice(i, 1)
              }
            }
          }
          if (old.length) {
            num = old[0]
            const { JobId } = this.lessData[num]
            this.getNewGroupByJob(JobId)
          }
        }
      },
      deep: true
    }
  },
  created () {
    const { OrganId, Status, OfficerId } = this.$route.query;
    const { OpenRole, PwdLengthBegin, PwdLengthEnd, PwdStruc, OpenGroup } =
      typeof this.systemSet === "string"
        ? JSON.parse(this.systemSet)
        : this.systemSet; //1是请求角色 0是请求用户
    // this.form.loginPwd = pwdProduce(PwdLengthBegin, PwdLengthEnd, PwdStruc);
    this.Status = Status;
    this.OfficerId = OfficerId;
    this.openRole = OpenRole;
    this.OpenGroup = OpenGroup;
    if (!OpenRole) {
      if (OrganId == -1) {
        this.queryType = "all";
      } else {
        this.queryType = "origin";
      }
    }
    this.getOfficerDetails(OfficerId);
  },
  methods: {
    //职员详情查询
    async getOfficerDetails (id) {
      try {
        let params = {
          OfficerId: id,
        };
        const res = await Staffdetails(params);
        if (res.code === 0) {
          const obj = res.returnData;
          const {
            AuthList,
            DepJobList,
            JobId,
            OrganId,
            OfficerDesc,
            OfficerLoginName,
            OfficerName,
            RoleList,
            TacList,
            GroupList
          } = obj;
          this.form.name = OfficerName;
          this.form.loginName = OfficerLoginName;
          this.form.app = OfficerDesc;
          this.orgCheckedKeys = [OrganId];
          this.oldOrganId = OrganId;
          this.roleDatas = RoleList;
          this.radioCheck = JobId;
          this.JobId = JobId;
          this.lessChecksData = DepJobList;
          this.isMainJob = false;
          let IDs = [];
          if (JobId && JobId != "") {
            if (!this.openRole && !this.OpenGroup) {
              this.queryType = "job";
              this.$refs.Permissiontree.MainJobId = JobId;
              if (DepJobList) {
                DepJobList.forEach((item) => {
                  IDs.push(item.JobId);
                });
              }
              this.treeId = IDs.toString();
            }
          } else {
            this.queryType = "origin";
            this.treeId = OrganId + "";
          }

          if (AuthList && AuthList.length) {
            AuthList.forEach((item) => {
              this.authId.push(item.AuthId);
            });
            this.authList = _.cloneDeep(AuthList);
            this.authTo = AuthList[0];
            this.checkedBoxs = this.authId;
          }
          if (RoleList && RoleList.length) {
            const [checkRoles, checkBoxs] = [[], []];
            RoleList.forEach((item, index) => {
              if (item.IsSelected == 1) {
                checkRoles.push(item);
                checkBoxs.push(index);
              }
            });
            if (checkRoles.length && checkBoxs.length) {
              this.checkRoles = checkRoles;
              this.roleAuths(RoleList[0].RoleId);
            }
          }
          if (GroupList && GroupList.length) {
            const [checkRoles, checkBoxs] = [[], []];
            GroupList.forEach((item, index) => {
              if (item.IsSelected == 1) {
                checkRoles.push(item);
                checkBoxs.push(index);
              }
            });
            if (checkRoles.length && checkBoxs.length) {
              this.checkRoles = checkRoles;
              this.groupAuths(GroupList[0].GroupId);
            }
          }
          this.checkedList = TacList;
          this.loginCheckBoxs = TacList;
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //获取选中的树数据
    getTreeData (arr) {
      this.checkTrees = arr;
    },
    // 默认选中
    defaultChecked (arr, id) {
      const datas = []
      arr.forEach((item, index) => {
        this.checkRoles.forEach(p => {
          if (item[id] == p[id]) {
            datas.push(index)
            this.publicCheckBoxs.push(item);
          }
        })
      })
      if (this.openRole) {
        this.roleCheckBoxs = datas;
      } else if (this.OpenGroup) {
        this.groupCheckBoxs = datas;
      }
    },
    //根据岗位获取岗位
    async getNewGroupByJob (id) {
      console.log(this.mainCheckData)
      try {
        let params = {
          JobId: id
        }
        const res = await GetGroupByJob(params)
        if (res.code === 0) {
          const arr = res.returnData
          this.arrs.concat(this.mainCheckData)
          this.arrs.forEach((item, index) => {
            arr.forEach(p => {
              if (item.GroupId == p.GroupId) {
                this.arrs.splice(index, 1)
              }
            })
          })
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    //获取组织选中的数据
    getOrgan (arr) {
      if (arr.length) {
        this.checkedKeys = arr;
        const { OrganId } = this.checkedKeys[this.checkedKeys.length - 1];
        this.AppId = OrganId;
        if (!this.openRole && !this.OpenGroup) {
          if (this.oldOrganId != OrganId) {
            this.queryType = "origin";
            this.treeId = OrganId;
          } else {
            this.oldOrganId = "";
          }
        } else if (this.openRole) {
          this.getRoleByOrgan(OrganId);
        } else if (this.OpenGroup) {
          this.getGroupByOrgan(OrganId)
        }
      }
    },
    //获取指定数据
    decompose (data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].OrganId == id) {
          this.dataObj = data[i];
        } else if (data[i].children && data[i].children.length > 0) {
          this.decompose(data[i].children, id);
        }
      }
    },
    //权限树点击
    nodeClick (obj) {
      const arr = this.$store.getters.authArrs;
      arr.push(obj);
      this.$store.dispatch("auth/changeAuthArrs", arr);
    },
    //岗位选择
    getTreeindex (index) {
      if (index == 1 && !this.checkedKeys.length) {
        this.$message.error("请先选中组织后再选择主岗");
        return false;
      } else if (index == 1 && this.checkedKeys.length) {
        const { OrganId } = this.checkedKeys[this.checkedKeys.length - 1];
        this.getJobListByOrgan(OrganId);
      } else if (index == 2 && !this.mainData.length) {
        this.$message.error("请先选中主岗后再选择副岗");
        return false;
      } else if (index == 2 && this.mainData.length) {
        this.mainCheckData = this.checkRoles
        this.getJobList();
      }
      if (index == 1) {
        this.msgType = 'org'
      } else if (index == 2) {
        this.msgType = 'main'
      } else {
        this.msgType = 'less'
      }
    },
    //根据主岗查询角色
    radioChange (val) {
      const { JobId } = this.mainData[val];
      this.radioCheck = JobId
      // if (val) {
      this.JobId = JobId;
      this.queryType = "job";
      this.treeId = JobId + "";
      this.isMainJob = true;
      if (this.openRole) {
        this.getRoleByJob(JobId, 1)
      } else if (this.OpenGroup) {
        this.getGroupByJob(JobId, 1)
      }
      // }
    },
    //副岗选中回调
    lessChecks (arr) {
      this.lessCheckData = arr
      this.isMainJob = false;
      const datas = [];
      let IDS = [];
      this.lessData.forEach((item, index) => {
        arr.forEach((p) => {
          if (p === index) {
            datas.push(item);
            IDS.push(item.JobId);
          }
        });
      });
      this.queryType = "job";
      this.treeId = IDS.toString();
      this.lessChecksData = datas;
      if (datas.length) {
        const { JobId } = datas[datas.length - 1];
        if (this.openRole) {
          this.getRoleByJob(JobId, 2)
        } else if (this.OpenGroup) {
          this.getGroupByJob(JobId, 2)
        }
      }
    },
    //根据岗位获取角色
    async getRoleByJob (id, index) {
      try {
        let params = {
          JobId: id,
        };
        const res = await jbdetpop(params);
        if (res.code === 0) {
          const datas = res.returnData;
          const arrs = [];
          datas.forEach((item) => {
            item.name = item.RoleName;
            if (item.IsSelected == 1) {
              arrs.push(item);
            }
          });
          if (index == 1) {
            this.arrs = arrs;
            this.lessCheckBoxs.push(arrs);
          } else if (index == 2) {
            if (arrs.length) {
              this.lessCheckBoxs.push(arrs);
              const msgs = this.lessCheckBoxs.flat();
              const uninqMsgs = _.unionBy(msgs, "RoleId");
              this.arrs = uninqMsgs;
            }
          }
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //根据组织查询岗位列表-主岗
    async getJobListByOrgan (id) {
      try {
        let params = {
          OrganId: id,
        };
        const res = await organgitpost(params);
        if (res.code === 0) {
          const datas = res.returnData;
          let obj = null;
          datas.forEach((item, index) => {
            item.name = item.JobName;
            if (item.JobId == this.radioCheck) {
              this.radioNum = index;
              obj = item;
            }
          });
          this.mainData = datas;
          if (datas.length && obj) {
            this.getGroupByJob(obj.JobId, 1);
          }
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //岗位列表查询-副岗
    async getJobList (name = "") {
      try {
        let params = {
          QueryName: name,
        };
        const res = await postList(params);
        if (res.code === 0) {
          const datas = res.returnData;
          const nums = [];
          datas.forEach((item, index) => {
            item.name = item.JobName;
            this.lessChecksData.forEach((p) => {
              if (item.JobId == p.JobId) {
                nums.push(index);
              }
            });
          });
          this.lessData = datas;
          this.checkBoxList = nums;
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //角色点击回调
    checkClick (item) {
      this.roleAuths(item.RoleId);
    },
    //岗位点击回调
    checkGroup (item) {
      this.groupAuths(item.GroupId)
    },
    //根据角色查看权限列表
    async roleAuths (id) {
      try {
        let params = {
          RoleId: id,
        };
        const res = await RoleAuths(params);
        if (res.code === 0) {
          this.RoleList = res.returnData;
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //角色选取
    checkChange (arr) {
      const datas = [];
      for (let i = 0; i < arr.length; i++) {
        datas.push(this.arrs[arr[i]]);
      }
      this.checkRoles = datas;
    },
    //获取权限规则
    getData (obj) {
      this.rulesObj = obj;
    },
    //获取登录策略回调
    getCheckedList (arr) {
      this.loginCheckBoxs = arr;
    },
    //保存
    saveBtn (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveOrgan();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //组织新增保存
    async saveOrgan () {
      try {
        if (!this.AppId) {
          this.$message.error("请选中一个组织后再新增");
          return false;
        }
        const datas = [];
        const checks = [];
        this.checkTrees.forEach((item) => {
          datas.push(item.AuthList);
        });
        this.checkRoles.forEach(item => {
          if (item) {
            checks.push(item);
          }
        });
        const res = await newstaffmod({
          OfficerName: this.form.name,
          OfficerDesc: this.form.app,
          OfficerLoginName: this.form.loginName,
          OfficerPwd: this.form.loginPwd,
          RoleList: this.openRole ? checks : [],
          AuthList: this.openRole ? [] : datas,
          TacList: this.loginCheckBoxs,
          DepJobList: this.lessChecksData,
          GroupList: this.OpenGroup ? checks : [],
          JobId: this.JobId,
          Status: Number(this.Status),
          OrganId: this.AppId,
          OfficerId: this.OfficerId,
        });
        if (res.code === 0) {
          this.$message.success(res.message);
          setTimeout(() => {
            this.$router.push("/staff");
          }, 2000);
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    reSetPassWord () {
      const { PwdLengthBegin, PwdLengthEnd, PwdStruc } =
        typeof this.systemSet === "string"
          ? JSON.parse(this.systemSet)
          : this.systemSet; //1是请求角色 0是请求用户
      this.form.loginPwd = pwdProduce(PwdLengthBegin, PwdLengthEnd, PwdStruc);
    },
  },
};
</script>

<style lang="scss" scoped>
.authorityPower {
  padding: 0 64px;
  padding-top: 32px;
}
.addApp-form {
  background: #ffffff;
  box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
  border-radius: 16px;
  padding: 32px 32px 40px 32px;
  .title {
    font-size: 24px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #303133;
    .isqy {
      span {
        font-weight: 400;
        font-size: 14px;
        margin: 0 28px 0 42px;
      }
    }
  }
  .addApp-form-content {
    margin-top: 40px;
    ::v-deep .form {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 40px;
        &:last-child {
          margin-right: 0;
        }
      }
      .el-input__inner {
        height: 32px;
        line-height: 32px;
        min-width: 184px;
      }
      .content {
        .el-form-item__content {
          flex: 1;
        }
        .el-form-item__label {
          margin-left: 27px;
        }
      }
    }
  }
}
.power-content {
  margin-top: 24px;
  min-height: 68vh;
  .part {
    height: 750px;
  }
}
</style>
