<template>
 <div class="cascader" v-click-outside="close">
  <div class="trigger" @click="toggle">{{result}}</div>
  <div v-if="isVisible">
   <CascaderItem :options="options" :value="value" :level="level" @change="change"></CascaderItem>
  </div>
 </div>
</template>
<script>
import cloneDeep from "lodash/cloneDeep";
import CascaderItem from "./CascaderItem";

export default {
 components: {
  CascaderItem
 },
 computed: {
  result() {
   return this.value.map(item => item.label).join("/");
  }
 },
 props: {
  lazyload: {
   type: Function
  },
  level: {
   type: Number,
   default: 0
  },
  value: {
   type: Array,
   default: () => []
  },
  options: {
   type: Array,
   default: () => []
  }
 },
 directives: {
  clickOutside: {
   inserted(el, bindings) {
    document.addEventListener("click", e => {
     if (el === e.target || el.contains(e.target)) {
      return;
     }
     bindings.value();
    });
   }
  }
 },
 data() {
  return { isVisible: false };
 },
 methods: {
  handle(id, children) {
   // id当前选择的 children 需要增加的孩子
   const cloneValue = cloneDeep(this.options);
   let stack = [...cloneValue];
   let index = 0;
   let current;
   while ((current = stack[index++])) {
    if (current.id !== id) {
     if (current.children) {
      stack = stack.concat(current.children);
     }
    } else {
     break;
    }
   }
   // current就是当前我要找的
   if (current) {
    current.children = children;
    console.log(current, "----");
    //    this.$set(current,'children',children);
    this.$emit("update:options", cloneValue);
   }
  },
  change(value) {
   const lastItem = value[value.length - 1];
   const { id } = lastItem;
   if (this.lazyload) {
    this.lazyload(id, data => this.handle(id, data));
   }
   this.$emit("input", value);
  },
  toggle() {
   this.isVisible = !this.isVisible;
  },
  close() {
   this.isVisible = false;
  }
 }
};
</script>
<style lang="stylus">
.trigger {
 width: 150px;
 height: 30px;
 line-height: 30px;
 border: 1px solid #ccc;
}

.content {
 display: flex;
}

.content-left {
 border: 1px solid #ccc;
 max-height: 200px;
 overflow-y: scroll;
}

.content-right {
 position: relative;
 margin-left: -1px;
}

.label {
 font-size: 14px;
 width: 80px;
 line-height: 20px;
}

.label:hover {
 background: #ccc;
}
</style>
