<template>
    <el-tree 
        ref="treeRef" 
        class="file-tree" 
        :data="orgData" 
        :props="defaultProps" 
        @node-click="handleNodeClick" 
        node-key="id"
        :highlight-current="true"
        :filter-node-method="filterNode" 
        :default-expand-all="true">
         <template #default="{ node, data }">
           <div class="custom_tree_node">
             <span
               class="label-text "
               :class="{'is_active': selectData && selectData.id === data.id}"
               :title="data.name"
               >{{ data.name }}
             </span>
             <span v-if="data.data_type === 2" class="tree-action-box first_node" @click.stop="showAction($event, data,node)">
               <bg-icon
                 class="tree-more"
                 icon="#bg-ic-s-more"
               ></bg-icon>
             </span>
             <span v-else class="tree-action-box" :class="{'position_sticky': isSticky(data.name) }" @click.stop="showAction($event, data,node)">
               <bg-icon
                 class="tree-more"
                 icon="#bg-ic-s-more"
               ></bg-icon>
             </span>
           </div>
         </template>
    </el-tree>
    <Teleport to="body">
       <div
         class="tree-action"
         v-show="actionFlag"
         :style="{ top: acTop, left: acLeft }"
       >
         <div v-if="selectData && selectData.data_type === 2" class="action" @click="treeAction({type: 'directory',action: 'create',target: null})">新建目录</div>
         <div v-if="selectData && selectData.data_type === 2" class="action" @click="treeAction({type: 'org',action: 'create',target: null})" >新建组织</div>

         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'create',target: 'local'})">新建本级目录</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'create',target: 'child'})">新建下级目录</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'org',action: 'create',target: 'local'})">新建本级组织</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'org',action: 'create',target: 'child'})">新建下级组织</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'edit',target: 'local'})">编辑目录</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'delete',target: 'local'})">删除</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'mvup',target: 'local'})">上移</div>
         <div v-if="selectData && selectData.data_type === 0" class="action" @click="treeAction({type: 'directory',action: 'mvdown',target: 'local'})">下移</div>

         <div v-if="selectData && selectData.data_type === 1" class="action" @click="treeAction({type: 'org',action: 'create',target: 'local'})">新建本级组织</div>
         <div v-if="selectData && selectData.data_type === 1" class="action" @click="treeAction({type: 'org',action: 'edit',target: 'local'})">编辑组织</div>
         <div v-if="selectData && selectData.data_type === 1" class="action" @click="treeAction({type: 'org',action: 'delete',target: 'local'})">删除</div>
         <div v-if="selectData && selectData.data_type === 1" class="action" @click="treeAction({type: 'org',action: 'mvup',target: 'local'})">上移</div>
         <div v-if="selectData && selectData.data_type === 1" class="action" @click="treeAction({type: 'org',action: 'mvdown',target: 'local'})">下移</div>
       </div>
    </Teleport>
</template>

