<!--
 * @Author: your name
 * @Date: 2021-11-29 16:31:31
 * @LastEditTime: 2022-03-02 13:51:29
 * @LastEditors: Please set LastEditors
 * @Description: 新增/编辑角色
 * @FilePath: \Foshan4A2.0\src\views\authorityManagement\components\authorityRoleStatus.vue
-->
<template>
  <div class="authorityPower">
    <!--新增权限项-->
    <div class="power-content flex-wrap">
      <div class="r24 flex1 part">
        <div style="padding: 27px 24px;height: 100%;" class="addApp-form">
          <div class="addApp-form-title flex">
            <div class="manageTitle">角色授权</div>
            <!-- <div class="title">
              编辑角色
              <span class="isqy">
                <span>是否启用</span>
                <el-radio v-model="radio" :label="1">是</el-radio>
                <el-radio v-model="radio" :label="0">否</el-radio>
              </span>
            </div> -->
            <!-- <div class="btn">
              <el-button @click="saveBtn('form')" size="small" type="primary">保存</el-button>
            </div> -->
          </div>
          <div class="addApp-form-content dialog-public-background">
            <el-form :inline="true" label-width="80px" ref="form" :rules="rules" class="form" :model="form">
              <el-form-item prop="role_name" label="角色名称">
                <el-input placeholder="请输入角色名称" maxlength="32" v-model="form.role_name" disabled></el-input>
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input style="width: 340px" type="textarea" :rows="3" maxlength="200" placeholder="请输入描述" v-model="form.role_comment" disabled></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="r24 flex1 part">
        <Permissiontree v-loading="loading" element-loading-text="数据加载中" @getTreeData="getTreeData" :checkedKeys="checkedKeys" title="权限树" />
      </div>
      <div class="flex1 part">
        <Rulesofcompetency v-loading="loading" element-loading-text="数据加载中" :authList="authList" :authTo="authTo" title="权限规则" />
      </div>
      <!-- <div class="flex1 part">
        <Rolelist
          v-is="['role_edit_mutually_exclusive']"
          v-loading="loading"
          element-loading-text="数据加载中"
          @checkChange="checkChange"
          @checkClick="checkClick"
          :roleType="roleType"
          :checkBoxList="radioCheck"
          :active="true"
          class="hucRole"
          :imageSize="80"
          :number="8"
          style="height: 280px; overflow: hidden"
          title="互斥角色"
        />
        <Permissionlist
          v-is="['role_edit_mutually_exclusive_list']"
          v-loading="permission"
          element-loading-text="数据加载中"
          :check="true"
          :imageSize="80"
          :RoleList="RoleList"
          class="hucPower"
          style="margin-top: 24px"
          title="互斥角色已有权限列表"
        />
      </div> -->
    </div>
  </div>
</template>

