<template>
  <div class="global-variable">
    <div class="condition">
      <el-form
        :inline="true"
        ref="ruleForm"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="formInline.roleName"
            placeholder="请输入角色名称"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="roleAvailable"   size="small">
          <el-select
            v-model="formInline.roleAvailable"
            placeholder="请选择状态"
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="small"
            >查询</el-button
          >
          <el-button @click="reset('ruleForm')" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list-page">
      <div class="newly">
        <el-button type="primary" @click="newnuedialog" size="small"
          >新增</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        class="center-align-table"
        :data="tableData"
        border
        :cell-style="rowStyle"
      >
        <el-table-column
          align="center"
          fixed
          prop="id"
          label="角色ID"
          width="100"
        >
        </el-table-column>

        <el-table-column align="center" label="角色名称" prop="roleDescription">
        </el-table-column>

        <el-table-column prop="roleType" align="center" label="角色类型">
          <template slot-scope="scope">
            <span v-for="item in stateOPtions" :key="item.contentsValue">
              {{
                scope.row.roleType == item.contentsValue
                  ? item.contentsName
                  : ""
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column align="center" prop="source" label="角色来源">
          <template slot-scope="scope">
            <span>
              {{
                scope.row.source == 0
                  ? "系统"
                  : scope.row.source == 1
                  ? "自定义"
                  : "/"
              }}</span
            >
          </template>
        </el-table-column>

        <el-table-column prop="roleCode" align="center" label="角色标识">
        </el-table-column>
        <el-table-column
          prop="roleAvailable"
          align="center"
          label="状态"
          width="100"
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.roleAvailable == 0
                  ? "停用"
                  : scope.row.roleAvailable == 1
                  ? "启用"
                  : "/"
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="创建时间">
        </el-table-column>
        <el-table-column
          prop="transition"
          align="center"
          fixed="right"
          label="操作"
          width="200"
        >
          <template slot-scope="scope">
            <el-button @click="compile(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button
              style="color: #f90"
              @click="editAuth(scope.row)"
              type="text"
              size="small"
              >权限设置</el-button
            >
            <el-button
              v-if="scope.row.roleAvailable == 0"
              @click="setState(1, scope.row.id)"
              type="text"
              size="small"
              >启用</el-button
            >
            <el-button
              v-else
              style="color: #666"
              @click="setState(0, scope.row.id)"
              type="text"
              size="small"
              >停用</el-button
            >

            <el-button
              style="color: #f00"
              @click="deleted(scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="formInline.pageNum"
          layout="total, prev, pager, next"
          :page-size="formInline.pageSize"
          :total="formInline.totalSize"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 弹出层 -->
    <!-- 新增 /编辑-->
    <el-dialog :title="title" :visible.sync="nuedialog" width="500px">
      <div v-loading="loadingView" class="views">
        <el-form
          :model="ruleForm"
          :rules="addUserRules"
          ref="addUserForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="ruleForm.roleName"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色标识" prop="roleCode">
            <el-input
              v-model="ruleForm.roleCode"
              placeholder="请输入角色标识"
            ></el-input>
          </el-form-item>

          <el-form-item label="角色类型:" prop="roleType">
            <el-select
              v-model="ruleForm.roleType"
              placeholder="请选择角色类型"
              style="width: 100%"
            >
              <el-option
                :label="item.contentsName"
                v-for="item in stateOPtions"
                :value="item.contentsValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel('addUserForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="submitForm('addUserForm')"
            size="small"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
    <!-- 权限设置 -->
    <el-dialog title="权限设置" :visible.sync="unusualdialog" width="500px">
      <div v-loading="loadingView" class="views">
        <el-form :model="editRoleAuth" ref="editRoleAuth" label-width="100px">
          <el-form-item
            label="角色名称"
            prop="roleName"
            :rules="[{ required: true, message: '角色名称不能为空' }]"
          >
            <el-input
              disabled
              v-model.number="editRoleAuth.roleName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色标识"
            prop="roleCode"
            :rules="[{ required: true, message: '角色标识不能为空' }]"
          >
            <el-input
              disabled
              v-model.number="editRoleAuth.roleCode"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-tabs type="border-card" class="tabs">
          <el-tab-pane label="功能权限"
            ><MenuTree ref="menuTreeRef" :treeObj="treeObj"></MenuTree
          ></el-tab-pane>
          <el-tab-pane label="数据权限">数据权限</el-tab-pane>
        </el-tabs>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="
              () => {
                this.$refs['editRoleAuth'].resetFields();
                this.unusualdialog = false;
                this.loadingView = false;
              }
            "
            size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="editAuthMenu('editRoleAuth')"
            size="small"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MenuTree from "./components/menuTree.vue";
import {
  getRoleTableList,
  updateRoleAvailable,
  getRoleBId,
  addRole,
  editRole,
  deleteRoleInfo,
  updateRolePermission,
  getDetailRoleAuth,
} from "@/api/system.js";
import { dictType } from "@/api/dict.js";
export default {
  components: {
    MenuTree,
  },
  data() {
    return {
      treeObj: {
        roleId: null,
        checkList: [],
      },
      loadingView: false,
      //角色类型
      stateOPtions: [],
      loading: false, //数据加载中
      rules: {
        roleAvailable: { trigger: "change" },
        roleName: { trigger: "blur" },
      },
      roleList: [],
      formInline: {
        roleName: undefined,
        roleAvailable: undefined,
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      tableData: [],
      // 新增编辑表单
      ruleForm: {
        roleType: null,
        roleCode: null,
        roleName: null,
      },
      addUserRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleCode: {
          required: true,
          message: "请输入角色标识",
          trigger: "blur",
        },
        roleType: {
          required: true,
          message: "请选择角色类型",
          trigger: "change",
        },
      },
      //修改权限
      editRoleAuth: {
        roleName: "",
        roleCode: "",
      },
      nuedialog: false,
      unusualdialog: false,
      title: "",
    };
  },
  created() {
    dictType({ dictType: 2 })
      .then((res) => {
        this.stateOPtions = res.data;
      })
      .catch(() => {});
    this.getTableList();
  },
  methods: {
    //修改权限
    editAuthMenu(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { permissionIds, roleId } =
            this.$refs.menuTreeRef.getCheckTreeKey();
          if (!permissionIds) {
            this.$message({
              message: "至少要选择一个菜单",
              type: "warning",
            });
          } else {
            this.loadingView = true;
            updateRolePermission({ permissionIds, roleId })
              .then((res) => {
                this.$message({
                  message: "权限修改成功",
                  type: "success",
                });
                this.getTableList();
                this.loadingView = false;
                this.unusualdialog = false;
              })
              .catch(() => {});
          }
        } else {
          return false;
        }
      });
    },
    //分页数据切换
    handleCurrentChange(val) {
      this.formInline.pageNum = val;
      this.getTableList();
    },
    //修改状态
    setState(state, roleId) {
      //启用接口
      updateRoleAvailable({ roleAvailable: state, roleId })
        .then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
          });
          this.getTableList();
        })
        .catch((error) => {});
    },
    async getTableList() {
      try {
        this.loading = true;
        const result = await getRoleTableList({
          ...this.formInline,
          roleAvailable: Number(this.formInline.roleAvailable),
          totalSize: undefined,
        });
        this.tableData = result.data.list;
        this.formInline.totalSize = result.data.totalSize;
        this.loading = false;
      } catch (error) {
        this.$message({
          type: "error",
          message: "请检查是否连接网络",
        });
      }
    },

    rowStyle() {
      return "text-align:center";
    },
    // 查询
    onSubmit() {
      this.getTableList();
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields();
      this.getTableList();
    },

    // 新增,编辑确定
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingView = true;
          switch (this.title) {
            case "新增":
              addRole({ ...this.ruleForm, roleId: undefined })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getTableList();
                  this.nuedialog = false;
                  this.loadingView = false;
                })
                .catch(() => {});
              break;
            case "编辑":
              editRole({ ...this.ruleForm })
                .then((res) => {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getTableList();
                  this.nuedialog = false;
                  this.loadingView = false;
                })
                .catch(() => {});

              break;
          }
        } else {
          return false;
        }
      });
    },
    //点击取消
    cancel(formName) {
      this.$refs[formName] && this.$refs[formName].resetFields();
      this.ruleForm = {
        roleType: null,
        roleCode: null,
        roleName: null,
        roleId: null,
      };
      this.nuedialog = false;
      this.loadingView = false;
    },
    // 编辑 回显数据
    async compile(row) {
      try {
        const result = await getRoleBId({ roleId: row.id });
        const userInfo = result.data;

        // 直接替换整个对象，以确保 Vue 的响应式系统能够检测到变化
        this.ruleForm = {
          roleType: userInfo.roleType,
          roleCode: userInfo.roleCode,
          roleName: userInfo.roleDescription,
          roleId: userInfo.id.toString(),
        };
        this.nuedialog = true;
        this.title = "编辑";
      } catch (error) {
        this.$message.error("获取用户信息失败");
      }
    },
    // 删除
    deleted(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRoleInfo({ roleId: row.id })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getTableList();
            })
            .catch(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //权限修改按钮
    editAuth(row) {
      this.editRoleAuth.roleCode = row.roleCode;
      this.editRoleAuth.roleName = row.roleDescription;
      getDetailRoleAuth({ roleId: row.id })
        .then((res) => {
          this.treeObj = {
            roleId: row.id,
            checkList: res.data,
          };
          this.unusualdialog = true;
        })
        .catch(() => {});
    },
    // 新增
    newnuedialog() {
      this.cancel("addUserForm");
      this.nuedialog = true;
      this.title = "新增";
    },
  },
};
</script>

<style lang="scss" scoped>
.general {
  display: flex;
  flex-wrap: wrap;

  .condition {
    width: 50%;
    display: flex;

    p {
      width: 100px;
      text-align: right;
      line-height: 40px;
    }

    span {
      line-height: 40px;

      padding-left: 20px;
    }

    .el-select {
      width: 100%;
      margin-bottom: 20px;
    }

    .el-input {
      margin-bottom: 20px;
    }
  }
}

.attachment {
  display: flex;
  padding-top: 10px;

  p {
    margin-right: 20px;
    color: #409eff;
  }
}

.addition {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.tabs {
  margin-bottom: 50px;
}
</style>
