<template>
  <div class="cus_vtree_wrap" @click.capture="clickNodeWrap">
    <v-tree-item
      :treeData="treeData"
      @clickNodeCom="clickNode"
      :checkBox="checkBox"
      :class="{ tree_root_lonely: treeData.length === 1 }"
      @toggleCheckBox="checkBoxFun"
      @saveFolder="handleSaveFolder"
      @cancelCreate="cancelCreate"
    ></v-tree-item>
  </div>
</template>
 
<script>
export default {
  name: "vue-tree",
  props: ["treeData", "checkBox"],
  data() {
    return {
      //userData:this.treeData
    };
  },
  mounted() {
    this.initData(true, true, true);
  },
  updated() {
    // this.initData(true, true, true);
  },
  methods: {
    initData(expandInit, activeInit, checkedInit) {
      var self = this;
      var modifyDataFun = function (datas) {
        if (datas) {
          datas.forEach((m, index) => {
            if (expandInit) {
              self.$set(m, "expand", false);
            }
            if (activeInit) {
              self.$set(m, "active", false);
            }
            if (checkedInit) {
              self.$set(m, "checked", false);
              self.$set(m, "partchecked", false);
            }
            if (index === datas.length - 1) {
              self.$set(m, "last", true);
            }
            if (m.children) {
              modifyDataFun(m.children);
            }
          });
        }
      };
      modifyDataFun(this.treeData);
    },
    clickNode(data) {
      this.$set(data, "expand", true);
      this.$emit("clickNode", data);
    },
    clickNodeWrap() {
      this.initData(false, true, false);
    },
    checkBoxFun(item) {},
    getCheckedNodes() {
      var resultArr = [];
      var getCheckedNodesFun = (datas) => {
        if (datas) {
          datas.forEach((m) => {
            if (m.checked === true) {
              resultArr.push(m);
            }
            if (m.children) {
              getCheckedNodesFun(m.children);
            }
          });
        }
      };
      getCheckedNodesFun(this.treeData);
      return resultArr;
    },
    getRoot() {
      return this.treeData[0];
    },
    findNode(selectedId) {
      var result;
      var findNodeFun = (datas) => {
        if (datas) {
          try {
            datas.forEach((m) => {
              if (m.id === selectedId) {
                result = m;
                throw new Error("stop");
              }
              if (m.children) {
                findNodeFun(m.children);
              }
            });
          } catch (e) {}
        }
      };
      findNodeFun(this.treeData);
      return result;
    },
    setSelectedNode(node, clickDiv) {
      var select;
      var that = this;
      var setSelectedFun = (datas) => {
        if (datas) {
          datas.forEach((m) => {
            if (m.id === node.id) {
              m.active = true;
              select = m;
              if (clickDiv) {
                var dom = document.getElementById(m.id);
                if (dom && dom.className.indexOf("cus_item_content") > -1) {
                  dom.click();
                } else {
                  var doms = document.getElementsByClassName(
                    "cus_item_content"
                  );
                  for (var y = 0; y < doms.length; y++) {
                    if (doms[y].id === m.id) {
                      doms[y].click();
                      break;
                    }
                  }
                }
              }
            } else {
              m.active = false;
            }
            if (m.children) {
              setSelectedFun(m.children);
            }
          });
        }
      };
      setSelectedFun(this.treeData);
      return select;
    },
    getSelectedNode() {
      var resultNode = null;
      var getSelectedFun = (datas) => {
        if (datas) {
          datas.forEach((m) => {
            if (m.active === true) {
              resultNode = m;
              return;
            }
            if (m.children) {
              getSelectedFun(m.children);
            }
          });
        }
      };
      getSelectedFun(this.treeData);
      return resultNode;
    },
    getParentNode(node) {
      var resultNode = null;
      var getParentNode = (datas, parent) => {
        if (datas) {
          try {
            datas.forEach((m) => {
              if (node && m.id === node.id) {
                resultNode = parent;
                throw new Error("Stop");
              }
              if (!resultNode && m.children) {
                getParentNode(m.children, m);
              }
            });
          } catch (e) {}
        }
      };
      getParentNode(this.treeData, null);
      return resultNode;
    },
    getParentNodesArr(node) {
      var resultArr = [];
      var parentNode;
      var getParent = (target) => {
        parentNode = this.getParentNode(target);
        if (parentNode) {
          resultArr.push(parentNode);
          getParent(parentNode);
        }
      };
      getParent(node);
      return resultArr;
    },
    handleSaveFolder (item, folderName) {
      this.$emit('saveFolder', item, folderName)
    },
    cancelCreate (item) {
      this.$emit('cancelCreate', item)
    }
  },
  components: {
    "v-tree-item": {
      name: "v-tree-item",
      template:
				`<ul class="cus_tree_ul" :class="{cus_tree_ulLine:(sortTreeData && sortTreeData.length)}">
					<li v-for="item in sortTreeData">
						<div class="cus_item_content" :title="item.name" @click="clickNode(item)" :id= item.id   :class="{active:item.active}">
              <div v-if="item.active"></div>
							<h-icon class="treeExpandBtn" @click.stop="toggleNode(item)" :class="{'no-child': !item.children || item.children.length === 0}" :type="item.expand && item.children.length > 0 ? 'jianhao' : item.children.length ? 'jiahao' : ''"></h-icon>
              <span class="tree-icon" :type="item.icon"></span>
							<span v-if="checkBox" @click="checkBoxClick(item)" class="cus_chekcbox" :class="{cus_chekcbox_checked: item.checked, cus_chekcbox_part_checked: item.partchecked}"></span>
              <span v-if="item.name">{{item.name}}</span>
              <div v-else>
                <input maxLength=12 class="folder-name-input" v-model="folderName" @keyup.enter="handleSaveFolder(item, folderName)" placeholder="输入文件夹名称，Enter完成" />
                <h-icon class="folder-name-close" type="guanbi" @click.stop="cancelCreate(item)" />
              </div>
						</div>
					<v-tree-item :treeData="item.children" @cancelCreate="cancelCreate" v-if="item.expand" @clickNodeCom="clickNodeCom" @saveFolder="handleSaveFolder"  :checkBox="checkBox" :class="{cus_checkbox_allchecked:item.checked}" @toggleCheckBox="checkBoxFun(item)" ></v-tree-item>
					</li
				></ul>`,

      methods: {
        cancelCreate (item) {
          this.folderName = ''
          this.$emit('cancelCreate', item)
        },
        clickNode(item) {
          item.active = true;
          this.$emit("clickNodeCom", item);
        },
        toggleNode(item) {
          item.expand = !item.expand;
          item.active = true;
        },
        clickNodeCom(data) {
          this.$emit("clickNodeCom", data);
        },
        handleSaveFolder (item, folderName) {
          this.$emit('saveFolder', item, folderName)
        },
        checkBoxClick(item) {
          item.partchecked = false;
          item.checked = !item.checked;
          //设置子元素是否勾选
          var checkChildFun = (childrenDatas) => {
            childrenDatas.forEach((m) => {
              m.checked = item.checked;
              if (m.children) {
                checkChildFun(m.children);
              }
            });
          };
          if (item.children) {
            checkChildFun(item.children);
          }

          this.$emit("toggleCheckBox");
        },
        checkBoxFun(item) {
          var checkedNum = 0;
          var partCheckedNum = 0;
          item.children.forEach((li) => {
            if (li.checked === true) {
              checkedNum++;
            } else if (li.partchecked === true) {
              partCheckedNum++;
            }
          });
          if (checkedNum === item.children.length) {
            //全选
            item.checked = true;
            item.partchecked = false;
          } else if (checkedNum > 0 || partCheckedNum > 0) {
            //部分勾选
            item.checked = false;
            item.partchecked = true;
          } else {
            //没有勾选
            item.checked = false;
            item.partchecked = false;
          }

          this.$emit("toggleCheckBox");
        },
      },
      props: ["treeData", "checkBox"],
      computed: {
        sortTreeData () {
          return this.treeData.map(item => {
            if (!item.children) {
              item.children = []
            }
            return item
          })
        }
      },
      data () {
        return {
          folderName: ''
        }
      }
    },
  },
};
</script>
 