<script>
import Permissionlist from "@/components/permissionlist";
import Rulesofcompetency from "@/components/rulesofcompetency";
import Permissiontree from "@/components/permissiontree";
import Rolelist from "@/components/rolelist";
import { RoleDetails, EditRole, RoleAuths } from "@/api/apiAuthority";
import { Query, GeneralDataReception } from "@/api/dataIntegration";
import roleData from "../minixs/roleData";
import { mapGetters } from 'vuex'
export default {
  name: "AuthorityRoleEdit",
  components: { Permissionlist, Rulesofcompetency, Permissiontree, Rolelist },
  mixins: [roleData],
  data () {
    return {
      radio: 1,
      form: {
        //应用表单
        role_name: "",
        role_comment: "",
      },
      rules: {
        //表单验证
        role_name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      loading: false,
      permission: false,
      treeData: [],
      arrs: [],
      checkedKeys: [],
      RoleList: [],
      radioCheck: [],
      checkedBoxs: [],
      defRoleId: [],
      roleId: null,
      Status: null,
      authTo: {},
      authList: [],
      authId: [],
      msgArrs: [],
      type: null, //参数类型
      roleType: "",
      msgIndex: 0
    };
  },
  created () {
    //this.getAuthTree();
    const { RoleId } = this.$route.query;
    this.roleId = RoleId;
    this.roleDetails(RoleId);
    this.roleAuths(RoleId);
  },
  mounted () {
    this.roleType = "onlyRole";
  },
  computed: {
    ...mapGetters['authArrs']
  },
  methods: {
    //角色明细
    async roleDetails (id = '') {
      try {
        this.loading = true;
        const res = await Query({
          id: DATACONTENT_ID.roleDetailsId,
          dataContent: [id]
        });
        if (res.code == 0) {
          this.form = res.returnData.listValues[0];
          this.loading = false;
        } else {
          this.$message.error(res.message);
          this.loading = false;
        }
      } catch (error) {
        console.log("出错了", error);
        this.loading = false;
      }
    },
    //删除
    removeRole () {
      this.deleteRole(this.roleId);
    },
    //获取权限树回调
    getTreeData (arr) {
      this.treeData = arr;
      this.msgArrs.push(arr);
      const data1 = this.msgArrs[this.msgArrs.length - 1] //最后一条数据
      const data2 = this.msgArrs[this.msgArrs.length - 2] //倒数第二条数据
      if (data1.length >= data2.length) {
        this.checksBoxTs(data1, data2, 'add')
      } else {
        this.checksBoxTs(data2, data1, 'del')
        setTimeout(() => {
          location.reload()
        }, 1500);
      }
    },
    //获取权限规则回调
    getData (obj) {
      this.authTo = obj;
    },
    //互斥角色选中回调
    checkChange (arr) {
      const arrs = [];
      arr.forEach((item) => {
        const obj = {
          DefRoleId: item.RoleId,
          IsSelected: 1,
          DefRoleName: item.RoleName,
        };
        arrs.push(obj);
      });
      this.checkedBoxs = arrs;
    },
    async roleAuths (id) {
      try {
        const res = await Query({
          id: DATACONTENT_ID.roleAuthId,
          dataContent: [id]
        });
        if (res.code == 0) {
          this.checkedKeys = [];
          const { listValues } = res.returnData
          if (listValues && listValues.length) {
            this.authList = listValues;
            this.authTo = listValues[0];
            listValues.forEach((item) => {
              const obj = item
              obj.auth_id = item.auth_id
              this.checkedBoxs.push(item)
              this.checkedKeys.push(item.auth_id)
            });
            // this.msgArrs.push([])
          }
          this.msgArrs.push(this.checkedBoxs)
        } else {
          this.$message.error(res.message);
          this.loading = false;
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
    //保存
    saveBtn (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data1 = this.msgArrs[this.msgArrs.length - 1] //最后一条数据
          const data2 = this.msgArrs[this.msgArrs.length - 2] //倒数第二条数据
          if (data1.length > data2.length) {
            this.checksBoxTs(data1, data2, 'add')
          } else {
            this.checksBoxTs(data2, data1, 'del')
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async checksBoxTs (datas, arr, type) {
      const res = [...datas, ...arr].filter(item => !(datas.some(p => item.auth_id == p.auth_id) && arr.some(c => item.auth_id == c.auth_id)))
      const [msg1, msg2] = [[], []]
      if (res && res.length) {
        for (let i = 0; i < res.length; i++) {
          let obj = {
            auth_id: res[i].auth_id || res[i].AuthId,
            role_id: this.roleId
          }
          let authObj = res[i].AuthList ? Object.assign(_.cloneDeep(obj), res[i].AuthList) : Object.assign(_.cloneDeep(obj), res[i])
          if (type == 'add') {
            if (authObj.QueryRow) {
              authObj.query_row_condition = authObj.QueryRow
            }
            if (authObj.QueryCol) {
              authObj.query_col_conditon = authObj.QueryCol
            }
            if (authObj.NewCol) {
              authObj.new_col_condition = authObj.NewCol
            }
            if (authObj.EditCol) {
              authObj.edit_col_condition = authObj.EditCol
            }
            if (authObj.EditRow) {
              authObj.edit_row_condition = authObj.EditRow
            }
            if (authObj.DeleteRow) {
              authObj.delete_row_condition = authObj.DeleteRow
            }
            obj.event = 1
            authObj.event = 1
            msg1.push(obj)
            msg2.push(authObj)
          } else {
            obj.event = 3
            authObj.event = 3
            msg1.push(obj)
            msg2.push(authObj)
            // const authList = this.$store.getters.authList;
            // authList.forEach((item, index) => {
            //   msg2.forEach(p => {
            //     if (item.auth_id == p.auth_id) {
            //       authList.splice(index, 1)
            //     }
            //   })
            // })
            // this.$store.dispatch("auth/changeAuthMsg", authList);
            // this.$store.dispatch("auth/changeAuthList", authList);
          }
        }
        GeneralDataReception({
          serviceId: SERVICE_ID.roleMsgTreeId,
          dataContent: JSON.stringify(msg1)
        }).then(result => {
          if (result.code == 0) {
            if (type == 'add') {
              this.$message.success('添加权限', res.message)
            } else {
              this.$message.success('取消权限', res.message)
            }
          } else {
            if (type == 'add') {
              this.$message.error('添加权限', res.message)
            } else {
              this.$message.error('取消权限', res.message)
            }
          }
        })
        GeneralDataReception({
          serviceId: SERVICE_ID.roleMsgAuthId,
          dataContent: JSON.stringify(msg2)
        }).then(result => {
          if (result.code == 0) {
            if (type == 'add') {
              this.$message.success('添加规则', res.message)
            } else {
              this.$message.success('取消规则', res.message)
            }
          } else {
            if (type == 'add') {
              this.$message.error('添加规则', res.message)
            } else {
              this.$message.error('取消规则', res.message)
            }
          }
        })
      } else {
        // this.$message.error('未选中数据')
      }
    },
    //确认保存
    async editRole () {
      try {
        const datas = [];
        this.treeData.forEach((item) => {
          datas.push(item.AuthList);
        });
        const res = await EditRole({
          RoleName: this.form.name,
          RoleDesc: this.form.app,
          DefRoleList: this.checkedBoxs,
          AuthList: datas,
          RoleStatus: this.radio,
          RoleId: this.roleId,
        });
        if (res.code === 0) {
          this.$message.success(res.message);
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push("/role");
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.log("出错了", error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../css/role.scss";
</style>
