<template>
  <div class="flex-h card-height-full org-mgr-div">
    <Panel title="系统组织机构一览" v-if="rightBlock" class="flex-2 full">
      <template slot="buttons">
        <el-button class="blue" icon="el-icon-fa-expand" @click="expandAll">展开</el-button>
        <el-button class="blue" icon="el-icon-fa-check-square-o" @click="checkNode">检查节点</el-button>
        <el-button class="blue" icon="el-icon-fa-wrench" @click="repairNode">修复节点</el-button>
        <el-button class="green" :icon="!leftBlock?'el-icon-caret-left':'el-icon-caret-right'" @click="leftBlock=!leftBlock"/>
      </template>
      <el-tree v-if='showOrgTree' ref="orgTree" :default-expand-all="expandedAll" v-loading="saving"
               lazy :load="loadTree" node-key="uuid" :current-node-key="currNode.uuid" :expand-on-click-node="false" highlight-current
               @current-change="currentChange" :props="treeProps">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <span :class="{'removed-line-through' : data.orgStat === '0'}"></span>

                        <span><i class='el-icon-fa el-icon-fa-sitemap margin-right-2'/>{{data.orgName}}</span>

                        <span>{{data.permName}}</span>
                    </span>
                    <el-button-group>
                        <el-button icon="el-icon-fa-refresh" @click.stop="refreshNode(node)"/>
                        <el-button icon="el-icon-fa-plus" @click.stop="addNode(node)"/>
                        <el-button icon="el-icon-fa-minus" @click.stop="removeNode(node)" :disabled="data.puuid === 'none'"/>
                    </el-button-group>
                </span>
      </el-tree>
    </Panel>
    <Panel title="组织机构编辑" v-if="leftBlock" class="flex-2 margin-left-2 full">
      <template slot="buttons">
        <el-button class="blue" @click="showMore=!showMore" icon="el-icon-more" v-if='currNode.puuid!=="none"&&currNode.uuid'>高级
        </el-button>
        <el-button class="blue" @click="onSubmit" icon="el-icon-fa-save" v-if='currNode.puuid!=="none"&&currNode.uuid'>保存
        </el-button>
        <el-button class="green" :icon="rightBlock?'el-icon-caret-left':'el-icon-caret-right'" @click="rightBlock=!rightBlock"/>
      </template>
      <el-form ref="form" :rules="rules" :model="currNode" label-position='top' v-if='currNode.puuid!=="none"&&currNode.uuid'>
        <el-row>
          <el-col :span="24">
            <el-form-item label="组织机构编码" prop="orgCode" :error="editor.error.orgCode">
              <el-input v-model="currNode.orgCode" maxlength='32'/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop='puuid' label="上级组织机构">
              <Selector v-model="currNode.puuid" :init-label="currParentNode.orgName" :clearable="true" label-key="label"
                        value-key="id" placeholder="隶属组织机构">
                <SelectorTree tree-key="orgTree" rootLabel="系统组织机构"/>
              </Selector>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织机构名称" prop="orgName" :error="editor.error.orgName">
              <el-input v-model="currNode.orgName" maxlength='64'/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织机构描述" prop="orgDesc" :error="editor.error.orgDesc">
              <el-input type="textarea" v-model="currNode.orgDesc" maxlength='256'/>
            </el-form-item>
          </el-col>

          <template v-if="showMore">
            <el-col :span="24">
              <el-form-item label="负责人" prop="orgMast" :error="editor.error.orgMast">
                <el-input v-model="currNode.orgMast" maxlength='32'/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="组织机构状态" prop="orgStat" :error="editor.error.orgStat">
                <el-radio-group v-model="currNode.orgStat">
                  <el-radio label="1">可用</el-radio>
                  <el-radio label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="组织机构简称" prop="orgBrfName" :error="editor.error.orgBrfName">
                <el-input type="textarea" v-model="currNode.orgBrfName" maxlength='16'/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="邮政编码" prop="orgPost" :error="editor.error.orgPost">
                <el-input v-model="currNode.orgPost" maxlength='16'/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="地址" prop="orgAddr" :error="editor.error.orgAddr">
                <el-input type="textarea" v-model="currNode.orgAddr" maxlength='256'/>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>

      <OptionHistory v-if='currNode.puuid !== "none" && currNode.uuid' :data="currNode"/>
    </Panel>
  </div>
