<template>
  <div class="tree-panel">
    <el-tree
      ref="cusTreeRef"
      :data="arealist"
      node-key="sa_saleareaid"
      default-expand-all
      highlight-current
      :show-checkbox="checked"
      :check-strictly="true"
      :check-on-click-node="true"
      :expand-on-click-node="false"
      :default-checked-keys="area_default"
      @node-click="handleClick">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <slot name="operation" :data="data"></slot>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>

import {mapGetters} from 'vuex'

export default {
  props:['checked','area_default'],
  components:{
  },
  computed:{
    ...mapGetters({
      pageOnlyRead:"pageOnlyRead"
    })
  },
  data () {
    return {
      arealist:[],
      cusChecked: [],
      responseData:[]
    }
  },
  methods:{
    handleClick (row,node,VueComponent) {
      this.$emit('onClick',node.data)
    },
    async query_arealist () {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_area",
        "content": {
        }
      })
      // 数据格式转换成elementui-tree所需的格式
      this.responseData = res.data
      this.arealist = this.createMenu(res.data)
      this.$emit('onClick',this.arealist[0])
    },
    createMenu (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        // 新节点
        var elNode = {
          label: node["areaname"],
          remarks:node["remarks"],
          isused:node["isused"],
          sa_saleareaid:node['sa_saleareaid'],
          parentid:node['parentid'],
          disabled:that.pageOnlyRead,
          children: []
        }
          
        if (node.subarea && node.subarea.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subarea.length; index++) {
          // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
          elNode.children.push(convertToElementTree(node.subarea[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },
    handleCheck (currentNode, treeStatus) {
      /**
       * @des 根据父元素的勾选或取消勾选，将所有子级处理为选择或非选中状态
       * @param { node: Object }  当前节点
       * @param { status: Boolean } （true ： 处理为勾选状态 ； false： 处理非选中）
       */
      const setChildStatus = (node, status) => {
          /* 这里的 id children 也可以是其它字段，根据实际的业务更改 */
          this.$refs.cusTreeRef.setChecked(node.sa_saleareaid, status)
          if (node.children) {
              /* 循环递归处理子节点 */
              for (let i = 0; i < node.children.length; i++) {
                  setChildStatus(node.children[i], status)
              }
          }
      }
      /* 设置父节点为选中状态 */
      const setParentStatus = (nodeObj) => {
          /* 拿到tree组件中的node,使用该方法的原因是第一次传入的 node 没有 parent */
          const node = this.$refs.cusTreeRef.getNode(nodeObj)
          if (node.parent.key) {
              this.$refs.cusTreeRef.setChecked(node.parent, true)
              setParentStatus(node.parent)
          }
      }

      /* 判断当前点击是选中还是取消选中操作 */
      if (treeStatus.checkedKeys.includes(currentNode.sa_saleareaid)) {
          setParentStatus(currentNode)
          setChildStatus(currentNode, true)
      } else {
          /* 取消选中 */
          if (currentNode.children) {
              setChildStatus(currentNode, false)
          }
      }

      this.cusChecked = [...this.$refs.cusTreeRef.getCheckedKeys()]
      this.$emit('onAreaChecked',this.cusChecked)
    }
  },
  mounted () {
    this.query_arealist()
  },
  watch:{
    pageOnlyRead (val) {
      console.log(val)
      this.query_arealist()
    },
    area_default (val) {
      // 如果存在默认组织数据就执行
      this.$emit('onAreaChecked',this.area_default)
    }
  }
}

</script>
<style>
.tree-panel .el-tree {
  background: none;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  background: none;
}
</style>
<style scoped>
.tree-panel{
  padding: 16px;
  font-size: 14px;
  /* width:300px; */
  background: #FAFAFA;
}
</style>