<!--
 * @Author: your name
 * @Date: 2021-11-29 11:26:07
 * @LastEditTime: 2022-01-17 10:04:48
 * @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="id" label="组织类型">
            <el-select v-model="form.id" placeholder="请选择">
              <el-option label="集团内" value="1"></el-option>
              <el-option label="集团外" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input style="width: 640px" 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" :data="data" nodekey="OrganId" :checkedKeys="checkedKeys" title="上级组织" />
      </div>
      <!--有角色-->
      <template v-if="openRole">
        <div class="r24 flex1 part">
          <Rolelist @checkChange="checkChange" @checkClick="checkClick" :checkBoxList="checkBoxList" :dataList="arrs" :active="true" class="hucRole" :number="8" title="角色列表" />
        </div>
        <div class="flex1 part">
          <Permissionlist :RoleList="RoleList" :check="true" class="hucPower" title="权限列表" />
        </div>
      </template>
      <!--有账号组-->
      <template v-else-if="OpenGroup">
        <div class="r24 flex1 part">
          <Rolelist @checkChange="checkChange" @checkClick="checkGroup" :checkBoxList="checkBoxList" :dataList="arrs" :active="true" class="hucRole" :number="8" title="权限组列表" />
        </div>
        <div class="flex1 part">
          <Permissionlist :RoleList="RoleList" :check="true" class="hucPower" title="权限列表" />
        </div>
      </template>
      <!--无角色-->
      <template v-else>
        <div class="r24 flex1 part">
          <Permissiontree :queryType="queryType" :queryId="OrganUpid" :checkedKeys="checkedBoxs" @nodeClick="nodeClick" @getTreeData="getTreeData" title="权限树" />
        </div>
        <div class="flex1 part">
          <Rulesofcompetency :authList="authList" :authTo="authTo" @getData="getData" 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 treeData from "../minixs/treeData";
