<template>
  <div class="appMainPage">
    <el-row :gutter="24">
      <el-col :md="16" style="margin-bottom: 10px">
        <div class="main">
          <div class="table-active">
            <div class="bttton-box">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="handleCreate"
                size="mini"
                v-permission="['AbpIdentity.Roles.Create']"
                >创建角色</el-button
              >
              <el-button
                type="success"
                icon="el-icon-refresh"
                @click.native.prevent="Createview"
                size="mini"
                >刷新</el-button
              >
            </div>
            <div class="query-box">
              <!-- 搜索 -->
              <searchNormal 
                ref="normalSearch_roleManage"
                @searchNormalClick="filtrate"
                @searchNormalClear="filtrate"
              ></searchNormal>
            </div>
          </div>
          <el-table
            border=""
            ref="multipleTable"
            :data="tableData"
            height="calc(100vh - 265px)"
            style="width: 100%"
            @sort-change="sortChange"
            @row-click="handleRowClick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              prop="name"
              label="角色名"
              sortable="custom"
              width="180"
              align="left"
            />
            <el-table-column
              prop="extraProperties.Description"
              label="角色描述"
              align="left"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="Update(scope.row)"
                  v-permission="['AbpIdentity.Roles.Update']"
                  v-if="scope.row.name == 'admin' ? false : true"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  @click="Delete(scope.row)"
                  v-permission="['AbpIdentity.Roles.Delete']"
                  v-if="scope.row.name == 'admin' ? false : true"
                  style="color:red"
                  >删除</el-button
                >
              </template>
            </el-table-column>
            <!-- <el-table-column prop="address" label="创建时间" />
        <el-table-column prop="address" label="编辑" /> -->
          </el-table>
        </div>
        <div class="Footer">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.currentPage"
            :page-sizes="[10, 15, 20]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
          <el-button
            type="primary"
            size="mini"
            style="margin-left: 10px; background-color: #409eff"
            >确定</el-button
          >
        </div>
      </el-col>
      <el-col :md="8" v-permission="['AbpIdentity.Roles.Update']">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix" style="height: 20px">
            <el-tooltip
              class="item"
              effect="dark"
              content="选择指定角色的模块权限"
              placement="top"
            >
              <span class="role-span">【{{name}}角色】模块权限</span>
            </el-tooltip>
            <el-button
              :loading="savePerLoading"
              :disabled="multipleSelection.length != 1"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePer"
              >保存
            </el-button>
          </div>
          <el-tree
            ref="tree"
            v-loading="treeLoading"
            :check-strictly="false"
            :data="permissionsData"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      :title="formTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="70px"
        :rules="rules"
        size="small"
        :inline="true"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" style="width: 380px" maxlength="23" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入描述信息"
            style="width: 380px"
            v-model="form.extraProperties.Description"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetform">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  postCreateRoles,
  postUpdateRoles,
  postDeleteRoles,
  getPageListRoles,
  getpermissionsRoles,
  putpermissionsRoles,
  menuPermissions,
  saveOrUpdateDescribe
} from "@/api/wms-auth";
import permission from "@/utils/permission/index";
import searchNormal from "@/components/searchNormal/index.vue"
export default {
  directives: { permission },
  components:{
    searchNormal
  },
  name:"RoleManage",
  data() {
    // 自定义验证
    return {
      URL: 'identity/roles',
      // 角色名称
      name: '',
      //所有权限
      rolesAll: [],
      //编辑弹出
      dialogVisible: false,
      //创建与编辑判断
      isEdit: false,
      //弹出title
      formTitle: "",
      //总条数
      total: 0,
      //分页器
      queryInfo: {
        //当前页数
        currentPage: 1,
        //每页条数
        pagesize: 20,
        Sorting: "",
      },
      //   Thecurrent: '',
      //选择添加分组
      //筛选栏分组
      //   value1: '',
      //报表组
      //   roleList: [],
      //当前用户ID
      usersId: "",
      //编辑参数
      concurrencyStamp: "",
      //新增参数
      form: {
        name: "",
        isDefault: true,
        isPublic: true,
        extraProperties: {
          Description: "",
        },
      },
      //权限模板保存按钮加载
      savePerLoading: false,
      //权限模板树形控件加载
      treeLoading: false,
      //权限模板树形控件默认勾选的数组
      checkedPermission: [],
      //权限模板树形结构渲染数据
      permissionsData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      //渲染权限模板参数
      params: {
        providerName: "R",
        providerKey: "",
      },
      //选择行数据
      multipleSelection: [],
      //table渲染
      tableData: [],
      rules: {
        name: [
          { required: true, trigger: "blur", message: "请输入姓名" },
          {
            min: 1,
            max: 23,
            message: "长度在 1 到 23 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.pageList();
  },
  methods: {
    //sort 按照排序字段(现在为数字)  默认sort
    sortData(sort){
      return function(a,b){
          const val1 = a[sort];
          const val2 = b[sort];
          return val1 - val2;
      }
    },
     // 树状图格式化数据
     initTreeData(list,code = ""){
      const children = []
      // 对于list,每个元素.如果他的parentCode==code,他就是当前的children
      list.forEach(item => {
        if (item['parentCode'] == code) {
          // children.push(item)
          children.push(
            {
              id: item.id,
              displayName: item.permission,
              name: item.name,
              parentCode: item.parentCode,
              code: item.code,
              sort: item.sort,
              children: []
            }
          )
          //排序
          children.find(findItem => findItem.id == item.id).children=this.initTreeData(list,item['code']).sort(this.sortData('sort'))
          this.rolesAll.forEach(itemRes => {
            if (item.permission == itemRes.name) {
              if (itemRes.isGranted) {
                this.checkedPermission.push(item.id);
              }
            }
          })
        }
      })
      return children
    },
    //请求数据渲染table
    pageList(val) {
      const data = {
        Filter: val || '',
        Sorting: this.queryInfo.Sorting,
        SkipCount: (this.queryInfo.currentPage - 1) * this.queryInfo.pagesize,
        MaxResultCount: this.queryInfo.pagesize,
      };
      getPageListRoles(data).then((res) => {
        const data = res;
        this.total = data.totalCount;
        this.tableData = data.items;
      });
    },
    //排序
    sortChange(data) {
      const { prop, order } = data;
      if (!prop || !order) {
        this.queryInfo.Sorting = "";
        this.handleFilter();
        return;
      }
      this.queryInfo.Sorting = prop + " " + order;
      // alert(this.listQuery.Sorting)
      this.handleFilter();
    },
    //排序触发页面更新
    handleFilter() {
      this.queryInfo.currentPage = 1;
      this.pageList();
    },
    //筛选
    filtrate(val) {
      this.queryInfo.currentPage = 1;
      this.pageList(val);
    },
    //选择每页条数分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.pageList();
    },
    //选择当前页分页
    handleCurrentChange(val) {
      this.queryInfo.currentPage = val;
      this.pageList();
    },
    //重置创建与编辑后的参数
    resetform() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.form.name = "";
      this.form.extraProperties.Description = "";
      this.$refs.multipleTable.clearSelection();
    },
    //创建角色
    handleCreate() {
      this.formTitle = "创建角色";
      this.dialogVisible = true;
      this.isEdit = false;
    },
    //刷新
    Createview() {
      this.queryInfo.currentPage = 1;
      this.queryInfo.Sorting = "";
      this.$refs.normalSearch_roleManage.searchNormalClear()//清空搜索
      this.$refs.multipleTable.clearSort();
    },
    //编辑默认参数
    Update(row) {
      if (row) {
        this.formTitle = "编辑角色";
        this.dialogVisible = true;
        this.isEdit = true;
        this.usersId = row.id;
        this.form.name = row.name;
        this.concurrencyStamp = row.concurrencyStamp;
        this.form.extraProperties.Description = row.extraProperties.Description;
      }
    },
    //删除
    Delete(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.tableData.length == 1) {
            this.queryInfo.currentPage = this.queryInfo.currentPage - 1;
          }
          postDeleteRoles(row.id).then((res) => {
            this.$successMsg("删除成功！");
            this.pageList();
          });
        })
        .catch(() => {});
    },
    //创建与编辑
    submitForm() {
      this.$refs.form.validate((valid) => {
        //创建报表组
        if (valid && !this.isEdit) {
          postCreateRoles(this.form)
            .then((res) => {
              this.saveOrUpdateDescribe(res.id)
              this.resetform();
              this.$successMsg("创建成功！");
              this.queryInfo.currentPage = 1;
              this.pageList();
            })
            .catch((err) => {
              this.resetform();
            });
        } else if (valid && this.isEdit) {
          //编辑报表
          const data = JSON.parse(JSON.stringify(this.form));
          data.concurrencyStamp = this.concurrencyStamp;
          postUpdateRoles(data, this.usersId)
            .then((res) => {
              this.$successMsg("编辑成功！");
              this.saveOrUpdateDescribe(this.usersId)
              this.pageList();
              this.resetform();
            })
            .catch((err) => {
              this.resetform();
            });
        } else {
          this.$errorMsg("请按照提示继续输入！");
          return false;
        }
      });
    },
    // 描述特殊储存处理
    saveOrUpdateDescribe (id) {
      saveOrUpdateDescribe({description:this.form.extraProperties.Description}, id).then(res => {
        // console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //模板权限保存
    savePer() {
      this.savePerLoading = true;
      let params = {};
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      params.permissions = [];
      this.permissionsData.forEach((element) => {
        element.children.forEach((item) => {
          let perm = {};
          perm.name = item.displayName;
          perm.isGranted = false;
          if (checkedKeys.indexOf(item.id) > -1) {
            perm.isGranted = true;
          }
          // 赋值节点下的增删改权限
          this.getZSG(item.displayName, params, perm.isGranted)
          params.permissions.push(perm);
          item.children.forEach((i) => {
            let perm = {};
            perm.name = i.displayName;
            perm.isGranted = false;
            if (checkedKeys.indexOf(i.id) > -1) {
              perm.isGranted = true;
            }
            // 赋值节点下的增删改权限
            this.getZSG(i.displayName, params, perm.isGranted)
            params.permissions.push(perm);
          });
        });
      });

      params.permissions.forEach((item,index) => {
        // 排除二级菜单
        if (item.name == 'skip') {
          params.permissions.splice(index, 1)
        }
        
        // 用户权限 | 角色权限 包含其子节点 创建，编辑，删除，更改
        if (item.name == 'AbpIdentity.Users' ) {
          if (item.isGranted) {
            params.permissions.push({
              isGranted: true,
              name: 'AbpIdentity.Users.Create'
            },{
              isGranted: true,
              name: 'AbpIdentity.Users.Update'
            },{
              isGranted: true,
              name: 'AbpIdentity.Users.Delete'
            },{
              isGranted: true,
              name: 'AbpIdentity.Users.ManagePermissions'
            })
          } else {
            params.permissions.push({
              isGranted: false,
              name: 'AbpIdentity.Users.Create'
            },{
              isGranted: false,
              name: 'AbpIdentity.Users.Update'
            },{
              isGranted: false,
              name: 'AbpIdentity.Users.Delete'
            },{
              isGranted: false,
              name: 'AbpIdentity.Users.ManagePermissions'
            })
          }
        }
        if (item.name == 'AbpIdentity.Roles' ) {
          if (item.isGranted) {
            params.permissions.push({
              isGranted: true,
              name: 'AbpIdentity.Roles.Create'
            },{
              isGranted: true,
              name: 'AbpIdentity.Roles.Update'
            },{
              isGranted: true,
              name: 'AbpIdentity.Roles.Delete'
            })
          } else {
            params.permissions.push({
              isGranted: false,
              name: 'AbpIdentity.Roles.Create'
            },{
              isGranted: false,
              name: 'AbpIdentity.Roles.Update'
            },{
              isGranted: false,
              name: 'AbpIdentity.Roles.Delete'
            })
          }
        }
      })

      // 修改必备权限，否则菜单无法正常显示 *************************
      params.permissions.filter((item) => {
        if (item.name == 'AbpIdentity.Roles.ManagePermissions' || item.name == 'Auth.UserMenu') {
          item.isGranted = true
        }
      })

      putpermissionsRoles(
        "/permission-management/permissions?providerName=R&providerKey=" +
          this.multipleSelection[0].name,
        params
      ).then((response) => {
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 2000,
        });
        this.savePerLoading = false;
      }).catch(err=>{
        this.savePerLoading = false;
      });
    },
    // 节点下的增删改权限
    getZSG(name,params,isGranted) {
      if (name !== 'skip') {
        this.rolesAll.forEach(item => {
          if (item.parentName == name ) {
            let perm = {}
            perm.name = item.name
            perm.isGranted = isGranted
            params.permissions.push(perm)
          }
        })
      }
    },
    //点击table行渲染权限模板
    handleRowClick(row, column, event) {
      let that = this
      this.name = row.name
      this.treeLoading = true;
      // if (row.name == "admin") {
      //   this.$notify({
      //     title: "提示",
      //     message: "不可更改超级管理员权限",
      //     type: "warning",
      //     duration: 2000,
      //   });
      //   this.$refs.multipleTable.clearSelection();
      //   this.permissionsData = [];
      //   this.checkedPermission = [];
      // } else {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row);
      // }
       
      this.params.providerKey = row.name;
      getpermissionsRoles(this.params).then((res) => {
        this.rolesAll = []
        this.permissionsData = [];
        this.checkedPermission = [];
        // 根据前端菜单，进行重置分组
        res.groups.forEach(itemRes => {
          itemRes.permissions.forEach(item => {
            // if (item.displayName !== '创建' && item.displayName !== '编辑' && item.displayName !== '删除' && item.displayName !== '修改') {
              this.rolesAll.push(item)
            // }
          })
        })
        let filters = []
        filters.push({
          logic: "And",
          column: "portal",
          action: "==",
          value: "0"
        })
        const data = {
          condition: {
            filters: filters
          },
          Sorting: "",
          SkipCount: 0,
          MaxResultCount: 1000,
        };
        menuPermissions(data).then((res) => {
          let rs = that.initTreeData(res.items,'').sort(that.sortData('sort'))
          rs.forEach(item => {
            that.permissionsData.push(item);
          })
          that.$nextTick(() => {
            that.$refs.tree.setCheckedKeys(that.checkedPermission)
          })
          // console.log('菜单树',that.permissionsData)
          // console.log('拥有权限',that.checkedPermission)
          // console.log('所有权限',that.rolesAll)
          that.treeLoading = false;
        }).catch((err)=>{
          that.treeLoading = false;
          console.log(err)
        })
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.appMainPage {
  padding: 20px;
  .main {

    .table-active {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      padding: 5px 0 15px 0;

      .bttton-box {
        display: flex;
      }

    }
  }

  .el-table__body-wrapper {
    tbody {
      span {
        cursor: pointer;

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  .Footer {
    padding: 25px 0;
    display: flex;
    justify-content: flex-end;
  }

  ::v-deep .el-dialog {
    .el-dialog__header {
      button {
        display: none;
      }
    }

  }
  .permission-tree{
    padding: 20px;
    height: 690px;
    overflow-y: auto;
  }
}
</style>

