<!--
 * @Author: your name
 * @Date: 2022-02-10 14:49:20
 * @LastEditTime: 2022-03-16 15:14:16
 * @LastEditors: your name
 * @Description: 编辑职员
 * @FilePath: \Foshan4A4.0\src\views\staffManagement\compontents\staffEdit.vue
-->
<template>
  <div class="authorityPower">
    <!--编辑职员-->
    <div class="addApp-form">
      <div class="addApp-form-title flex">
        <div class="title">新增职员</div>
        <div v-is="['officer_btn_save']" 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="请输入职员名称" v-model.trim="form.name"></el-input>
          </el-form-item>
          <el-form-item prop="loginName" label="职员登录名">
            <el-input placeholder="请输入职员登录名" v-model.trim="form.loginName"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="职员手机号">
            <el-input placeholder="请输入职员手机号" v-model.trim="form.phone"></el-input>
          </el-form-item>
          <el-form-item prop="loginPwd" style="margin-right: 16px" label="登录密码">
            <el-input placeholder="*******" disabled v-model="form.loginPwd"></el-input>
          </el-form-item>
          <el-form-item v-is="['officer_btn_resetpwd']">
            <el-button size="small" type="primary" @click="reSetPassWord">{{ doesPwdExist ? '重置' : '生成' }}密码</el-button>
          </el-form-item>
          <el-form-item prop="desc" label="描述">
            <el-input class="lastInput" placeholder="请输入描述" v-model.trim="form.desc"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="power-content flex-wrap">
      <div class="r24 flex1 part">
        <Organization ref="Organization" :defaultProps="defaultProps" :vice="true" :data="data" @getTreeData="getOrgan" @getTreeDataDuo="getTreeDataDuo" :checkedKeys="orgCheckedKeys" nodekey="OrganId" title="选择组织" />
      </div>
      <!--开启多对多-->
      <template v-if="OpenAuthData">
        <div class="flex1 part">
          <Rolelist @checkChange="accountChange" :checkBoxList="checkBoxList" :roleType="roleType" :active="true" class="hucRole" :number="4" title="账号列表" />
        </div>
      </template>
      <!--未开启多对多-->
      <template v-else>
        <!--有岗位 无角色-->
        <template v-if="OpenGroup && !openRole">
          <div class="r24 flex1 part">
            <Usergroup @getTreeData="getUserGroup" :checkedKeys="userGroupKeys" :title="`${accountGroupType}树`" />
          </div>
          <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)" :imageSize="20" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
          </div>
        </template>
        <!--有角色 无岗位-->
        <template v-if="openRole && !OpenGroup">
          <div class="r24 flex1 part">
            <Rolelist @checkChange="checkChange" :imageSize="120" @checkClick="checkClick" :roleType="roleType" :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% - 24px - 376px)" :imageSize="120" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
          </div>
        </template>
        <!--有角色 有岗位-->
        <template v-if="openRole && OpenGroup">
          <div class="r24 flex1 part">
            <Usergroup @getTreeData="getUserGroup" :checkedKeys="userGroupKeys" :title="`${accountGroupType}树`" />
          </div>
          <div class="r24 flex1 part">
            <Rolelist @checkChange="checkChange" @role-list-change="roleChange" :imageSize="120" needType="1" :GroupIds="GroupIds" @checkClick="checkClick" :roleType="roleType" :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% - 24px - 376px)" :imageSize="120" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
          </div>
        </template>
        <!--无岗位 无角色-->
        <template v-if="!OpenGroup && !openRole">
          <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)" :imageSize="20" :checkedList="checkedList" @getCheckedList="getCheckedList" title="登录策略" />
          </div>
        </template>
      </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 Usergroup from "@/components/msgTree";
