<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入角色名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="角色编号" prop="id" align="center" />
      <el-table-column
        label="角色名称"
        prop="name"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="创建时间" align="center" prop="updated_at">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updated_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleAuthMenu" icon="el-icon-user"
                >菜单权限</el-dropdown-item
              >
              <el-dropdown-item
                command="handleDataScope"
                icon="el-icon-circle-check"
                >基本权限</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注">
          <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" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色菜单权限对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openMenuScope"
      width="500px"
      append-to-body
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            default-expand-all
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMenuScope">确 定</el-button>
        <el-button @click="cancelMenuScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  roleMenuList,
  roleMenuBind,
  roleAuthList,
  roleAuthBind,
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
} from "@/api/system/role";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  treeselect as deptTreeselect,
  roleDeptTreeselect,
} from "@/api/system/dept";

export default {
  name: "Role",
  // dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（菜单权限）
      openMenuScope: false,
      // 菜单列表
      menuOptions: [],
      // 查询参数
      queryParams: {
        page_num: 1,
        page_size: 10,
        name: undefined,
      },
      // 表单参数
      form: {},
      // 是否为菜单权限弹窗和基本权限弹窗
      roleFlag: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listRole(this.queryParams).then((response) => {
        this.roleList = response.data.data;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（菜单权限）
    cancelMenuScope() {
      this.openMenuScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        id: undefined,
        name: undefined,
        menu_ids: [],
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page_num = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 更多操作触发
    handleCommand(command, row) {
      if (command == "handleAuthMenu") {
        // 菜单权限按钮
        this.roleFlag = true;
      } else {
        // 基本权限按钮
        this.roleFlag = false;
      }
      this.handleAuthMenu(row);
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改角色";
    },
    /** 菜单权限操作 */
    handleAuthMenu: function (row) {
      this.form = Object.assign({}, row);
      this.openMenuScope = true;
      if (this.roleFlag) {
        roleMenuList({ role_id: row.id }).then((res) => {
          this.menuOptions = res.data;
          const checkedKeys = [];
          this.filterSetChecked(res.data, "checked", checkedKeys);
          this.$refs.menu.setCheckedKeys(checkedKeys);
        });
        this.title = "分配菜单权限";
      } else {
        roleAuthList({ role_id: row.id }).then((res) => {
          console.log(res);
          this.menuOptions = res.data;
          const checkedKeys = [];
          this.filterSetChecked(res.data, "checked", checkedKeys);
          this.$refs.menu.setCheckedKeys(checkedKeys);
        });
        this.title = "分配基本权限";
      }
    },
    filterSetChecked(data, field, out) {
      data.map((item) => {
        if (item[field]) {
          out.push(item.id);
        }
        if (item.children.length) {
          this.filterSetChecked(item.children, field, out);
        }
      });
    },
    /** 提交按钮 - 修改名称普通数据 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（菜单权限） */
    submitMenuScope: function () {
      if (this.form.id) {
        if (this.roleFlag) {
          roleMenuBind({
            role_id: this.form.id,
            menu_ids: this.$refs.menu.getCheckedKeys(),
          }).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.openMenuScope = false;
            this.getList();
          });
        } else {
          // Todo...
          // roleAuthBind
          console.log("提交基本权限");
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id;
      this.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return delRole({ id: roleIds });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>