<template>
  <div v-loading="treeDlgLoading">
    <el-checkbox-group v-model="checkedIDs">
      <el-tree
        :data="catalogTree"
        :render-content="renderContent"
        :props="defaultProps"
        node-key="ID"
        :expand-on-click-node="false"
        :default-expand-all="true"
        :highlight-current="true"
        :check-strictly="checkStrictly"
        class="padding-top-bottom mini"
        ref="tree">
      </el-tree>
    </el-checkbox-group>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  data() {
    return {
      treeDlgLoading: false,
      catalogTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      clientHeight: document.documentElement.clientHeight - 350,
      checkedIDs: []// 选中ID
    }
  },
  methods: {
    getCheckedNodes(ids) {
      let nodes = []
      ids.forEach(el => {
        let node = util.findTreeNode(
          this.catalogTree,
          'ID',
          el,
          'children'
        )
        if (node) {
          nodes.push(node)
        }
      })
      return nodes
    },
    // 树节点点击事件
    handleNodeClick(event, val) {
      event.stopPropagation()
      if (!val.children || !val.children.length) {
        if (this.isNeedNode) {
          this.$emit('callback', this.checkedIDs, this.getCheckedNodes(this.checkedIDs))
        } else {
          this.$emit('callback', this.checkedIDs)
        }
        return
      }
      let keys = []
      const childrenNodeKeys = (node) => {
        if (!node.children || node.children.length === 0) {
          return
        }
        node.children.forEach((childrenNode) => {
          keys.push(childrenNode.ID)

          if (childrenNode.children && childrenNode.children.length) {
            childrenNodeKeys(childrenNode)
          }
        })
      }
      childrenNodeKeys(val)
      this.checkedIDs = this.checkedIDs.filter(id => {
        return ![...keys].includes(id)
      })
      if (this.isNeedNode) {
        this.$emit('callback', this.checkedIDs, this.getCheckedNodes(this.checkedIDs))
      } else {
        this.$emit('callback', this.checkedIDs)
      }
    },
    handleNodeCheckClick(val, data) {
      if (!data.children || data.children.length === 0) {
        if (this.isNeedNode) {
          this.$emit('callback', this.checkedIDs, this.getCheckedNodes(this.checkedIDs))
        } else {
          this.$emit('callback', this.checkedIDs)
        }
        return
      }
      const childrenNodeKeys = (tmp) => {
        if (!tmp.children || tmp.children.length === 0) {
          return
        }
        tmp.children.forEach((childrenNode) => {
          keys.push(childrenNode.ID)
          if (childrenNode.children && childrenNode.children.length) {
            childrenNodeKeys(childrenNode)
          }
        })
      }
      let keys = []
      childrenNodeKeys(data)
      if (val) { // 选中
        keys.forEach(id => {
          if (!this.checkedIDs.includes(id)) {
            this.checkedIDs.push(id)
          }
        })
      } else { // 未选中
        this.checkedIDs = this.checkedIDs.filter(id => {
          return ![...keys].includes(id)
        })
      }
      if (this.isNeedNode) {
        this.$emit('callback', this.checkedIDs, this.getCheckedNodes(this.checkedIDs))
      } else {
        this.$emit('callback', this.checkedIDs)
      }
    },
    renderContent: function(createElement, { node, data, store }) {
      if (parseInt(data.ID) === 0 || parseInt(data.branchInnerCode) === 0 || data.ID === 'site') {
        return createElement('span', [
          createElement(
            'el-checkbox',
            {
              props: {label: data.ID},
              'on': {
                change: (val) => this.handleNodeCheckClick(val, data)
              }
            }, [
              createElement(
                'i',
                { attrs: { class: 'fa fa-desktop' } }
              ),
              createElement('span', node.label)
            ]
          )
        ])
      } else {
        const buttonText = '取消子节点'
        let ele = null
        if (parseInt(node.data.ID) !== 0 && node.childNodes.length) {
          ele = createElement(
            'button',
            {
              attrs: {
                'class': 'el-button el-button--primary el-button--mini',
                'type': 'button'
              },
              'style': { 'margin-left': '20px' },
              'on': {
                click: (event) => this.handleNodeClick(event, data)
              }
            },
            [createElement('span', buttonText)]
          )
        }
        return createElement('span', [
          createElement(
            'el-checkbox',
            {
              props: {label: data.ID},
              'on': {
                change: (val) => this.handleNodeCheckClick(val, data)
              }
            }, [
              createElement(
                'i',
                { attrs: { class: 'fa fa-folder' } }
              ),
              createElement('span', node.label)
            ]
          ),
          ele
        ])
      }
    },
    // 初始化批量添加内容弹出框左侧树结构
    async loadCatalogTree() {
      this.treeDlgLoading = true
      let params = {
        contentType: this.contentType,
        siteID: this.siteID,
        type: this.type,
        dimensionID: localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_ewdid']
      }
      let res = await axios.get(`/ui/catalog/bindcopycontenttree`, { params })
      this.treeDlgLoading = false
      this.catalogTree = res.data.data || []
    }
  },
  watch: {
    contentType() {
      this.loadCatalogTree()
    },
    siteID: 'loadCatalogTree',
    defaultChecked(val) {
      this.checkedIDs = val
    },
    show(val) {
      if (!this.defaultChecked || !this.defaultChecked.length) {
        this.checkedIDs = []
      }
    }
  },
  created() {
    this.loadCatalogTree()
  },
  props: {
    defaultChecked: Array,
    contentType: String,
    checkStrictly: { type: Boolean, default: false },
    siteID: [String, Number],
    isNeedNode: {type: [Boolean, Object]},
    show: [Boolean, Object],
    type: String
  }
}
</script>

<style scoped>

</style>
