<template>
  <div>
    <section class="content" style="margin-top: -10px;">
      <div class="box box-info">
        <!-- 头信息 -->
        <div class="box-header with-border">
          <h3 class="box-title">鉴权管理 &gt; 角色权限配置</h3>
          <div class="box-tools pull-right">
            <button
              type="button"
              class="btn btn-box-tool"
              data-widget="collapse"
            >
              <i class="fa fa-minus"></i>
            </button>
          </div>
        </div>

        <!-- 正文信息 -->
        <div class="box-body">
          <!-- 选择 -->
          <el-form
            :inline="true"
            :model="form"
            label-position="right"
            label-width="100px"
          >
            <el-row>
              <el-form-item label="顶级机构" class="pull-left">
                <el-select
                  class="input_width_lg"
                  v-model="form.orgId"
                  placeholder="请选择"
                  @change="rootOrgChanged"
                  :disabled="!isSuperAdmin"
                >
                  <el-option
                    v-for="item in orgList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="角色" class="pull-left">
                <el-select
                  class="input_width_lg"
                  v-model="form.roleId"
                  placeholder="请选择"
                  @change="change"
                >
                  <el-option
                    v-for="item in roleList"
                    :label="item.roleName"
                    :value="item.roleId"
                    :key="item.roleId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="权限组" class="pull-left">
                <el-select
                  class="input_width_lg"
                  v-model="form.privilegeGroupId"
                  placeholder="请选择"
                  @change="change"
                >
                  <el-option
                    v-for="item in privilegeGroupList"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
          </el-form>

          <div style="margin-bottom:10px;margin-left: 50px;">
            <el-button
              :plain="true"
              type="success"
              :disabled="!treeChanged"
              @click="save"
              >保 存</el-button
            >
          </div>

          <!-- 权限树 -->
          <div style="width: 50%;margin-left: 50px;">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              show-checkbox
              node-key="id"
              ref="tree"
              highlight-current
              :check-strictly="true"
              :default-expanded-keys="[-1]"
              :default-checked-keys="checkedKeys"
              @check-change="treeChange"
              :expand-on-click-node="true"
            >
            </el-tree>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { core_api } from "../constants/constants.js";

export default {
  data() {
    return {
      completed: false,
      isSuperAdmin: false,
      form: {
        orgId: null,
        roleId: null,
        privilegeGroupId: null
      },
      orgList: [],
      roleList: [],
      privilegeGroupList: [],
      treeChanged: false,
      treeData: [],
      checkedKeys: [],
      uncheckChildren_nodeId: null,
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  computed: {
    ...mapState({ user: state => state.user })
  },
  methods: {
    /*初始化*/
    init() {
      for (let role of this.user.roleList) {
        if (role.roleCode == "SUPER_ADMIN") {
          this.isSuperAdmin = true;
          break;
        }
      }

      var url1 = core_api + "/org/getRootOrgList";
      var url2 =
        core_api + "/rolePrivilege/getRoles?includeSuperAdmin=" + false;
      var url3 = core_api + "/rolePrivilege/getPrivilegeGroupList";

      Promise.all([
        this.$http.get(url1),
        this.$http.post(url2),
        this.$http.get(url3)
      ]).then(([resp1, resp2, resp3]) => {
        this.orgList = resp1.data;

        this.form.orgId = this.user.rootOrgId;
        this.roleList = resp2.data;
        if (0 < this.roleList.length) {
          this.form.roleId = this.roleList[0].roleId;
        }
        this.privilegeGroupList = resp3.data;
        if (0 < this.privilegeGroupList.length) {
          this.form.privilegeGroupId = this.privilegeGroupList[0].id;
        }

        this.initTree(
          this.form.orgId,
          this.form.roleId,
          this.form.privilegeGroupId
        );
      });
    },
    /*初始化权限树*/
    initTree(orgId, roleId, privilegeGroupId) {
      var url1 =
        core_api + "/rolePrivilege/getPrivilegeTree/" + privilegeGroupId;
      var url2 =
        core_api + "/rolePrivilege/getPrivilegeIdList/" + orgId + "/" + roleId;

      Promise.all([this.$http.get(url1), this.$http.get(url2)]).then(
        ([resp1, resp2]) => {
          console.log("initTree(). treeData:", resp1.data.children);
          console.log("initTree(). checkedKeys:", resp2.data);
          this.treeData = resp1.data.children;
          this.checkedKeys = resp2.data;
          this.completed = true;
        }
      );
    },
    /*change事件*/
    change() {
      if (!this.completed) {
        return;
      }

      this.initTree(
        this.form.orgId,
        this.form.roleId,
        this.form.privilegeGroupId
      );
    },
    rootOrgChanged() {
      if (!this.completed) {
        return;
      }

      var url =
        core_api +
        "/rolePrivilege/getRoles?includeSuperAdmin=" +
        false +
        "&rootOrgId=" +
        this.form.orgId;
      this.$http
        .post(url)
        .then(response => {
          this.roleList = response.data;
          if (0 < this.roleList.length) {
            this.form.roleId = this.roleList[0].roleId;
          }
        })
        .catch(response => {
          if (response.status == 500) {
            this.$notify({
              showClose: true,
              message: response.data.desc,
              type: "error"
            });
          }
        });

      this.initTree(
        this.form.orgId,
        this.form.roleId,
        this.form.privilegeGroupId
      );
    },
    treeChange(node, checked) {
      console.log("[tree change] node:", node);
      if (checked && !this.checkedKeys.contains(node.id)) {
        this.checkedKeys.push(node.id);
      }
      if (!checked && this.checkedKeys.contains(node.id)) {
        this.checkedKeys.remove(node.id);
      }

      var checkChildren = this.uncheckChildren_nodeId != node.id;
      this.uncheckChildren_nodeId = null;
      if (checked) {
        if (node.parentId) {
          this.uncheckChildren_nodeId = node.parentId;
          this.$refs.tree.setChecked(node.parentId, true, false);
        }
        if (checkChildren) {
          if (node.children && 0 < node.children.length) {
            for (const cur of node.children) {
              this.$refs.tree.setChecked(cur.id, true, false);
            }
          }
        }
      } else {
        if (node.children && 0 < node.children.length) {
          for (const cur of node.children) {
            this.$refs.tree.setChecked(cur.id, false, false);
          }
        }
      }

      this.treeChanged = true;
    },
    save() {
      console.log("save(). checkedKeys:", this.checkedKeys);
      var url = core_api + "/rolePrivilege/updateRolePrivilegeRelations";
      this.$http
        .post(url, {
          rootOrgId: this.form.orgId,
          roleId: this.form.roleId,
          privilegeGroupId: this.form.privilegeGroupId,
          privilegeIdSet: this.checkedKeys
        })
        .then(() => {
          this.$notify({
            message: "更新成功",
            type: "success"
          });
          this.treeChanged = false;
        })
        .catch(response => {
          if (response.status == 500) {
            this.$notify({
              showClose: true,
              message: response.data.desc,
              type: "error"
            });
          }
        });
    }
  },
  created() {
    this.init();
  }
};
</script>

<style scoped>
.el-radio-group {
  margin-top: 5px;
}
</style>
