<!--
 * @Author: Billy
 * @Date: 2021-12-29 17:34:35
 * @LastEditors: Billy
 * @LastEditTime: 2022-01-04 21:51:32
 * @Description: 请输入
-->
<template>
  <PageSplit
    class="split-pane"
    :distribute="0.15"
    :lineThickness="6"
    :firstMinValue="200"
    :isVertical="true"
    @resizeLineStartMove="onResizeLineStartMove"
    @resizeLineMove="onResizeLineMove"
    @resizeLineEndMove="onResizeLineEndMove"
  >
    <template v-slot:first>
      <div class="container">
        <div class="title title-flex-both">
          <span class="title-inner">组织架构</span>
        </div>
        <div class="content">
          <el-tree
            ref="org-tree"
            v-loading="vloadingOrgTree"
            :data="orgTreeData"
            :node-key="'id'"
            :props="treeProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            :default-expanded-keys="defaultExpandedKeys"
            :render-content="renderTreeNodeContent"
            @node-click="onTreeNodeClick"
            @current-change="onOrgTreeCurrChange"
          ></el-tree>
        </div>
      </div>
    </template>
    <template v-slot:second>
      <div class="container">
        <div class="title title-flex-right">
          <el-button size="mini" type="primary" @click="onAddUserBtnClick"
            >新建用户</el-button
          >
        </div>
        <div class="content">
          <UserList
            ref="user-list"
            :orgId="currSelectedOrg.id"
            :orgTreeData="orgTreeData"
          />
        </div>
      </div>
    </template>
    <div class="others">
      <UserAdd
        :org="currSelectedOrg"
        :isVisible.sync="isDialAddUserVisible"
        @user-add-success="onUserAddSuccess"
      />

      <el-dialog
        title="新建部门"
        width="30%"
        :visible.sync="isDialAddDeptVisible"
        :before-close="onDialAddDeptClose"
        @open="onDialAddDeptOpen"
      >
        <OrgAdd
          ref="org-add-form"
          :org="currEditingOrg"
          @cancel="isDialAddDeptVisible = false"
          @success="onOrgAddSuccess"
        />
      </el-dialog>

      <el-dialog
        title="编辑部门"
        width="30%"
        :visible.sync="isDialEditDeptVisible"
        :before-close="onDialEditDeptClose"
        @open="onDialEditDeptOpen"
      >
        <OrgEdit
          ref="org-edit-form"
          :org="currEditingOrg"
          @cancel="isDialEditDeptVisible = false"
        />
      </el-dialog>

      <el-dialog
        title="移动部门"
        width="50%"
        :visible.sync="isDialMoveDeptVisible"
        :before-close="onDialMoveDeptClose"
        @open="onDialMoveDeptOpen"
      >
        <OrgMove
          ref="org-move-form"
          :org="currEditingOrg"
          :treeData="orgTreeData"
          @cancel="isDialMoveDeptVisible = false"
          @success="onOrgMoveSuccess"
        />
      </el-dialog>
    </div>
  </PageSplit>
</template>
<script>
import PageSplit from "vue-page-split";
import UserList from "../../components/Rbac/User/UserList4Org.vue";
import UserAdd from "../../components/Rbac/User/UserAdd.vue";
import OrgAdd from "../../components/Rbac/Organization/OrgAdd.vue";
import OrgEdit from "../../components/Rbac/Organization/OrgEdit.vue";
import OrgMove from "../../components/Rbac/Organization/OrgMove.vue";
import TreeNodeWith3Dots from "../../components/_Common/Tree/TreeNodeWith3Dots.vue";

import OrganizationBiz from "../../biz/Rbac/Organization.js";

// 空间树根节点
const ORG_ROOT = {
  name: "COMPANY",
  id: -1,
};