</template>
<script>
  import OrgAPI from "@/api/base/usrm/OrgAPI";
  import OptionHistory from "@/common/OptionHistory.vue";
  import SelectorTree from "@/common/SelectorTree";

  export default {
    name: "OrgMgr",
    components: {OptionHistory, SelectorTree},
    data() {
      return {
        showMore: false,
        leftBlock: true,
        rightBlock: true,
        //显示树
        showOrgTree: true,
        currParentNode: {},
        currNode: {},
        saving: false,
        expandedAll: false,
        editor: {
          error: {}
        },
        rules: {
          orgCode: [{required: true, message: "组织机构编码不能为空!"}],
          puuid: [{required: true, message: "上级组织机构不能为空!"}],
          orgName: [{required: true, message: "组织机构名称不能为空!"}]
        },
        treeProps: {
          isLeaf: "isLeaf"
        }
      };
    },
    mounted() {
    },
    methods: {
      getTreeListen(orgId) {
        OrgAPI.getCopyRoleTree(orgId).then(resp => {
          if (this.$refs.roleTree) {
            this.$refs.roleTree.root.setData({children: resp.data});
            if (this.data.arrRoles) {
              this.$refs.roleTree.setCheckedKeys(this.data.arrRoles, false);
            }
          }
        });
      },
      /**
       * 检查节点
       */
      repairNode() {
        OrgAPI.repairNode(this.currNode.uuid);
      },
      /**
       * 修复节点异常
       */
      checkNode() {
        OrgAPI.checkNode(this.currNode.uuid);
      },
      // 提交数据
      onSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.saving = true;
            this.editor.error = {};
            OrgAPI.editNode(this.currNode)
              .then(data => {
                this.saving = false;
                this.expandAll();
                this.expandedAll = true;
              })
              .catch(error => {
                this.editor.error = error.validError;
                this.saving = false;
              });
          }
        });
      },
      //  展开/关闭 全部
      expandAll() {
        if (this.expandedAll) {
          this.saving = true;
          this.showOrgTree = false;
          this.expandedAll = false;
          setTimeout(() => {
            this.showOrgTree = true;
            this.saving = false;
          }, 200);
          return;
        }
        this.expandedAll = true;
        let expandFn = (element, expand) => {
          element.childNodes.forEach(element => {
            if (!element.isLeaf) {
              element.expand(() => {
                expandFn(element);
              });
            }
          }, this);
        };
        expandFn(this.$refs.orgTree.root);
      },
      // 点击菜单树节点
      currentChange(data, node) {
        this.currParentNode = node.parent.data || data;
        this.currNode = data || {};
      },
      // 加载树内容
      loadTree(node, resolve) {
        let puuid = "none";
        if (node.data) {
          puuid = node.data.uuid;
        }
        OrgAPI.getChildren(puuid).then(resp => resp.data && resolve(resp.data));
      },
      // 新增菜单
      addNode(node) {
        let newNode = {
          orgName: "新建组织机构",
          orgCode: "请填写组织机构代码",
          orgStat: "1",
          puuid: node.data.uuid
        };
        this.saving = true;
    //    this.currParentNode.orgName = node.data.orgName;
        OrgAPI.editNode(newNode)
          .then(data => {
            Object.assign(newNode, {
              uuid: data.uuid,
              opUserUuid: this.$store.state.base.sysUser.uuid,
              crUserUuid: this.$store.state.base.sysUser.uuid
            }); // 合并刚才返回的UUID主键
            this.saving = false; // 保存结束
            node.insertChild({data: newNode}); // 让当前节点追加一个新节点
            node.expand(() => {
              this.currNode = newNode;
            }); // 如果没拉取子节点,先拉取子节点,然后设置当前节点
          })
          .catch(() => {
            this.saving = false;
          });
      },
      // 删除菜单
      removeNode(node) {
        // 删除菜单实际要执行的方法
        let action = data => {
          this.saving = true;
          OrgAPI.delNode(data.uuid)
            .then(data => {
              this.saving = false;
              node.parent.removeChild(node);
            })
            .catch(() => {
              this.saving = false;
            });
        };
        // 单出提示,然后执行该方法
        this.confirm(node.data).then(action);
      },
      // 刷新菜单
      refreshNode(node) {
        node.loaded = false;
        node.expand(() => {
        });
      }
    }
  };
</script>

<style lang="scss">
  .org-mgr-div {
    & > .la-panel {
      height: calc(100vh - 117px);

      & > .la-panel__body {
        overflow-y: auto;
      }
    }
  }
</style>
