<!--
 * @Author: your name
 * @Date: 2021-11-29 11:26:07
 * @LastEditTime: 2022-04-11 14:35:27
 * @LastEditors: your name
 * @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 v-is="['organ_btn_edit']" 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="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 prop="desc" label="描述">
            <el-input style="width: 835px" placeholder="请输入描述" v-model.trim="form.desc"></el-input>
          </el-form-item>
          <div class="top24">
            <el-form-item class="oneCode" prop="oneCode" label="1级编码">
              <el-input placeholder="请输入编码" v-model.trim="form.oneCode"></el-input>
            </el-form-item>
            <el-form-item prop="twoCode" class="twoCode" label="2级编码">
              <el-input placeholder="请输入编码" style="width: 202px" v-model.trim="form.twoCode"></el-input>
            </el-form-item>
            <el-form-item prop="threeCode" label="3级编码">
              <el-input placeholder="请输入编码" v-model.trim="form.threeCode"></el-input>
            </el-form-item>
            <el-form-item prop="fourCode" label="4级编码">
              <el-input placeholder="请输入编码" v-model.trim="form.fourCode"></el-input>
            </el-form-item>
            <el-form-item prop="fiveCode" label="5级编码">
              <el-input placeholder="请输入编码" v-model.trim="form.fiveCode"></el-input>
            </el-form-item>
            <el-form-item prop="bmCode" label="编码类型">
              <el-input placeholder="请输入编码类型" v-model.trim="form.bmCode"></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="power-content flex-wrap">
      <div class="flex1 part">
        <Organization :defaultProps="defaultProps" :data="data" node-key="OrganId" up-node-key="OrganUpid" @getTreeData="getTreeData" :checkedKeys="checkedKeys" :orgList="orgList" title="上级组织" />
      </div>
    </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";
import { lengthValidator, checkDx } from '@/utils/validate'
export default {
  name: "AuthorityPower",
  mixins: [treeData, roleData],
  components: {
    Rulesofcompetency,
    Organization,
    Permissiontree,
    Permissionlist,
    Rolelist,
  },
  data () {
    return {
      Status: null,
      AppId: null,
      form: {
        //应用表单
        name: "",
        id: "",
        desc: "",
        oneCode: "",
        twoCode: "",
        threeCode: "",
        fourCode: "",
        fiveCode: "",
        bmCode: ""
      },
      title: "角色",
      rules: {
        //表单验证
        name: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
          { validator: lengthValidator, max: 128, message: '长度在 1 到 128 个字符', trigger: ['change', 'blur'] }
        ],
        id: [{ required: true, message: "请输入标识符", trigger: "blur" }],
        desc: [{ validator: lengthValidator, max: 256, message: '长度在 1 到 256 个字符', trigger: ['change', 'blur'] }],
        oneCode: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
          { validator: lengthValidator, max: 2, message: '长度在 1 到 2 个字符', trigger: ['change', 'blur'] }],
        twoCode: [{ validator: lengthValidator, max: 3, message: '长度在 1 到 3 个字符', trigger: ['change', 'blur'] }],
        threeCode: [{ validator: lengthValidator, max: 8, message: '长度在 1 到 8 个字符', trigger: ['change', 'blur'] }],
        fourCode: [{ validator: lengthValidator, max: 2, message: '长度在 1 到 2 个字符', trigger: ['change', 'blur'] }],
        fiveCode: [{ validator: lengthValidator, max: 2, message: '长度在 1 到 2 个字符', trigger: ['change', 'blur'] }],
        bmCode: [
          { validator: lengthValidator, max: 1, message: '长度在 1 个字符', trigger: ['change', 'blur'] },
          { validator: checkDx, trigger: ['change', '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: [],
      orgList: []
    };
  },
  computed: {
    ...mapGetters(["systemSet"]),
  },
  watch: {
    //监听上级组织数据
    dataList: {
      handler (val) {
        const arr = [val];
        // this.data = arr;
        this.decompose(arr, this.AppId);
        this.data = arr;
        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);
  },
  methods: {
    //获取选中的树数据
    getTreeData (arr) {
      if (arr.length === 1) {
        const { OrganId } = arr[0];
        this.OrganUpid = OrganId;
      } else if (arr.length === 0) {
        this.OrganUpid = -1
      }
    },
    //获取指定数据
    decompose (data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].OrganId == id) {
          if (data[i].children && data[i].children.length) {
            data.splice(i, 1);
          } else {
            data.splice(i, 1);
          }
          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,
            L1,
            L2,
            L3,
            L4,
            L5,
            Type
          } = res.returnData;
          this.form.name = OrganName;
          this.form.id = Number(OrganType);
          this.form.desc = OrganDesc;
          this.form.oneCode = L1;
          this.form.twoCode = L2;
          this.form.threeCode = L3;
          this.form.fourCode = L4;
          this.form.fiveCode = L5;
          this.form.bmCode = Type;
          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.desc,
          OrganUpid: this.OrganUpid,
          OrganId: this.AppId,
          Status: this.Status,
          RoleList: this.openRole ? this.checkRoles : [],
          AuthList: this.openRole ? [] : datas,
          GroupList: this.OpenGroup ? this.checkRoles : [],
          L1: this.form.oneCode,
          L2: this.form.twoCode,
          L3: this.form.threeCode,
          L4: this.form.fourCode,
          L5: this.form.fiveCode,
          Type: this.form.bmCode
        });
        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;
      }
      .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;
        }
      }
      .top24 {
        margin-top: 24px;
        .el-form-item__label {
          margin-left: 16px;
        }
        .oneCode {
          .el-form-item__label {
            margin-left: 0px;
          }
        }
      }
    }
  }
}
.power-content {
  margin-top: 24px;
  height: 704px;
  .part {
    height: 704px;
  }
}
</style>
