<template>
  <div>
    <el-tree v-loading="treeDlgLoading"
      :data="catalogTree"
      :render-content="renderContent"
      :props="defaultProps"
      node-key="id"
      :expand-on-click-node="false"
      :show-checkbox="showCheckBox"
      :default-expand-all="true"
      :highlight-current="true"
      @check-change="getCheckChange"
      @node-click="handleNodeClick"
      ref="tree">
    </el-tree>
  </div>
</template>
<script>
export default {
  data() {
    return {
      treeDlgLoading: false, // 数据加载状态
      catalogTree: [], // 栏目树数据
      //  showCheckBox:false
      defaultProps: {
        children: 'children',
        label: 'name'
      }, // 默认配置
      allCatalogChecked: false // 选中所有节点
    }
  },
  methods: {
    // 栏目树渲染函数
    renderContent: function (createElement, { node, data, store }) {
      let ele = null
      let ele2 = null
      if (node.data.catalogID !== 0 && node.childNodes.length) {
        ele2 =
            createElement('button',
              {
                attrs: {
                  class: 'el-button el-button--primary el-button--small',
                  type: 'button'
                },
                style: {'margin-left': '20px'}}, [
                createElement('span', '取消子节点')
              ])
      }
      ele = createElement('span', [
        createElement('i', { attrs: { class: data.icon } }),
        createElement('span', node.label)
      ])
      return createElement('span', [
        ele, ele2
      ])
    },

    // 节点点击事件
    handleNodeClick(val) {
      if (!val.children || !val.children.length) {
        return
      }
      // console.log(val);
      let ids = this.$refs.tree.getCheckedKeys()
      let hasContainID = false
      for (var i = 0; i < ids.length; i++) {
        if (ids[i] === val.id) {
          hasContainID = true
          break
        }
      }
      this.$refs.tree.setChecked(val.id, false, true)
      if (hasContainID) {
        this.$refs.tree.setChecked(val.id, true, false)
      }
    },

    // 选中值改变事件
    getCheckChange(data, checked, indeterminate) {
      this.$emit('getCheckedNodes', this.$refs.tree.getCheckedNodes())
    },

    // 加载栏目树
    async loadCatalogTree() {
      this.treeDlgLoading = true
      let param = {
        siteID: this.siteID,
        contentType: this.contentType,
        type: 'Default'
      }
      let res = await axios.get(`/ui/site/catalogTree`, param)
      this.catalogTree = res.data.status === 1 ? res.data.data : []
      this.treeDlgLoading = false
    }
  },
  created() {
    this.loadCatalogTree()
  },
  props: {
    // 是否显示checkBox
    'showCheckBox': {
      type: Boolean,
      default: true
      // required: true
    },

    // 栏目内容类型
    'contentType': {
      type: String
    },

    // 站点ID
    'siteID': {
      type: [String, Number],
      required: true
    }
  },
  watch: {
    'contentType': 'loadCatalogTree',
    'siteID': 'loadCatalogTree'
  }
}
</script>

<style scoped>

</style>
