<template>
  <el-card class="user">
    <el-card class="search">
      <el-form
        :inline="true"
        :model="searchForm"
        class="search_form"
        style="text-align: left"
      >
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            @keyup.enter.native="onSubmit"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser">添加角色</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table">
      <table-template
        :indexShow="true"
        :tableData="tableData"
        :tableColumns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        @Jump="jumpPage"
      >
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" round @click="edit(scope.row)">分配权限</el-button>
            <el-button type="danger" size="mini" round @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </table-template>
    </el-card>
    <el-dialog
      title="添加角色"
      :visible.sync="addVisible"
      width="40%"
      :before-close="addClose"
      :close-on-click-modal="false"
    >
      <el-form class="form" ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="角色名称：" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述：" prop="remark">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addClose">取 消</el-button>
          <el-button type="primary" @click="createRole">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="editVisible"
      width="40%"
      :before-close="editClose"
      :close-on-click-modal="false"
    >
      <el-tree
        class="tree"
        :data="treeList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="idList"
        :props="defaultProps"
        ref="tree"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editClose">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import TableTemplate from "@/components/Table";
import { rolePage,createRole,listRoleMenu,assignRoleMenu,deleteUser } from "@/api/role";
import { listMenus } from "@/api/login";
import { getToken,setMenuList } from "@/utils/auth.js";


export default {
  components: { TableTemplate },
  data() {
    return {
      searchForm: {
        roleName: "",
      },
      loading: false,
      pagination: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      tableData: [],
      tableColumns: [
        {
          key: "roleName",
          label: "角色名称",
        },
        {
          key: "description",
          label: "角色描述",
        },
        {
          key: "createTime",
          label: "创建时间",
        },
      ],
      addVisible: false,
      form: {
        name: '',
        remark: '',
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
        remark: [{ required: true, message: '请输入角色描述', trigger: 'change' }]
      },
      editVisible: false,
      treeList: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      idList: [],
      roleId: ''
    };
  },
  methods: {
    init() {
      this.loading = true;
      let params = {
        roleName: this.searchForm.roleName,
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      };
      rolePage(params).then((res) => {
        this.loading = false;
        if (res.success) {
          this.pagination.total = res.data.total;
          this.tableData = res.data.list;
        }
      });
    },
    jumpPage() {
      this.init();
    },
    onSubmit() {
      this.pagination.currentPage = 1;
      this.init();
    },
    addUser() {
      this.addVisible = true
    },
    addClose() {
      this.addVisible = false;
      this.form = {};
    },
    createRole() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {
            roleName: this.form.name,
            description: this.form.remark
          }
          createRole(params).then((res) => {
            if (res.success) {
              this.$message({
                type: "success",
                message: "创建成功!",
              });
              this.addClose();
              this.onSubmit();
            } else {
              this.$message({
                type: "error",
                message: res.msg ||"创建失败!",
              });
            }
          })
        }
      })
    },
    edit(row) {
      this.roleId = row.id
      listRoleMenu({roleId: this.roleId}).then((res) => {
        this.idList = []
        res.data.map((item) => {
          // 选中菜单回显
          if (item.status == 1 && item.parentId != 0) {
            return this.idList.push(item.id)
          }
        })
        console.log(this.idList)
        this.initTree(res.data);
        this.editVisible = true;
      })
    },
    // 平铺数据--->树状结构
    initTree(list) {
      let map = {};
      this.treeList = [];
      list.forEach((item) => {
        item.children = [];
        map[item.id] = item;
      });
      list.forEach((item) => {
        const obj = map[item.parentId];
        if (obj) {
          obj.children.push(item);
        } else {
          this.treeList.push(item);
        }
      });
    },
    editClose() {
      this.editVisible = false;
    },
    editUser() {
      let menuIds = []
      this.$refs.tree.getCheckedNodes().map((item) => {
        if (item.parentId != 0) {
          menuIds.push(item.parentId)
          menuIds.push(item.id)
        }else {
          menuIds.push(item.id)
        }
      })
      assignRoleMenu({menuIds: menuIds,roleId: this.roleId}).then((res) => {
        if (res.success) {
          listMenus({ tokenValue: getToken() }).then((res) => {
            if (res.success == true) {
                setMenuList(JSON.stringify(res.data));
                location.reload();
            }
          })
        }
      })
    },
    del(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUser({ id: row.id }).then((res) => {
            if (res.success == true) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.init();
            } else {
                this.$message({
                    type: "warning",
                    message: res.msg || '删除失败，请联系管理员',
                }); 
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
  },
  created() {
    this.init();
  },
};
</script>

<style lang="stylus" scoped>
.user {
  width: 100%;
  height: calc(100vh - 100px);

  .search {
  }

  .table {
    margin-top: 15px;
    max-height: calc(100vh - 260px);
    overflow: auto;
  }
}
</style>