<template>
  <div class="app-container flex-col p4">
    <p>选择启用的权限</p>
    <el-input
        class="w400"
        placeholder="查找权限"
        clearable @clear="keyword=undefined"
        v-model="keyword">
    </el-input>
    <div class="over-scroll tree-container w400 mt10">
      <el-tree
          :data="permissions"
          :default-expanded-keys="expanded"
          :props="{label:'name'}"
          :filter-node-method="filterPermissions"
          show-checkbox
          node-key="id"
          empty-text="无数据"
          ref="permissions">
      </el-tree>
    </div>
    <div class="pl10 flex justify-center w400">
      <el-button @click="onReset" type="primary" plain>重置</el-button>
      <el-button :disabled="!permissions" @click="onSave" type="primary">保存</el-button>
    </div>
  </div>
</template>

<script>

export default {
  name: "SystemPermissions",
  data() {
    return {
      permissions: undefined, // 所有权限
      expanded: [], // 展开的权限
      selectIds: [], // 启用的权限
      keyword: undefined, // 过滤关键字
    }
  },

  watch: {
    keyword(val) {
      this.$refs["permissions"].filter(val);
    }
  },

  // 页面创建
  created() {
    this.initData();
  },

  // 页面挂载
  mounted() {
    this.getData();
  },

  // keep-alive 显示界面时调用
  activated() {
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 初始化数据
    initData() {
    },

    // 权限显示过滤
    filterPermissions(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 恢复选择状态
    onReset() {
      this.$refs.permissions.setCheckedKeys(this.selectIds);
    },

    // 保存权限启用状态
    onSave() {
      this.$axios.put("/v1/system/permissions/update/enable", this.$refs.permissions.getCheckedNodes(false, true).map(item => item.id)).then(() => {
        this.$message.success("保存成功！");
      });
    },

    // 加载数据
    getData() {
      this.$axios.get("/v1/system/permissions/list/tree").then((data) => {
        this.processing(data)
        this.permissions = data;
        this.$refs.permissions.setCheckedKeys(this.selectIds);
        this.expanded = this.permissions.map(p => p.id);
      });
    },

    // 处理数据
    processing(data) {
      data.forEach((item) => {
        if (item.children.length > 0) {
          this.processing(item.children)
        } else if (!item.disabled) {
          this.selectIds.push(item.id);
        }
        item.disabled = false;
      });
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  max-height: calc(100vh - 70px);

  .tree-container {
    ::v-deep .el-form-item__content {
      max-height: 100%;
      overflow-y: auto;
    }
  }
}
</style>