<script setup>
import { reactive, toRefs, ref } from '@vue/reactivity'
import { getCurrentInstance, watch, nextTick} from 'vue'
import { computed, onBeforeMount, onBeforeUnmount } from '@vue/runtime-core'
import { useRouter } from 'vue-router';
  const { proxy } = getCurrentInstance()
  const { $axios,$message } = proxy

  const acTop = ref(0);
  const acLeft = ref(0);
  const actionFlag = ref(false)
  const selectData = ref(null)
  const selectDataParent = ref(null) 
  const mvDataParent = ref(null)
  const treeRef = ref(null)

  const orgData = ref([])
  const defaultProps = {
    label: 'name',
    children: 'Child',
    value: 'organization_id'
  }

  const  getOrgTree = () => {
    $axios.get(`/apaas/system/v5/org/tree`)
      .then((res) => {
      if (res.data.code == 200) {
          orgData.value = res.data.data || [];
          nextTick(() =>{
            treeRef.value.setCurrentNode(orgData.value[0],true)
            emit('select',ref(orgData.value[0]));
          })
          
      }else {
          $message.error(res.data.msg)
      }
      })
  }


  const filterTree =(val) => {
    treeRef.value.filter(val)
  }

  const filterNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
  }

  const showAction = (e, data,node) => {
    const rect = e.target.getBoundingClientRect(); //获取点击的dom的位置
    acTop.value = rect.y - 17 + "px";
    acLeft.value = rect.x + 35 + "px";
    actionFlag.value = true;
    selectData.value = data;
    selectDataParent.value = node.parent.data.name ? node.parent.data : null;
    mvDataParent.value = node.parent.data.Child ? node.parent.data.Child : node.parent.data;
  };

  const isSticky = (data) => {

    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    context.font = '14px MicrosoftYaHei';
    const { width } = context.measureText(data);
    return width > 255 ? true : false;
  }

  const closeAction = ()=>{
    actionFlag.value = false;
  }
  

  const emit = defineEmits(['action'])
  const handleNodeClick = (node,nodeAttr,treeNode,event) => {
    selectData.value = node;
    emit('select',selectData);
    //只读则无操作事件
      closeAction();
  }

  const treeAction = (params) => {
    emit('select',selectData);
    let data = null;
    if(params.action === 'create') {
      if(params.target === 'local') {
        data = selectDataParent;
      }else if(params.target === 'child') {
        data = selectData;
      }else {
        
      }
    }else if(params.action === 'mvup') {
      if(mvDataParent.value.indexOf(selectData.value) === 0) {
        $message.error('已经是第一个元素，不可上移')
        return 0;
      }else {
        let brother = mvDataParent.value[mvDataParent.value.indexOf(selectData.value) - 1];
        data = [{id: selectData.value.id,sort: brother.sort},{id: brother.id,sort: selectData.value.sort}]
      }
      
    }else if(params.action === 'mvdown') {
      if(mvDataParent.value.indexOf(selectData.value) === (mvDataParent.value.length-1)) {
        $message.error('已经是最后一个元素，不可下移')
        return 0;
      }else {
        let brother = mvDataParent.value[mvDataParent.value.indexOf(selectData.value) + 1];
        data = [{id: selectData.value.id,sort: brother.sort},{id: brother.id,sort: selectData.value.sort}]
      }
    }else {
      data = selectData;
    }
    emit('action',{type: params.type,action: params.action,
                   data: data});
  }
  
  onBeforeMount(()=>{
    //只读则无操作事件
      window.addEventListener("click", closeAction);
      window.addEventListener("scroll", closeAction,true);
      getOrgTree()
  })
  
  onBeforeUnmount(()=>{
    //只读则无操作事件
      window.removeEventListener('click', closeAction);
      window.removeEventListener('scroll', closeAction);
      
  })

  defineExpose({getOrgTree, filterTree })

</script>

<style scoped>
.tree-action-box {
    display: none;  
    position: absolute;
    right: -5px;
    top: 0px;
    width: 44px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    background-color: #f2f3f7;
    box-shadow: -3px 0px 8px -3px 
		rgba(0, 7, 101, 0.15);
}
.position_sticky {
  position: sticky;
  position: -webkit-sticky;
}
.tree-more {
  font-size: 12px;
  color: #3759be;
}

.file-tree :deep() .el-tree-node__content:hover .tree-action-box {
  display: inline-block;
}
.file-tree :deep() .el-tree-node__content .first_node {
  display: inline-block;
}
.file-tree :deep() .el-tree-node > .el-tree-node__children {
  overflow: visible;
}
.file-tree :deep() .el-tree-node__content {
  position: relative;
}
.action-box:hover .tree-action {
  display: block;
}
.label-text {
  font-size: 14px;
	color: #404a62;
}
.tree-action-box:hover + .label-text {
  padding: 8px 0;
  background-color: var(--el-tree-node-hover-bg-color);
}

.label-text:hover {
  padding: 8px 0;
  background-color: var(--el-tree-node-hover-bg-color);
}
.is_active {
  padding: 8px 0;
  background-color: var(--el-color-primary-light-9);
}

.custom_tree_node {
  width: 100%;
  font-size: 14px;
  color: #202531;
  padding-right: 16px;
}
.text_clip {
      width: 100%;
    display: inline-block;
}

.tree-action .action {
  width: 100%;
  height: 34px;
  line-height: 34px;
  padding-left: 16px;
  font-size: 14px;
  color: #202531;
  cursor: pointer;
}
.tree-action :deep().el-upload {
  width: 100%;
}
.tree-action .action:hover {
  background-color: #eff2fa;
  color: #3759be;
}

.tree-action .disable{
  cursor: not-allowed;
  color: #616f94;
}
.tree-action .disable:hover{
  background-color: #fff;
  color: #616f94;
}

.tree-action {
  /* display: none; */
  width: 144px;
  background-color: #ffffff;
  box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
  padding: 4px 0;
  border-radius: 4px;
  position: fixed;
  z-index: 9;
}

.file-tree :deep().el-tree-node__content{
  height: 36px!important;
}

</style>