<template>
  <div class="common-box">
    <!--条件-->
    <el-form :model="listQuery" ref="queryForm" :inline="true">
      <el-form-item label="角色编码">
        <el-input
          v-model="listQuery.roleId"
          placeholder="请输入角色编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色名称">
        <el-input
          v-model="listQuery.roleName"
          placeholder="请输入角色名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch()">查询</el-button
        ><el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="right-button">
      <el-button
        type="primary"
        class="lake-Blue"
        icon="el-icon-plus"
        @click="handleAddOrEdit(0, null, 'create')"
        >新增
      </el-button>
    </div>
    <!--列表-->
    <div>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中"
        fit
        stripe
        border
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column label="角色编码" prop="roleId" />

        <el-table-column label="角色名称" prop="roleName" />

        <el-table-column label="说明" :v-if="true" prop="dscr" />

        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              class="cyan"
              type="text"
              @click="handleAddOrEdit(scope.$index, scope.row, 'update')"
              >编辑</el-button
            >
            <el-button
              class="red"
              type="text"
              @click="handleDelete(scope.row, 'deleted')"
              >删除</el-button
            >
            <el-button
              class="orange"
              type="text"
              @click="handlePrivilege(scope.row)"
              >设置权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <yl-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getData"
    />

    <!--添加/修改-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="420px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        style="width: 370px; margin-left: 10px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="temp.roleName" />
        </el-form-item>
        <el-form-item label="说明" prop="dscr">
          <el-input v-model.trim="temp.dscr" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitData()" :loading="btLoading1">{{
          btLoading1 ? "确认中" : "确认"
        }}</el-button>
      </div>
    </el-dialog>

    <!-- 设置权限 -->
    <el-dialog
      v-if="dialogPrivilegeFormVisible"
      title="设置权限"
      :visible.sync="dialogPrivilegeFormVisible"
      width="400px"
    >
      <el-form
        ref="dataPrivilegeForm"
        :rules="rules"
        :model="tempPrivilege"
        label-position="left"
        label-width="80px"
      >
        <funTree
          ref="funtree"
          :defaultMenu="defaultMenu"
          :allMenu="menuData"
          :checkBoxShow="true"
          :reload="reload"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPrivilegeFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="commitPrivilegeData()"
          :loading="btLoading2"
          >{{ btLoading2 ? "确认中" : "确认" }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleData,
  getMenuButtonData,
  setRole,
  setRoleMenu
} from "@/api/system/role";
import ylPagination from "@/components/yl-pagination";
import FunTree from "@/views/components/funTree";

export default {
  components: {
    ylPagination,
    FunTree
  },

  data() {
    return {
      btLoading1: false,
      btLoading2: false,
      reload: "",
      roleId: "",
      defaultMenu: [],
      menuData: [], //菜单
      list: null, //列表
      total: 0, //分页
      listLoading: true,
      listQuery: {
        //条件查询
        roleName: "",
        current: 1,
        size: 10,
        roleId: ""
      },
      roles: [],
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      temp: {},
      dialogPrivilegeFormVisible: false, //角色对话框
      tempPrivilege: {
        //权限表单
      },
      rules: {
        roleId: [
          {
            required: true,
            message: "角色编码不能为空",
            trigger: "blur"
          }
        ],
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },

  created() {
    this.getData();
  },

  methods: {
    // 重置页面
    reset() {
      this.listQuery.roleId = "";
      this.listQuery.roleName = "";
      this.getData();
    },

    // 查询
    handleSearch() {
      this.listQuery.current = 1;
      this.getData();
    },

    //获取列表数据
    getData() {
      this.listLoading = true;
      getRoleData(this.listQuery)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    //提交角色表单数据
    commitData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.btLoading1 = true;
            setRole(this.temp)
              .then((response) => {
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.btLoading1 = false;
                this.dialogFormVisible = false;
                this.getData();
              })
              .catch(() => {
                this.btLoading1 = false;
              });
          });
        }
      });
    },

    //  菜单提交
    commitPrivilegeData() {
      if (
        this.$refs.funtree.$refs.tree.getCheckedNodes(false, true).length == 0
      ) {
        this.$message({
          message: "请选择至少一级菜单",
          type: "error"
        });
        return;
      }
      this.btLoading2 = true;
      let commitList = new Array();
      for (
        let i = 0;
        i < this.$refs.funtree.$refs.tree.getCheckedNodes(false, true).length;
        i++
      ) {
        let entity = {
          roleId: this.roleId,
          menuId: this.$refs.funtree.$refs.tree.getCheckedNodes(false, true)[i]
            .id,
          penartId: this.$refs.funtree.$refs.tree.getCheckedNodes(false, true)[
            i
          ].parentId,
          type: this.$refs.funtree.$refs.tree.getCheckedNodes(false, true)[i]
            .menuType
        };
        commitList.push(entity);
      }
      setRoleMenu(commitList)
        .then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.btLoading2 = false;
          this.dialogPrivilegeFormVisible = false;
        })
        .catch(() => {
          this.btLoading2 = false;
        });
    },

    //添加/修改对话框
    handleAddOrEdit(index, row, type) {
      if (type === "update") {
        this.temp = {
          id: row.id,
          // roleId: row.roleId,
          roleName: row.roleName,
          dscr: row.dscr,
          type: "updt"
        };
      } else {
        this.temp = {
          id: "",
          // roleId: "",
          roleName: "",
          dscr: "",
          type: "add"
        };
      }

      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    // 打开设置权限对话框
    handlePrivilege(row) {
      this.roleId = row.roleId;
      this.defaultMenu = [];
      getMenuButtonData({ roleId: row.roleId }).then((response) => {
        let data = response.data;

        data.forEach((item, index) => {
          if (item.cho == 0) {
            this.defaultMenu.push(item);
          }
        });
        if (data && data.length > 0) {
          this.menuData = data;
          this.dialogPrivilegeFormVisible = true;
        }
      });
    },

    //删除
    handleDelete(row, status) {
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.temp = {
          id: row.id,
          roleId: row.roleId,
          roleName: row.roleName,
          dscr: row.dscr,
          type: "del"
        };
        setRole(this.temp).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          // 解决element el-pagination分页最后一页数据清空了页码显示正确，但是列表为空
          const totalPage = Math.ceil((this.total - 1) / this.listQuery.size);
          const currentPage =
            this.listQuery.current > totalPage
              ? totalPage
              : this.listQuery.current;
          this.listQuery.current = currentPage < 1 ? 1 : currentPage;
          this.getData();
        });
      });
    }
  }
  //--------------------method
};
</script>

<style scoped>
</style>