export default {
  components: { PageSplit, UserList, UserAdd, OrgEdit, OrgAdd, OrgMove },
  data() {
    return {
      treeProps: {
        label: "name",
        children: "Children",
      },
      orgTreeData: [], // 组织架构树数据
      vloadingOrgTree: false, // 组织架构树是否正在loading
      defaultExpandedKeys: [ORG_ROOT.id], // 组织架构树默认展开的节点id(默认展开根节点)
      isDialAddUserVisible: false, // 添加用户对话框是否显示

      isDialEditDeptVisible: false, // 编辑部门对话框是否显示
      isDialAddDeptVisible: false, // 新建部门对话框是否显示
      isDialMoveDeptVisible: false, // 移动部门对话框是否显示

      currSelectedOrg: ORG_ROOT, // 当前选中的部门id（什么都没选中，视为选中根节点）
      currEditingOrg: {
        id: ORG_ROOT.id, // 当前选中的部门id（什么都没选中，视为选中根节点）
        name: ORG_ROOT.name, // 当前选中的部门名称
      },
    };
  },
  async mounted() {
    //加载组织架构树
    this.orgTreeData = await this.getAllNodesWithRoot();
    this.$nextTick(() => {
      // let rootNode = this.$refs["org-tree"].getNode(this.orgTreeData[0]);
      // console.log("rootNode :>> ", rootNode);
      this.$refs["org-tree"].setCurrentKey(ORG_ROOT.id);
    });
  },
  methods: {
    // “添加用户”按钮被点击时
    onAddUserBtnClick() {
      this.isDialAddUserVisible = true;
    },

    // 当添加用户窗口添加用户成功时
    onUserAddSuccess(userId) {
      this.$refs["user-list"].goToLastPage();
    },

    // “新建部门”的对话框的确定按钮被点击时
    onNewDeptConfirmClick() {
      this.$refs["new-org-form"].validate(async (valid) => {
        if (valid) {
          try {
            let orgs = await OrganizationBiz.findByName(this.newOrg.name);
            let _org = orgs.find(
              (org) =>
                org.name === this.newOrg.name &&
                org.parentId === this.newOrg.parentNode.id
            );

            if (_org) {
              this.$message({ type: "error", message: "不能有同名节点" });
            } else {
              let newOrg = await OrganizationBiz.add(
                this.newOrg.parentNode.id,
                this.newOrg.name
              );
              this.orgTreeData = await this.getAllNodesWithRoot();
              this.defaultExpandedKeys[0] = newOrg.id;
            }
          } catch (e) {
            this.$message({ type: "error", message: e.message });
          }
        }
      });
    },

    // “新建部门”的对话框的退出按钮被点击时
    onNewDeptQuitClick() {
      this.isDialNewDeptVisible = false;
    },

    // “新建部门”的对话框的❌被点击时
    onDialAddDeptClose(done) {
      done();
    },

    // “编辑部门”的对话框的❌被点击时
    onDialEditDeptClose(done) {
      done();
    },

    // “移动部门”的对话框的❌被点击时
    onDialMoveDeptClose(done) {
      done();
    },

    onTreeNodeClick() {},

    // 当组织架构树被改变选中时
    onOrgTreeCurrChange(data, node) {
      this.currSelectedOrg = data;
    },

    // 当添加子部门的对话框的open事件被触发时
    onDialAddDeptOpen() {
      let $refForm = this.$refs["org-add-form"];
      // 第一次打开dialog时，表单会不存在
      if ($refForm) {
        $refForm.updateForm();
      }
    },

    // 当编辑部门的对话框的open事件被触发时
    onDialEditDeptOpen() {
      let $refForm = this.$refs["org-edit-form"];
      // 第一次打开dialog时，表单会不存在
      if ($refForm) {
        $refForm.updateForm();
      }
    },

    // 当移动部门的对话框的open事件被触发时
    onDialMoveDeptOpen() {
      let $refForm = this.$refs["org-move-form"];
      // 第一次打开dialog时，表单会不存在
      if ($refForm) {
        $refForm.updateForm();
      }
    },

    // 当添加子部门成功时
    async onOrgAddSuccess(currNodeData, newSubNodeData) {
      let treeNode = this.$refs["org-tree"].getNode(currNodeData); // 获取子部门的父部门树节点对象
      this.$refs["org-tree"].append(newSubNodeData, treeNode); // 在父部门树节点对象下加入子部门
      // this.$refs["org-tree"].append(newSubNodeData, currNodeData.id); // 在父部门树节点对象下加入子部门
      this.defaultExpandedKeys = [newSubNodeData.id]; // 展开父部门
    },

    // 当移动部门的对话框里移动部门成功时
    onOrgMoveSuccess(currNodeData, targetParentData) {
      // console.log("currNodeData :>> ", currNodeData);
      // console.log("targetParentData :>> ", targetParentData);
      // let treeNode = this.$refs["org-tree"].getNode(currNodeData.id); // 获取子部门的树节点对象
      let parentTreeNode = this.$refs["org-tree"].getNode(targetParentData); // 获取子部门的目标父部门树节点对象
      let subTreeNode = this.$refs["org-tree"].getNode(currNodeData); // 获取子部门的树节点对象
      this.$refs["org-tree"].remove(subTreeNode);
      this.$refs["org-tree"].append(currNodeData, parentTreeNode);
    },

    // 获取所有组织架构节点，并在最外层加上root节点
    async getAllNodesWithRoot() {
      this.vloadingOrgTree = true;
      let allTreeData = await OrganizationBiz.getAllNodes(null);
      this.vloadingOrgTree = false;
      let treeRoot = { ...ORG_ROOT };
      treeRoot.Children = allTreeData;
      return [treeRoot];
    },

    // 渲染组织架构树节点内容的函数
    renderTreeNodeContent(h, { node, data, store }) {
      return (
        <TreeNodeWith3Dots
          data={data}
          btns={data.id ? ["edit", "add", "move", "delete"] : ["add"]}
          addBtnName={"新增子部门"}
          on-menu-select={(index, indexPath, data) => {
            switch (index) {
              case "add":
                this.isDialAddDeptVisible = true;
                this.currEditingOrg = data;
                break;
              case "edit":
                this.isDialEditDeptVisible = true;
                this.currEditingOrg = data; // 这样在OrgEdit中可以直接修改组织架构树的部门名
                // this.currEditingOrg.id = data.id;
                // this.currEditingOrg.name = data.name;
                break;
              case "move":
                this.currEditingOrg = data;
                this.isDialMoveDeptVisible = true;
                break;
              case "delete":
                this.currEditingOrg = data;
                this.$confirm(`确定删除部门 ${this.currEditingOrg.name}?`, {
                  title: "确认删除",
                  showCancelButton: true,
                  showConfirmButton: true,
                })
                  .then(async () => {
                    try {
                      let count = await OrganizationBiz.delById(
                        this.currEditingOrg.id
                      );
                      if (count) {
                        this.$message.success(
                          `部门 ${this.currEditingOrg.name} 删除成功`
                        );
                        this.$refs["org-tree"].remove(this.currEditingOrg);
                      } else {
                        this.$message.success(
                          `部门 ${this.currEditingOrg.name} 删除失败`
                        );
                      }
                    } catch (e) {
                      this.$message.success(
                        `部门 ${this.currEditingOrg.name} 删除失败，原因：${e.message}`
                      );
                    }
                  })
                  .catch(() => {});
                break;
            }
          }}
        />
      );
    },

    onResizeLineStartMove: function () {},
    onResizeLineMove: function (e) {},
    onResizeLineEndMove: function () {},
  },
};
</script>
<style lang="scss" scoped>
@import "~@/scss/_variables.scss";

$line-height: 28px;
.split-pane {
  // background-color: #fff;
  // border-radius: 8px;
  // border: solid 1px $theme-background-light;
  box-sizing: border-box;
  .pane {
    .container {
      box-sizing: border-box;
      height: 100%;
      padding: 16px;
      .title {
        padding-bottom: 16px;
        border-bottom: 1px solid $theme-background-dark;
        height: $line-height;
        &.title-flex-right {
          display: flex;
          flex-direction: row;
          justify-content: flex-end;
        }
        &.title-flex-both {
          // display: flex;
          // flex-direction: row;
          // justify-content: space-between;
        }
        .title-inner {
          line-height: $line-height;
        }
        .el-button.el-button--text {
          // padding: 0;
        }
      }
      .content {
        padding-top: 16px;
      }
    }
  }
}
</style>