<template>
  <el-container>
    <el-dialog
      id="palRepositoryTree"
      :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-start">
                <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"
                :expand-on-click-node=false
                :highlight-current=true
                @node-click="openNode"
                @node-expand="expandNode"
                @node-collapse="closeNode"
                :show-checkbox=multiple
                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: "PALRepositoryTree",
      props: {
        visible: {
          type: Boolean,
          default: false
        },
        wsId: {// 资产库ID
          type: String,
          default: '',
          required: true
        },
        teamId: {// 小组ID
          type: String,
          default: ''
        },
        categorys: {// 建模大类,多个则逗号分隔
          type: String,
          default: ''
        },
        rootId: {// 父节点，为空则查询根节点
          type: String,
          default: ''
        },
        multiple: {// 是否多选
          type: Boolean,
          default: false
        },
        title: {// 标题
          type: String,
          default: '请选择'
        },
        // width: {// 宽度
        //   type: String,
        //   default: '500px'
        // },
        selected: {// 默认选中，比如[]，不区分单多选，单选只取第一个值
          type: Array,
          default: function () {
            return []
          }
        }
      },
      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.checkbox) {// 多选
                result = this.$refs.tree.getCheckedNodes();
              } else {// 单选
                const node = this.$refs.tree.getCurrentNode();
                if (node != null) {
                  result.push(node);
                }
              }
            this.$emit('getResult', result);
          } else {
            this.$emit('cancel');
          }
          // 清空所有数据
        },
        handleNodeClick(data) {
          console.log(data);
        },
        openNode(obj, node, tree) {// 打开一只模型文件

        },
        treeSearchSelect(item) {
          this.queryTreeByIdAndPath(item.id, item.versionId, 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',
                wsId: that.wsId,
                teamId: that.teamId,
                categorys: that.categorys,
                rootId: that.rootId,
                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, versionId, 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(versionId) != null) {
              tree.setCurrentKey(versionId);
            }
          }, index * 300);
        },
        _expandNode(tree, versionId) {
          return function() {
            tree.getNode(versionId).expand();
          }
        },
        loadNode(node, resolve) {// `动态`加载
          const that = this;
          that.loading = true;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_subjson',
              wsId: that.wsId,
              teamId: that.teamId,
              categorys: that.categorys,
              pid: ''
            }
          };
          if (node.level === 0) {
            // 获取根目录
            data.data.pid = that.pid;
          } else {
            // 获取其他目录
            data.data.pid = node.data.id;
          }
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            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) {// 打开
            this.pid = this.rootId;
            this.refresh = true;
          } else {// 关闭
            this.refresh = false;
          }
        }
      }
    }
</script>

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