<template>
  <div>
    <template v-for="(item, i) in list">
      <div
        :key="item.id"
        :class="[
          'tree-node',
          { selected: currentCourse === item.id },
          { children: depth > 0 },
          { 'has-children': item.is_leaf === 'false' }
        ]"
      >
        <div
          class="tree-node-name"
          :style="{ 'font-weight': depth === 0 || item.nodes ? 700 : 400 }"
          @click="handleTreeClick(item.is_leaf === 'true', i, item.id)"
        >
          <span class="tree-node-name-leaf">
            <i
              v-if="item.is_leaf === 'false'"
              :class="[scopesDefault[i] ? 'el-icon-arrow-down' : 'el-icon-arrow-right']"
            />
          </span>
          <span>{{ item.name }}</span>
        </div>
        <div v-if="item.is_leaf === 'false'" class="tree-node-children">
          <tree-menus
            v-show="scopesDefault[i]"
            :list="item.nodes"
            :depth="depth + 1"
            :current-course="currentCourse"
            @curCourse="curCourse"
          />
        </div>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'TreeMenus',
  props: {
    list: {
      default() {
        return [];
      },
      type: Array
    },
    depth: {
      default: 0,
      type: Number
    },
    currentCourse: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      scopesDefault: [],
      scopes: []
    };
  },
  created() {
    this.scope();
  },
  methods: {
    scope() {
      this.list.forEach((item, i) => {
        this.scopesDefault[i] = false;
        if ('nodes' in item) {
          this.scopes[i] = true;
        } else {
          this.scopes[i] = false;
        }
      });
    },
    curCourse(val) {
      this.$emit('curCourse', val);
    },
    handleTreeClick(is_leaf, i, id) {
      if (is_leaf) {
        this.curCourse(id);
        return false;
      } else if (this.scopesDefault[i] === true) {
        this.$set(this.scopesDefault, i, false);
      } else {
        this.$set(this.scopesDefault, i, this.scopes[i]);
      }
    }
  }
};
</script>

<style lang="scss">
.tree-node {
  &-name {
    display: flex;
    padding: 12px 0;
    cursor: pointer;
    font-weight: 700;

    :nth-child(2):hover {
      color: $basicColor;
    }

    &-leaf {
      display: inline-block;
      width: 20px;
    }
  }

  &.selected {
    background-color: $basicColor;
    color: #fff;
  }

  &.children {
    &.has-children {
      margin-left: 20px;
    }
  }

  &:not(.has-children) .tree-node-name:hover {
    color: #fff;
    background-color: $basicColor;

    :nth-child(2):hover {
      color: #fff;
    }
  }
}
</style>
