<!--  -->
<template>
  <div class="role_box">
    <el-card :style="'height:' + fullHeight + 'px'">
      <!-- 筛选 -->
      <el-row>
        <el-col>
          <!-- 组织搜索 -->
          <div class="search_box">
            <el-input
              size="mini"
              placeholder="请输入角色名称"
              v-model.trim="input"
              @change="searchData"
              clearable
            >
            </el-input>
            <div class="btn_box">
              <el-button type="primary" size="mini" @click="searchData"
                >搜索</el-button
              >
              <el-button type="primary" size="mini" @click="addrRole"
                >添加角色</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <el-table :data="tableData" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="ind" label="序号" width="280"></el-table-column>
        <el-table-column prop="role_name" label="角色名称" width="380">
        </el-table-column>
        <el-table-column prop="role_message" label="角色描述" width="580">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <a class="reset" href="javascript:;" @click="actionFunc(scope.row)"
              >编辑</a
            >
            <i class="line"></i>
            <a class="delete" href="javascript:;" @click="deleteFunc(scope.row)"
              >删除</a
            >
            <i class="line"></i>
            <a class="addr" href="javascript:;" @click="limitsData(scope.row)"
              >分配权限</a
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="tableData.length !== 0"
        @current-change="changeList"
        background
        layout="prev, pager, next, jumper"
        :current-page="page"
        :total="pagesum"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 - 编辑用户 -->
    <el-dialog
      :title="tltData"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="addrUserVisible"
      width="45%"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="90px">
        <el-form-item label="角色名称: " prop="name">
          <el-input
            style="width: 80%"
            size="mini"
            v-model.trim="form.name"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色描述: " prop="describe">
          <el-input
            style="width: 80%"
            size="mini"
            type="textarea"
            resize="none"
            v-model.trim="form.describe"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button size="small" type="primary" @click="submitForm"
            >确定</el-button
          >
          <el-button size="small" @click="addrUserVisible = false"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="pur_id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    //这里存放数据
    return {
      fullHeight: document.documentElement.clientHeight - 116, //
      input: "",
      tableData: [],
      loading: false, // 加载
      page: 1,
      pagesum: 0,

      //   添加用户 - 编辑用户
      tltData: "",
      addrUserVisible: false,
      form: {
        name: "",
        describe: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          //   { min: 3, max: 5, message: "长度在 1 到 15 个字符", trigger: "blur" },
        ],
        describe: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          //   { min: 3, max: 5, message: "长度在 1 到 30 个字符", trigger: "blur" },
        ],
      },

      // 分配权限
      setRightDialogVisible: false,
      rightsList: [],
      //  默认选中节点ID值
      defKeys: [],
      describeData: {}, // 点击表格操作时获取到的当前数据
      //  树形控件的属性绑定对象
      treeProps: {
        label: "purview_name",
        children: "children",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    // 添加、编辑角色弹框
    addrUserVisible(val) {
      if (val == false) {
        this.form.name = "";
        this.form.describe = "";
      }
    },

    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function () {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },

    setRightDialogVisible(val) {
      if (val == false) {
        this.defKeys = []
      }
    },
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    tabListData() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: "10",
          role_name: this.input,
        }),
      })
        .then((res) => {
          if (res.data.data.total_item !== 0) {
            var data = res.data.data.page_list;
            this.pagesum = res.data.data.total_item;
            var list = [];
            data.forEach((item, index) => {
              item.ind = index + 1;
              list.push(item);
            });
            this.tableData = list;
          } else {
            this.tableData = [];
            this.pagesum = 0;
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        });
    },

    // 搜索
    searchData() {
      this.tabListData();
    },

    // 下一页
    changeList(num) {
      this.page = num;
      this.tabListData();
    },

    // 添加角色
    addrRole() {
      this.tltData = "添加角色";
      this.addrUserVisible = true;
    },
    // 编辑角色
    actionFunc(data) {
      //   console.log(data);
      this.describeData = data;
      this.tltData = "编辑角色";
      this.form.name = data.role_name; // 角色名称
      this.form.describe = data.role_message; // 角色描述
      this.addrUserVisible = true;
    },
    // 添加、编辑角色确定
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.tltData == "添加角色") {
            // 添加
            this.addrRoleAxios(); // 添加
          } else if (this.tltData == "编辑角色") {
            // 编辑
            this.editRoleAxios(); // 编辑
          }
        } else {
          //   console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加 - 确定
    addrRoleAxios() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_add",
        data: this.qs.stringify({
          role_name: this.form.name,
          role_message: this.form.describe,
        }),
      })
        .then((res) => {
          if (res.data.data == true) {
            this.$message({
              message: "成功!",
              type: "success",
              duration: 1500,
            });
            this.addrUserVisible = false;
            this.tabListData();
          } else {
            this.$message({
              message: "失败!",
              type: "error",
              duration: 1500,
            });
          }
          //   console.log(res);
          this.addrUserVisible = false;
        })
        .catch((err) => {
          //   console.log(err);
        });
    },
    // 编辑 - 确定
    editRoleAxios() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_modify",
        data: this.qs.stringify({
          role_id: this.describeData.id,
          role_name: this.form.name,
          role_message: this.form.describe,
        }),
      })
        .then((res) => {
          if (res.data.data == true) {
            this.$message({
              message: "成功!",
              type: "success",
              duration: 1500,
            });
            this.addrUserVisible = false;
            this.tabListData();
          } else {
            this.$message({
              message: "失败!",
              type: "error",
              duration: 1500,
            });
          }
          //   console.log(res);
          this.addrUserVisible = false;
        })
        .catch((err) => {
          //   console.log(err);
        });
    },

    // 分配权限
    limitsData(val) {
      this.describeData = val;
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.user_info",
      })
        .then((res) => {
          if (res.data.message == "") {
            var data = res.data.data.children;
            this.rightsList = []
            this.rightsList = data;
            this.limitsList(); //获取当前角色的权限
          } else {
            this.rightsList = []
            this.$message.error("获取权限列表失败!");
          }
        })
        .catch((err) => {
          // console.log(err)
        });
    },
    // 当前角色权限
    limitsList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_info",
        data: this.qs.stringify({
          role_id: this.describeData.id, //角色ID
        }),
      })
        .then((res) => {
          if (res.data.data) {
            this.setRightDialogVisible = true;
            var list = this.tableData;
            for (var i = 0; i < list.length; i++) {
              if (list[i].id == this.describeData.id) {
                list[i]["children"] = res.data.data;
                this.defKeys = [];
                this.getLeafkeys(list[i], this.defKeys);
              }
            }
            this.tableData = list;
          } else {
            this.tableData = []
          }
        //   this.tabListData = list;
          // this.tableData = list;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getLeafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.pur_id);
      }
      node.children.forEach((item) => this.getLeafkeys(item, arr));
    },
    setRightDialogClosed() {
      this.rightsList = [];
    },
    // 确定 - 分配权限
    allotRights() {
        var that = this
      // 获得当前选中的Id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      console.log(idStr);
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.usermanager.role_perm",
        data: this.qs.stringify({
          pur_id: idStr, // 权限id
          role_id: this.describeData.id, // 角色id
        }),
      })
        .then((res) => {
          console.log(res);
          if (res.data.message == "") {
            this.$message.success("分配权限成功!");
            that.setRightDialogVisible = false;
            that.tabListData();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 删除
    deleteFunc(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=sysmenage.usermanager.role_delete",
            data: this.qs.stringify({
              role_id: data.id,
            }),
          })
            .then((res) => {
              if (res.data.message == "") {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                  duration: 1500,
                });
              }
              this.tabListData();
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loading = true
    this.tabListData(); // 表格数据
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
.role_box {
  .search_box {
    display: flex;
    /deep/.el-input {
      // width: 300px;
      width: 15%;
    }
    .btn_box {
      margin: 0 0 0 15px;
    }
  }
  a {
    text-decoration: none;
  }
  .reset {
    color: #1890ff;
  }
  .delete {
    color: #f56c6c;
  }
  .addr {
    color: #67c23a;
  }
  .line {
    display: inline-block;
    width: 1px;
    background: rgba(0, 0, 0, 0.09);
    margin: 0 11px;
    height: 14px;
  }
}
</style>