import treeData from "../minixs/treeData";
import { mapGetters } from "vuex";
import { RoleAuths } from "@/api/apiAuthority";
import {
  newstaff,
  organgitpost,
} from "@/api/postInterface";
import { pwdProduce } from "@/utils/validate";
import { lengthValidator, regular } from '@/utils/validate';
export default {
  name: "AuthorityPower",
  mixins: [treeData],
  components: {
    Rulesofcompetency,
    Organization,
    Permissiontree,
    Permissionlist,
    Rolelist,
    Loginpolicy,
    Usergroup
  },
  data () {
    return {
      Status: 1,
      AppId: null,
      form: {
        //应用表单
        name: "",
        loginName: "",
        loginPwd: "",
        desc: "",
        phone: ""
      },
      title: "角色",
      rules: {
        //表单验证
        name: [
          { required: true, message: "请输入职员名称", trigger: "blur" },
          { validator: lengthValidator, max: 128, message: '长度在 1 到 128 个字符', trigger: ['change', 'blur'] }
        ],
        loginName: [
          { required: true, message: "请输入职员登录名", trigger: "blur" },
          { pattern: regular.name, message: regular.nameMessage, trigger: ['change', 'blur'] },
          { validator: lengthValidator, max: 32, message: '长度在 1 到 32 个字符', trigger: ['change', 'blur'] },
        ],
        phone: [
          { pattern: regular.integer, message: '请输入纯数字', trigger: ['blur', 'change'] },
          { validator: lengthValidator, min: 11, max: 11, message: '请输入11位电话号码', trigger: ['change', 'blur'] }
        ],
        desc: [
          { validator: lengthValidator, max: 256, message: '长度在 1 到 256 个字符', trigger: ['change', 'blur'] },
        ],
        loginPwd: [
          { required: true, message: "请生成职员登录密码" }
        ],
      },
      defaultProps: {
        children: "children",
        label: "OrganName",
      },
      treeId: null, //根据组织获取权限树的组织ID
      checkedKeys: [], //上级组织选中
      RoleList: [],
      checkedBoxs: [],
      arrs: [],
      authArrs: [],//
      OfficerId: null,
      authId: [], //权限树默认选中ID
      authList: [],
      authTo: {},
      orgTypes: [],
      checkBoxList: [], //副岗默认选中
      checkedList: [], //登录策略默认选中的数据
      radioCheck: null, //主岗默认选中
      radioNum: null, //主岗已选中
      roleDatas: [], //接口详情返回的角色列表数据
      roleCheckBoxs: [], //角色列表默认选中数据
      groupCheckBoxs: [], //权限组列表默认选中数据
      orgCheckedKeys: [], //组织树默认选中
      loginCheckBoxs: [], //登录策略数据
      mainData: [], //主岗数据
      JobId: "", //选中主岗ID
      DepJobIds: [],//选中副岗ID集合
      lessData: [], //副岗数据
      lessCheckBoxs: [], //副岗选中数据联合主岗
      lessChecksData: [], //副岗选中数据
      queryType: null, //权限树类型
      openRole: null,
      OpenGroup: null,
      OpenAuthData: null,
      roleType: '',
      dataObj: {}, //上级权限指定树数据
      data: [], //上级权限
      roleList: [], //角色
      checkRoles: [], //选中的角色
      checkTrees: [], //上级权限选中树数据
      rulesObj: {}, //权限规则数据
      isMainJob: true, //是否主岗
      oldOrganId: "",
      OrganId: null,
      onCheckedArr: [],//当前显示选中权限组
      alljobArr: [],//全部岗位
      GroupIds: [], //当前选中的用户组
      userGroupKeys: [], //当前回调选中的用户组
      doesPwdExist: false
    };
  },
  computed: {
    ...mapGetters(["systemSet"]),
  },
  watch: {
    //监听上级组织数据
    dataList: {
      handler (val) {
        if (this.orgTypes == 'org') {
          this.orgCheckedKeys = [this.OrganId];
          // this.getJobListByOrgan(this.OrganId);
        }
        const arr = [val];
        this.decompose(arr);
        this.data = arr;
      },
      deep: true,
    },
    mainData: {
      handler (arr) {
        if (this.radioCheck) {
          let ids = null;
          arr.forEach((item, index) => {
            if (item.JobId == this.radioCheck) {
              ids = index;
            }
          })
          this.radioNum = ids;
        }
      },
      deep: true,
    }
  },
  created () {
    const { OrganId, Status, OfficerId, orgType } = this.$route.query;
    const { OpenRole, PwdLengthBegin, PwdLengthEnd, PwdStruc, OpenGroup, UserOfficerMulti } =
      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;
    this.OpenAuthData = UserOfficerMulti;
    this.OrganId = OrganId;
    this.AppId = OrganId;
    this.orgTypes = orgType;
    if (OpenGroup || !OpenGroup && !OpenRole) {
      this.queryType = "all";
    }
  },
  mounted () {
    if (this.OpenAuthData) {
      this.roleType = 'account';
    }
    if (this.openRole && !this.OpenGroup) {
      this.roleType = 'onlyRole';
    } else {
      this.roleType = 'q';
    }
  },
  methods: {
    //获取选中的树数据
    getTreeData (arr) {
      this.checkTrees = arr;
    },
    //获取组织选中的数据-单选
    getOrgan (arr) {
      const { OrganId } = arr[0];
      this.AppId = OrganId;
      this.getJobListByOrgan(OrganId);
    },
    //获取组织选中的数据-多选
    getTreeDataDuo (arr) {
      this.lessData = arr;
    },
    //获取指定数据
    decompose (data, id) {
      for (let i = 0; i < data.length; i++) {
        data[i]['status'] == 1 ? '' : data[i]['disabled'] = true;
        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);
    },
    //根据主岗查询角色
    radioChange (val) {
      const { JobId } = this.mainData[val];
      this.JobId = JobId;
      this.radioCheck = null;
    },
    //根据组织查询岗位列表-主岗
    async getJobListByOrgan (id) {
      try {
        let params = {
          OrganId: id,
        };
        const res = await organgitpost(params);
        if (res.code === 0) {
          const datas = res.returnData;
          datas.forEach((item) => {
            item.name = item.JobName;
          });
          this.mainData = datas;
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //角色点击回调
    checkClick (item) {
      this.roleAuths(item.RoleId);
    },
    //用户组选中回调
    getUserGroup (arr) {
      const datas = [];
      arr.forEach(item => {
        datas.push(item.GroupId);
      })
      this.GroupIds = datas;
    },
    //岗位点击回调
    checkGroup (item) {
      this.groupAuths(item.GroupId)
    },
    roleChange () {
      this.checkRoles = []
    },
    //根据角色查看权限列表
    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);
      }
    },
    //账号列表选取
    accountChange (arr) {
      this.checkBoxList = arr;
    },
    //角色选取
    checkChange (arr) {
      this.checkRoles = arr;
      this.onCheckedArr = arr;
    },
    //获取权限规则
    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.JobId) {
        //   if (!this.AppId) {
        //     this.$message.error("请选中一个组织后再新增");
        //     return false;
        //   }
        // }
        const datas = [];
        const checks = [];
        const GroupIds = [];
        const arrs = [];
        if (this.checkTrees.length) {
          this.checkTrees.forEach((item) => {
            datas.push(item.AuthList);
          });
        }
        if (this.GroupIds.length) {
          this.GroupIds.forEach(item => {
            const obj = {
              GroupId: item
            }
            GroupIds.push(obj);
          });
        }
        if (this.checkRoles.length) {
          this.checkRoles.forEach(item => {
            item.IsSelected = 1;
            checks.push(item);
          });
        }
        if (this.lessData.length) {
          this.lessData.forEach(item => {
            const obj = {
              JobId: item.OrganId || item.organId
            }
            arrs.push(obj);
          });
        }
        const res = await newstaff({
          OfficerName: this.form.name,
          OfficerDesc: this.form.desc,
          OfficerLoginName: this.form.loginName,
          OfficerPwd: this.form.loginPwd,
          Phone: this.form.phone,
          RoleList: checks.length ? checks : [],
          AuthList: this.openRole ? [] : datas,
          TacList: this.loginCheckBoxs,
          GroupList: GroupIds.length ? GroupIds : [],
          JobId: this.JobId,
          DepJobList: arrs.length ? arrs : [],
          Status: 1,
          OrganId: this.AppId,
          OfficerId: this.OfficerId,
          UserList: this.OpenAuthData ? this.checkBoxList : []
        });
        if (res.code === 0) {
          this.$message.success(res.message);
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push("/staff");
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    reSetPassWord () {
      !this.doesPwdExist && (this.doesPwdExist = true)
      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: 30px;
        &:last-child {
          margin-right: 0;
        }
      }
      .el-input__inner {
        height: 32px;
        line-height: 32px;
        width: 150px;
      }
      .content {
        .el-form-item__content {
          flex: 1;
        }
        .el-form-item__label {
          margin-left: 27px;
        }
      }
      .lastInput {
        width: 27vw;
        .el-input__inner {
          width: 100%;
        }
      }
    }
  }
}
.power-content {
  margin-top: 24px;
  min-height: 68vh;
  .part {
    height: 750px;
    // ::v-deep .paren_content {
    //   height: 85%;
    //   .cont > .paren_content {
    //     height: 100% !important;
    //   }
    // }
  }
}
</style>