<style lang="less" >
.cus_vtree_wrap > ul:first-child {
  background-image: none;
}
ul.cus_tree_ul {
  padding-left: 30px;
  background-position: 4px 10px;
  background-repeat: repeat-y;
}
li:last-child > ul.cus_tree_ul:last-child {
  background-image: none;
}

ul.cus_tree_ul li {
  text-align: left;
  cursor: pointer;
  list-style: none;
}

.cus_item_content .treeExpandBtn {
  display: inline-block;
  width: 14px;
  height: 14px;
	margin-right: 0;
	border: 1px solid #EBEBEB;
	line-height: 14px;
	font-size: 12px;
  /* background-image:url('../images/zTreeStandard.png'); */
  &.no-child {
    border: none;
  }
}

ul.cus_tree_ul li .cus_item_content {
  position: relative;
  padding: 4px;
  white-space: nowrap;
  // overflow-x: hidden;
  display: flex;
  align-items: center;
}
ul.cus_tree_ul li .cus_item_content:hover {
  /* background:#8f83e1; */
  color: #15BEC8;
}
ul.cus_tree_ul li .cus_item_content.active {
  /* background:#7663f8; */
  color: #15BEC8;
  & > * {
    position: relative;
  }
  > div {
    content: '';
    display: block;
    top: 0;
    position: absolute;
    width: 10000%;
    left: -500%;
    background: #e3f5f6;
    background: rgba(227, 245, 246, 1);
    height: 30px;
    z-index: 0;
  }
}

.folder {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 6px;
  /* background-image:url('../images/zTreeStandard.png'); */
  background-position: -110px -0px;
}
.file {
  display: inline-block;
  width: 18px;
  height: 18px;
  margin-right: 6px;
  /* background-image:url('../images/zTreeStandard.png'); */
  background-position: -110px -30px;
}
.cus_item_content {
  color: #909090;
}
.tree-icon {
  /* color: #15BEC8; */
  /* font-size: 18px; */
  margin: 0 4px 0 10px;
  display: inline-block;
  width: 18px;
  height: 14px;
  background: url(~@/assets/images/refactor/usercenter/folder.png) no-repeat center center;
  background-size: cover;
  flex-shrink: 0;
}
.folder-name-input {
  border: none;
  border-bottom: 1px solid #909090;
  line-height: 18px;
  font-size: 12px;
  width: 155px;
}
.folder-name-close {
  color: #323233;
}
</style>