<template>
  <el-container>
    <el-dialog
          id="bpmOrgAddress"
          :title="title"
          :visible.sync="dialogVisible"
          :destroy-on-close=true
          :width="width"
          :modal-append-to-body=false
          :append-to-body=true
          :close-on-click-modal=false
          :before-close="handleClose">
      <template v-if="refresh">
        <div
              v-loading="loading"
              element-loading-text="拼命加载中">
<!--          <el-autocomplete-->
<!--                v-model="treeSearchKey"-->
<!--                size="small"-->
<!--                :fetch-suggestions="treeSearch"-->
<!--                @select="treeSearchSelect"-->
<!--                suffix-icon="el-icon-search"-->
<!--                placeholder="快速查询"-->
<!--                :trigger-on-focus=false-->
<!--                style="width:100%;">-->
<!--            <template slot-scope="{ item }">-->
<!--              <el-tooltip class="item" placement="bottom">-->
<!--                <div slot="content">{{item.pathName}}</div>-->
<!--                <span>{{ item.name }}</span>-->
<!--              </el-tooltip>-->
<!--            </template>-->
<!--          </el-autocomplete>-->
          <div style="height: 300px;overflow: auto;border: 1px solid #f2f2f2;">
            <div class="tree">
              <el-tree
                    ref="tree"
                    :props="treeProps"
                    :show-checkbox="multiple"
                    :expand-on-click-node=false
                    :check-strictly=true
                    :highlight-current=true
                    @node-click="openNode"
                    @node-expand="expandNode"
                    @node-collapse="closeNode"
                    node-key="id"
                    lazy
                    :load="loadNode">
                <span slot-scope="{node, data}">
                  <i class="awsui-iconfont tree-content-icon tree-content-icon-padding" :style="{'color': node.data.icon.color}" v-html="node.data.icon.icon"></i>
                  <span>{{node.label}}</span>
                </span>
              </el-tree>
            </div>
          </div>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <awsui-button class="button-general-color" type="primary" @click="submit">确定</awsui-button>
        <awsui-button @click="cancel">取消</awsui-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
  import awsuiAxios from "../../../../awsuiAxios";

  export default {
    name: "BpmOrgAddress",
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      addressType: {// 地址簿类型，默认部门地址簿，可进行部门department、用户user、角色role组合，逗号分隔
        type: String,
        default: 'department'
      },
      multiple: {// 是否多选
        type: Boolean,
        default: false
      },
      rootDeptId: {// 默认根部门,为空则默认当前人所属单位为根节点
        type: String,
        default: ''
      },
      highSecurityFilter: {// 地址簿过滤三员用户类型 三员开启模式并且地址簿类型包含用户user时有效，系统管理员sysAdmin、安全保密员secAdmin、安全审计员auditor，逗号分割
          type: String,
          default: ''// 例如值为sysAdmin,auditor，则开启三员之后该地址簿不显示系统管理员和安全审计员
      },
      title: {// 标题
        type: String,
        default: ''
      },
      selected: {// 默认选中，比如{'department':[],'user':[],'role':[],'position':[]}，不区分单多选，单选只取第一个值
        type: Object,
        default: function () {
          return {'department':[],'user':[],'role':[],'position':[]}
        }
      }
    },
    data() {
      return {
        refresh: false,
        dialogVisible: false,
        loading: false,
        searchKey: '',
        treeSearchKey: '',
        timeout:  null,
        pid: '',
        width: '500px',
        treeProps: {
          label: 'name',
          isLeaf: 'leaf'
        }
      };
    },
    methods: {
      handleClose(done) {
        this.closeDlalog('cancel');
        done();
      },
      cancel() {
        this.closeDlalog('cancel');
        this.dialogVisible = false;
      },
      submit() {
        this.closeDlalog('save');
        this.dialogVisible = false;
      },
      closeDlalog(type) {// 取消/确定之后的关闭
        if (type == 'save') {
          let result = [];
          if (this.multiple) {// 多选
            result = this.$refs.tree.getCheckedNodes();
          } else {// 单选
            const node = this.$refs.tree.getCurrentNode();
            if (node != null) {
              result.push(node);
            }
          }
          this.$emit('getResult', JSON.parse(JSON.stringify(result)));
        } else {
          this.$emit('cancel');
        }
        // 清空所有数据
      },
      handleNodeClick(data) {
        // console.log(data);
      },
      openNode(obj, node, tree) {// 打开一只模型文件

      },
      treeSearchSelect(item) {
        this.queryTreeByIdAndPath(item.id, item.path);
      },
      treeSearch(key, cb) {
        const that = this;
        if (key != undefined && key.trim() != '') {
          // that.loading = true;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_search',
              addressType: that.addressType,
              rootDeptId: that.rootDeptId,
              name: key
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if (ro.result == 'ok') {
              if (ro.data.length > 0) {
                clearTimeout(that.timeout);
                that.timeout = setTimeout(() => {
                  cb(ro.data);
                }, 3000 * Math.random());
              } else {
                clearTimeout(that.timeout);
              }
            } else {
              clearTimeout(that.timeout);
            }
          }).catch(error=>{
            console.log(error);
          })
        } else {
          clearTimeout(that.timeout);
        }
      },
      queryTreeByIdAndPath(id, path) {// 定位展开某节点
        const that= this;
        const tree = that.$refs.tree;
        // 分隔字符串
        const pathArr = path.split(',');
        let index = 1;
        for (let i = 0; i < pathArr.length; i++) {// 依次展开
          if (i > 0) {
            if (tree.getNode(pathArr[i-1]) != null) {
              setTimeout(that._expandNode(tree, pathArr[i-1]), index * 300);
              index++;
            }
          }
        }
        setTimeout(function() {
          if (tree.getNode(id) != null) {
            tree.setCurrentKey(id);
          }
        }, index * 300);
      },
      _expandNode(tree, id) {
        return function() {
          tree.getNode(id).expand();
        }
      },
      loadNode(node, resolve) {// `动态`加载
        const that = this;
        that.loading = true;
        const data = {
          url:'jd',
          data:{
            cmd: 'com.actionsoft.apps.coe.pal_bpm_org_address_component_subjson',
            addressType: that.addressType,
            pid: '',
            highSecurityFilter: that.highSecurityFilter
          }
        };
        if (node.level === 0) {
          // 获取根目录
          data.data.pid = that.pid;
          data.data.parentType = '';
        } else {
          // 获取其他目录
          data.data.pid = node.data.id;
          data.data.parentType = node.data.type;
        }
        // 查询数据
        awsuiAxios.post(data).then(function (ro) {
          // 设置是否可选中
          if (that.multiple) {// 多选
            const isDept = that.addressType.indexOf('department') > -1;
            const isUser = that.addressType.indexOf('user') > -1;
            const isRole = that.addressType.indexOf('role') > -1;
            const isPosition = that.addressType.indexOf('position') > -1;
            for (let i = 0; i < ro.data.length; i++) {
              const curr = ro.data[i];
              if (curr.type == 'company' || curr.type == 'roleRoot' || curr.type == 'roleGroup' || curr.type == 'positionRoot' || curr.type == 'positionGroup') {
                curr.disabled = true;
              } else {
                if (isDept && curr.type == 'department') curr.disabled = false;
                if (!isDept && curr.type == 'department') curr.disabled = true;
                if (isUser && curr.type == 'user') curr.disabled = false;
                if (!isUser && curr.type == 'user') curr.disabled = true;
                if (isRole && curr.type == 'role') curr.disabled = false;
                if (!isRole && curr.type == 'role') curr.disabled = true;
                if (isPosition && curr.type == 'position') curr.disabled = false;
                if (!isPosition && curr.type == 'position') curr.disabled = true;
              }
            }
          };
          resolve(ro.data);
          that.loading = false;
          if (node.level == 0 && ro.data.length > 0) {
            const tree = that.$refs.tree;
            tree.getNode(ro.data[0].id).expand();
            setTimeout(function(){
              const childNode = tree.getNode(ro.data[0].id).childNodes[0];
              if (childNode != null) {
                childNode.expand();
              }
            }, 500);
          }
        }).catch(error=>{
          console.log(error);
        })
      },
      expandNode(obj, node, tree) {// 展开节点

      },
      closeNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
        node.childNodes = [];
        node.loaded = false;
      },
      refreshNode(id) {// 刷新当前选中节点的子节点，即关闭当前节点后重新打开，会执行loadNode进行自动加载
        if (id == undefined) {// 未指定节点，默认刷新当前选中
          const nodeData = this.$refs.tree.getCurrentNode();
          if (nodeData != null) {
            if (this.$refs.tree.store.nodesMap[nodeData.id] != undefined) {
              this.$refs.tree.store.nodesMap[nodeData.id].expanded = false;
            }
            const node = this.$refs.tree.getNode(nodeData.id);
            this.closeNode(null, node, null);
            node.expand();
          }
        } else {// 指定刷新某节点
          if (this.$refs.tree.store.nodesMap[id] != undefined) {
            this.$refs.tree.store.nodesMap[id].expanded = false;
          }
          const node = this.$refs.tree.getNode(id);
          if (node != null) {
            this.closeNode(null, node, null);
            node.expand();
          }
        }
      }
    },
    watch: {
      visible(val) {
        this.dialogVisible = val;
        if (val) {// 打开
          if (this.addressType.indexOf('department') > 0) {
            this.pid = this.rootDeptId;
          }
          this.refresh = true;
        } else {// 关闭
          this.refresh = false;
        }
      }
    }
  }
</script>

<style scoped>
  #bpmOrgAddress >>> .el-dialog__body {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  #bpmOrgAddress >>> .el-input__inner {
    border-radius: 0px;
  }
  #bpmOrgAddress >>> .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #F5F7FA;
    color: #4E7FF9;
  }
  #bpmOrgAddress >>> .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content .awsui-iconfont {
    color: #4E7FF9 !important;
  }
  /*#bpmOrgAddress >>> .el-tree .el-tree-node>.el-tree-node__children{*/
  /*  overflow: visible;*/
  /*}*/
  .tree{
    overflow: auto;
    width:458px;
    height: 300px;
  }
  #bpmOrgAddress >>> .el-tree {
    min-width: 100%;
    display:inline-block !important;
  }
</style>
