<template>
  <div class="app-container">
    <div style="font-size:13px;color:#A8A8A8;text-align: center;margin-bottom: 10px">
      <i class="el-icon-info"/>单击左边列表某一行选中角色，中部展示角色对应的菜单按钮权限，右边展示具有此角色的用户,可以对菜单按钮和用户进行增删
    </div>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-card style="height:calc(100vh - 115px)">
          <div class="head-container">
            <el-button size="mini" type="primary" @click="handleAdd">新增</el-button>

            <el-input
              v-model="roleName"
              placeholder="请输入角色名称"
              clearable
              size="mini"
              prefix-icon="el-icon-search"
              style="margin-left: 20px"/>
          </div>

          <el-table :data="roleFilterList" size="mini" @row-click="rowClick" :row-style="rowStyle">
            <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true"/>
            <!--          <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true"/>-->
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
              <template slot-scope="scope" v-if="scope.row.id !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:role:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:role:delete']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </el-col>

      <el-col :span="8">
        <el-card style="height:calc(100vh - 115px)">
          <div class="head-container">
            <div style="font-size: 18px">菜单权限</div>
            <el-button size="mini" type="primary" @click="saveRoleMenus">保存</el-button>
          </div>
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
          <div style="height:calc(100vh - 200px);overflow: auto">
            <el-tree
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              ref="menuTree"
              node-key="id"
              :check-strictly="!menuCheckStrictly"
              empty-text="加载中，请稍候"
              :props="defaultProps"
            ></el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card style="height:calc(100vh - 115px)">
          <div class="head-container">
            <el-input
              v-model="userName"
              placeholder="请输入名字进行过滤"
              clearable
              size="mini"
              prefix-icon="el-icon-search"
              style="margin-right: 20px"/>

            <el-button size="mini" type="primary" @click="saveRoleUser">保存</el-button>
          </div>
          <div style="height:calc(100vh - 180px);overflow: auto">
            <el-tree
              class="tree-border"
              ref="userTree"
              :data="userList"
              node-key="id"
              show-checkbox
              :props="{label:'name'}"
              :default-expand-all="true"
              :filter-node-method="filterNode">
            </el-tree>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符"/>
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {getDeptUserTree} from '@/api/system/user'
import {roleMenuTreeselect, treeselect as menuTreeselect} from "@/api/system/menu";
import {addRole, delRole, getRole, getUserIdsByRoleId, listRole, saveRoleUser, updateRole} from "@/api/system/role";


export default {
  name: "Dept",
  components: {Treeselect},

  data() {
    return {
      roleName: '',
      roleList: [],
      roleFilterList: [],
      selectedRow: null,
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      userName: null,
      // 用户列表
      userList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roleName: [
          {required: true, message: "角色名称不能为空", trigger: "blur"}
        ],
        roleKey: [
          {required: true, message: "权限字符不能为空", trigger: "blur"}
        ],
        roleSort: [
          {required: true, message: "角色顺序不能为空", trigger: "change"}
        ]
      }
    };
  },
  watch: {
    userName(val) {
      this.$refs.userTree.filter(val);
    },
    roleName(val) {
      if (!val) {
        this.roleFilterList = this.roleList
      }
      this.roleFilterList = this.roleList.filter(item => item.roleName.indexOf(val) > -1)
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.getRoleList();
      this.getMenuTreeSelect();
      this.getDeptUserTrees();
    },

    /** 查询角色列表 */
    getRoleList() {
      listRole({}).then(response => {
          this.roleList = response.data;
          this.roleFilterList = this.roleList
        }
      );
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true,
        remark: undefined
      };
      this.resetForm("form");
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRole(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改角色";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRole(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getRoleList();
            });
          } else {
            addRole(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getRoleList();
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 角色状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.roleName + '"角色吗？').then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$message.success(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除角色编号为"' + ids + '"的数据项？').then(() => {
        return delRole(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },

    rowClick(row, column, event) {
      if (column.label === '操作') {
        return
      }
      this.selectedRow = row.id
      this.setRoleMenuTreeSelect(row.id)
      this.setRoleUserTreeSelect(row.id)
    },
    rowStyle({row, rowIndex}) {
      if (row.id === this.selectedRow) {
        return {
          background: '#DCDFE6'
        }
      }
    },

    /** 查询菜单树结构 */
    getMenuTreeSelect() {
      menuTreeselect().then(res => {
        this.menuOptions = res.data;
      });
    },

    /** 根据角色ID查询菜单树结构 */
    setRoleMenuTreeSelect(id) {
      roleMenuTreeselect(id).then(res => {
        let checkedKeys = this.$refs.menuTree.getCheckedKeys();
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menuTree.setChecked(v, false, false);
          })
        })

        let data = res.data.checkedKeys
        data.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menuTree.setChecked(v, true, false);
          })
        })

      });
    },

    /** 保存角色权限 */
    saveRoleMenus() {
      if (!this.selectedRow) {
        this.$message.info('请先选择角色')
        return
      }
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menuTree.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      let data = {
        id: this.selectedRow,
        menuIds: checkedKeys
      }
      updateRole(data).then(response => {
        this.$message.success("保存成功");
      });
    },

    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menuTree.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menuTree.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.menuCheckStrictly = value ? true : false;
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    getDeptUserTrees() {
      getDeptUserTree('').then(res => {
        this.userList = res.data
      });
    },

    setRoleUserTreeSelect(id) {
      getUserIdsByRoleId(id).then(res => {
        let checkedKeys = this.$refs.userTree.getCheckedKeys();
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.userTree.setChecked(v, false, false);
          })
        })

        res.data.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.userTree.setChecked(v, true, false);
          })
        })
      })
    },

    /** 保存角色用户 */
    saveRoleUser() {
      if (!this.selectedRow) {
        this.$message.info('请先选择角色')
        return
      }
      // 目前被选中的人员节点
      let checkedKeys = this.$refs.userTree.getCheckedKeys();
      // 半选中的人员节点
      let halfCheckedKeys = this.$refs.userTree.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      let data = {
        roleId: this.selectedRow,
        userIds: checkedKeys
      }
      saveRoleUser(data).then(res => {
        this.$message.success("保存成功");

      })
    }


  }
};
</script>
<style scoped lang="scss">
.head-container {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}

.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