import roleData from "../minixs/roleData";
import { mapGetters } from "vuex";
import { RoleAuths } from "@/api/apiAuthority";
import { newOrganmod, newOrganall } from "@/api/postInterface";
export default {
  name: "AuthorityPower",
  mixins: [treeData, roleData],
  components: {
    Rulesofcompetency,
    Organization,
    Permissiontree,
    Permissionlist,
    Rolelist,
  },
  data () {
    return {
      Status: null,
      AppId: null,
      form: {
        //应用表单
        name: "",
        id: "",
        app: "",
      },
      title: "角色",
      rules: {
        //表单验证
        name: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
        id: [{ required: true, message: "请输入标识符", trigger: "blur" }],
      },
      defaultProps: {
        children: "children",
        label: "OrganName",
      },
      queryType: null,
      checkBoxList: [], //角色列表选中
      Status: null,
      OrganUpid: null,
      checkedKeys: [], //上级组织选中
      RoleList: [],
      checkedBoxs: [],
      arrs: [],
      authId: [], //权限树默认选中ID
      authList: [],
      authTo: {},
      openRole: null,
      OpenGroup: null,
      dataObj: {}, //上级权限指定树数据
      data: [], //上级权限
      roleList: [], //角色
      checkRoles: [], //选中的角色
      checkTrees: [], //上级权限选中树数据
      rulesObj: {}, //权限规则数据
      upRoleList: [],
    };
  },
  computed: {
    ...mapGetters(["systemSet"]),
  },
  watch: {
    //监听上级组织数据
    dataList: {
      handler (val) {
        const arr = [val];
        this.decompose(arr, this.OrganUpid);
        if (Array.isArray(this.dataObj)) {
          if (this.dataObj.children) {
            delete this.dataObj.children;
          }
          this.data = this.dataObj;
        } else {
          if (this.dataObj.children) {
            delete this.dataObj.children;
          }
          this.data = [this.dataObj];
        }
        this.checkedKeys = [this.OrganUpid];
      },
      deep: true,
    },
    arrs: {
      handler (arr) {
        if (this.openRole) {
          this.defaultChecked(arr, "RoleId");
        } else if (this.OpenGroup) {
          this.defaultChecked(arr, "GroupId");
        }
      },
      deep: true,
    },
  },
  created () {
    const { OrganId, OrganUpid } = this.$route.query;
    const { OpenRole, OpenGroup } =
      typeof this.systemSet === "string"
        ? JSON.parse(this.systemSet)
        : this.systemSet; //1是请求角色 0是请求用户
    this.OrganUpid = OrganUpid;
    this.AppId = OrganId;
    this.openRole = OpenRole;
    this.OpenGroup = OpenGroup;
    this.getOrganTree();
    this.getOrganDetails(this.AppId);
    if (OrganUpid == -1) {
      if (this.openRole) {
        this.gueryRole();
        //this.getRoleByOrgan(this.OrganUpid)
      } else if (this.OpenGroup) {
        this.getGroupTree();
      }
      this.queryType = "all";
    } else {
      this.queryType = "origin";
      if (this.openRole) {
        this.getRoleByOrgan(this.OrganUpid);
      } else if (this.OpenGroup) {
        this.getGroupByOrgan(this.OrganUpid);
      }
    }
  },
  methods: {
    //获取选中的树数据
    getTreeData (arr) {
      this.checkTrees = arr;
    },
    //获取指定数据
    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);
        }
      }
    },
    // 默认选中
    defaultChecked (arr, id) {
      const datas = [];
      arr.forEach((item, index) => {
        this.checkRoles.forEach((p) => {
          if (item[id] == p[id]) {
            datas.push(index);
          }
        });
      });
      this.checkBoxList = datas;
    },
    //权限树点击
    nodeClick (obj) {
      const arr = this.$store.getters.authArrs;
      arr.push(obj);
      this.$store.dispatch("auth/changeAuthArrs", arr);
    },
    //角色点击回调
    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);
      }
    },
    //组织详情查询
    async getOrganDetails (id) {
      try {
        let params = {
          OrganId: id,
        };
        const res = await newOrganall(params);
        if (res.code === 0) {
          const {
            AuthList,
            OrganDesc,
            OrganName,
            OrganType,
            RoleList,
            Status,
            GroupList,
          } = res.returnData;
          this.form.name = OrganName;
          this.form.id = OrganType;
          this.form.app = OrganDesc;
          this.Status = Status;
          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);
            }
          }
        } 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]]);
      }
      datas.forEach((item) => {
        item.IsSelected = "1";
      });
      this.checkRoles = datas;
    },
    //获取权限规则
    getData (obj) {
      this.rulesObj = obj;
    },
    //保存
    saveBtn (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveOrgan();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //组织新增保存
    async saveOrgan () {
      try {
        const caps = [];
        const newDatas = [];
        const arr = this.$store.getters.authArrs;
        this.checkTrees.forEach((item) => {
          caps.push(item.AuthList);
        });
        arr.forEach((item) => {
          newDatas.push(item.AuthList);
        });
        const newMsg = newDatas.concat(caps);
        newMsg.forEach((item) => {
          item["AuthId"] = Number(item["AuthId"]);
        });
        const datas = _.unionBy(newMsg, "AuthId");
        const res = await newOrganmod({
          OrganName: this.form.name,
          OrganType: this.form.id,
          OrganDesc: this.form.app,
          OrganUpid: this.OrganUpid,
          OrganId: this.AppId,
          Status: this.Status,
          RoleList: this.openRole ? this.checkRoles : [],
          AuthList: this.openRole ? [] : datas,
          GroupList: this.OpenGroup ? this.checkRoles : [],
        });
        if (res.code === 0) {
          this.$message.success(res.message);
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push("/organization");
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
  },
};
</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;
      }
      .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;
  height: 704px;
  .part {
    height: 704px;
  }
}
</style>
