<template>
  <div id="dragBox" ref="dragBoxRef" class="u-tree-drag">
    <!-- 左侧树 -->
    <div id="leftTree" class="left-tree">
      <!-- 标题 -->
      <div class="top-title u-flex-jab">
        <div class="title">{{ treeTitle }}</div>
        <div class="refresh" @click="handleRefresh"></div>
      </div>
      <div class="interlock-tree-container">
        <!-- 搜索+新增 -->
        <div class="tree-search">
          <a-button v-if="hasHandleBtn && isSysManage" type="primary" icon="plus" @click="handleAdd"/>
          <!-- <a-button v-if="hasHandleBtn" type="primary" icon="plus" @click="handleAdd" v-has="'add:tree'"/> -->
          <a-input-search allow-clear placeholder="请输入" @change="onChange" :class="hasHandleBtn?'has-btn':'noHas-btn'"/>
        </div>
        <!-- 树列表 -->
        <div class="interlock-tree-content">
          <a-tree
            v-if="tpmTreeData.length > 0"
            :tree-data="tpmTreeData"
            :replace-fields="replaceFields"
            autoExpandParent
            :expandedKeys="expandedKeys"
            :selectedKeys="selectedKeys"
            @expand="onExpand"
            @select="selectNode"
            blockNode
            >
            <template v-slot:title="nodeData">
              <div class="item-node-container">
                <div>
                  <a-icon slot="icon" :type="nodeData.interlockType==='0'?'cluster':'project'" />
                  <!-- carry-out  apartment cluster -->
                  <span class="item-node-name">{{nodeData.interlockName}}</span>
                </div>
                <template v-if="hasHandleBtn">
                <!-- <div v-if="hasHandleBtn" v-has="'edit:tree'"> -->
                  <!-- 系统管理员：全部权限 -->
                  <template v-if="isSysManage">
                    <a-dropdown>
                      <a-icon type="more" />
                      <a-menu slot="overlay">
                        <a-menu-item>
                          <a @click="handleEdit(nodeData)">修改</a>
                        </a-menu-item>
                        <a-menu-item>
                          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(nodeData.id)">
                            <a>删除</a>
                          </a-popconfirm>
                        </a-menu-item>
                      </a-menu>
                    </a-dropdown>
                  </template>
                  <template v-if="!isSysManage">
                    <!-- 非系统管理员：装置--不能增删改（装置不能操作）；系统--不能新增删除，只能修改有权限的系统名称和对应配置 -->
                    <a-dropdown v-if="nodeData.interlockType === '1' && nodeData.limitType === '0'">
                      <a-icon type="more" />
                      <a-menu slot="overlay">
                        <a-menu-item>
                          <a @click="handleEdit(nodeData)">修改</a>
                        </a-menu-item>
                        <!-- <a-menu-item v-if="isSysManage">
                          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(nodeData.id)">
                            <a>删除</a>
                          </a-popconfirm>
                        </a-menu-item> -->
                      </a-menu>
                    </a-dropdown>
                  </template>
                </template>
              </div>
            </template>
            <!-- :filter-tree-node="filterTreeNode" -->
          </a-tree>
        </div>
      </div>
    </div>
    <!-- 拖拽盒子 -->
    <div class="resize" id="resize" title="收缩侧边栏">
      <span class="resize-btn"></span>
      <!-- <span class="resize-btn">⋮</span> -->
    </div>
    <!-- 右侧slot -->
    <div id="rightSlot" class="right-content">
      <slot></slot>
    </div>
    <!-- 新增修改弹框 -->
    <base-InterLock-modal ref="modalForm" @ok="modalFormOk"></base-InterLock-modal>
  </div>
</template>

<script>
  import { getAction,deleteAction } from '@api/manage'
  import BaseInterLockModal from '@/views/module_interLock/baseInterLock/modules/BaseInterLockModal.vue'
  import cookie from 'js-cookie'
  export default({
    name: 'UEquipmentTree',
    components: {
      BaseInterLockModal
    },
    props: {
      treeTitle: {
        type: String,
        default: '列表'
      },
      // treeData: {
      //   type: Array,
      //   default: function(){
      //       return [] // 使用工厂函数返回默认值
      //   }
      // },
      hasHandleBtn: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        searchValue: '',
        // autoExpandParent: true,
        tpmListData: [], // 原始数据
        tpmTreeData: [], // 树形列表使用数据
        replaceFields: {
          key: 'id',
          children: 'children',
          title: 'interlockName',
        },
        expandedKeys: ['1808684817591234562'],
        selectedKeys: [], // 设置再次点击不仍然高亮
        url: {
          // list: '/base/interlockBase/list', // 修改权限前接口
          list: '/base/interlockBase/listByUser',
          // delete: "/base/interlockBase/delete",
          delete: "/iotedgeCollectData/iotedgeCollectData/deleteGroup",
        },
      }
    },
    computed: {
      treeSelectKeys() {
        return this.$store.getters.treeSelectKeys
      },
      treeExpandedKeys() {
        return this.$store.getters.treeExpandedKeys
      },
      isSysManage(){
        return cookie.get('SSORole') === 'globalAdmin'
      },
    },
    created() {
      this.getTpmTreeData()
    },
    mounted() {
      this.dragControllerDiv()
    },
    methods: {
      getTpmTreeData(){
        // 现版本
        // getAction(`/base/interlockBase/lever12`).then(res=>{
        // 原版本
        getAction(this.url.list).then(res=>{
          // if (res.success) {
            // 防止res.result对tpmListData造成地址赋值的问题
            this.tpmListData = JSON.parse(JSON.stringify(res))
            // 现版本
            // this.tpmTreeData = this.tpmListData
            // 原版本
            this.tpmTreeData = this.handleTree(res, "id", "pid")
            // console.log(this.tpmTreeData)
          // } else {

          // }
        })
        this.selectedKeys = this.treeSelectKeys
        this.expandedKeys = this.treeExpandedKeys
      },
      filterTreeNode(node) {
        // console.log(node)
        // if (!inputValue) return true;
        return node.title.indexOf('设备') !== -1;
      },
      onExpand(expandedKeys) {
        console.log(expandedKeys)
        this.expandedKeys = expandedKeys;
        // this.autoExpandParent = false;
        this.$store.commit('SET_TREEEXPANDEKEYS', expandedKeys);
      },
      onChange(e) {
        const value = e.target.value;
        // 筛选后数据
        var filterData = []
        // 筛选符合条件的数据：包含当前搜索的项
        console.log('原数据',this.tpmListData)
        filterData = this.tpmListData.filter(item => (item.interlockName.indexOf(value) !== -1))
        // var data = []
        // filterData.forEach(item => {
        //   var arr = this.tpmListData.filter(data => item.pid === data.id)
        //   console.log('父级', arr)
        //   // filterData = [...filterData, ...arr]
        // })
        // 循环寻找父级
        // console.log(this.findParents(this.tpmTreeData, '287813167808513'))

        // 原版本
        this.tpmTreeData = this.handleTree(filterData, "id", "pid")
        // 现版本
        // this.tpmTreeData = filterData
        // const expandedKeys = dataList.map(item => {
        //   if (item.name.indexOf(value) > -1) {
        //       // return getParentKey(item.key, gData);
        //       return this.filterNode(item.key, gData);
        //   }
        //   return null;
        // }).filter((item, i, self) => item && self.indexOf(item) === i);
        // Object.assign(this, {
        //   expandedKeys,
        //   searchValue: value,
        //   autoExpandParent: true,
        // });
      },
      // 树节点选择操作
      selectNode(selectedKeys, e){
        if (!e.selected){
          // 再次点击节点时，仍然高亮
          return
        }
        this.selectedKeys = selectedKeys
        let selectNode = e.selectedNodes[0].data.props
        var selectData = {
          id: selectNode.id,
          pid: selectNode.pid,
          interlockType: selectNode.interlockType,
          limitType: selectNode.limitType,
        }
        this.$store.commit('SET_CLICKSYSTEMNODE', selectData);
        this.$store.commit('SET_TREESELECTKEYS', selectedKeys);
        this.$emit('select')
      },
      // 树重置/刷新操作
      handleRefresh(){
        this.selectedKeys = []
        this.$store.commit('SET_CLICKSYSTEMNODE', {});
        this.$emit('select')
      },
      // findParents(treeData,id){
      //   let allparents = []
      //   if(treeData.length==0){
      //     return
      //   }

      //   let findele = (data,id) => {
      //     if(!id) return
      //     data.forEach((item,index) => {
      //       if(item.id == id){
      //         allparents.unshift(item.id)
      //         findele(treeData,item.parentid)

      //       }else{
      //         if(!!item.children){
      //             findele(item.children,id)
      //         }

      //       }
      //     })
      //   }

      //   findele(treeData,id)
      //   return allparents

      // },
      handleAdd: function () {
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.disableEdit = false;
      },
      handleEdit: function (record) {
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.disableEdit = true;
      },
      handleDelete: function (id) {
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            that.getTpmTreeData();
            that.$message.success(res.message);
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.getTpmTreeData();
      },
      // 拖拽事件
      dragControllerDiv(){
        let resize = document.getElementById("resize");
        let leftTree = document.getElementById("leftTree");
        let rightSlot = document.getElementById("rightSlot");
        let dragBox = document.getElementById("dragBox");

        // 鼠标按下事件
        resize.onmousedown = function (e) {
          // 记录坐标起始位置
          let startX = e.clientX;

          // 左边元素起始宽度
          resize.left = leftTree.offsetWidth;
          // console.log("宽度：", resize.left);
          // 鼠标拖动事件
          document.onmousemove = function (e) {
            // 鼠标拖动的终止位置
            let endX = e.clientX;

            // （endx-startx）= 移动的距离
            //  resize.left + 移动的距离 = 左边区域最后的宽度
            let moveLen = resize.left + (endX - startX);
            // console.log(moveLen);

            // 左右两边区域的总宽度 = 大容器宽度 - 中间区域拖拉框的宽度
            let maxWidth = dragBox.clientWidth - resize.offsetWidth;

            // 限制左边区域的最小宽度为220px
            if (moveLen < 220) moveLen = 220;

            // 右边区域最小宽度为 150px 限制左边区域到150后不能再拉宽
            if (moveLen > maxWidth - 420) moveLen = maxWidth - 420;

            // 设置左边区域的宽度，通过换算为百分比的形式，实现窗体放大缩小自适应
            // console.log((moveLen / maxWidth) * 100);
            // leftTree.style.width =(moveLen / maxWidth * 100) + '%';
            leftTree.style.width = moveLen + "px";

            // 右边区域即是总大小 - 左边宽度 - 拖动条宽度
            // console.log(((maxWidth - moveLen) / maxWidth) * 100);
            rightSlot.style.width = maxWidth - moveLen + "px";
            // console.log(moveLen);
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
            // console.log(11);
            document.onmousemove = null;
            document.onmouseup = null;
            resize.releaseCapture && resize.releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize.setCapture && resize.setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
        };
      },
    },
  })
</script>

<style lang="less">
.u-tree-drag{
  height: 100%;
  width: 100%;
  display: flex;
  overflow: hidden;
  /** 样式设置开始 */
  // 左侧树
  .left-tree{
    height: 100%;
    width: 300px;
    overflow: hidden;
  }
  /*拖拽区div样式*/
  .resize {
    width: 1px;
    height: 100%;
    background-color: #c8c8c8;
    position: relative;
    .resize-btn{
      width: 16px;
      height: 32px;
      cursor: col-resize;
      z-index: 99;
      position: absolute;
      top: 8px;
      left: -8px;
      background: url('../../../assets/drag.svg') no-repeat;
      background-size: 16px 32px;
      // width: 11px;
      // height: 50px;
      // font-size: 32px;
      // text-align: center;
      // color: #d6d6d6;
      // border-radius: 10px;
      // background-color: #ffffff;
      // background-size: cover;
      // background-position: center;
    }
  }
  /*拖拽区鼠标悬停样式*/
  .resize:hover {
    color: #444444;
  }
  /* 右侧 */
  .right-content{
    width: calc(100% - 301px);
    height: 100%;
    overflow: hidden;
  }
  /** 样式设置结束 */

  .top-title{
    height: 48px;
    line-height: 24px;
    padding: 12px 24px;
    border-bottom: 1px solid #e1e1e1;
    .title{
      color: #323233;
      font-size: 16px;
      font-weight: 700;
    }
    .refresh{
      width: 24px;
      height: 24px;
      background: url('../../../assets/refresh.svg') no-repeat;
      background-size: 24px 24px;
      cursor: pointer;
    }
    .refresh:hover{
      background: url('../../../assets/refresh-hover.svg') no-repeat;
      background-size: 24px 24px;
    }
  }
  /** 树区域设置 */
  .interlock-tree-container{
    width: 100%;
    height: calc(100% - 48px);
    background-color: transparent;
    overflow: auto;
    // border: 1px solid #CADAE6;
    // box-shadow: 0px 5px 10px 0 #CADAE6;
    .tree-search{
      padding: 8px 15px;
      .ant-btn{
        width: 32px;
        height: 32px;
        margin-right: 8px;
      }
      .has-btn{
        width: calc(100% - 40px);
      }
      .noHas-btn{
        width: 100%;
      }
    }
    .interlock-tree-content{
      width: 100%;
      // height: calc(100% - 40px);
      overflow: auto;
      padding: 0 15px 10px;
      .ant-tree{
        li{
          padding: 0;
          span.ant-tree-switcher{
            height: 40px;
            line-height: 40px;
          }
          .ant-tree-node-content-wrapper{
            height: 40px;
          }
          .ant-tree-node-content-wrapper:hover{
            background: linear-gradient(315deg,rgba(11,76,217,.05) 0%,rgba(11,76,217,.05) 0%,rgba(0,140,214,.05) 100%),#ffffff;
          }
        }
        .ant-tree-title{
          .item-node-container{
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 16px;
            color: #323233;
            height: 40px;
          }
          .item-node-name{
            padding-left: 8px;
          }
        }
        // 节点折叠时
        .ant-tree-treenode-switcher-close{
          
        }
        // 节点打开时
        .ant-tree-treenode-switcher-open{
  
        }
        // 节点行被选择时
        .ant-tree-treenode-selected{
          // 节点文字
          .ant-tree-node-selected{
            background: linear-gradient(to right,#a1c4fd8a 0%,#c2e9fb8a 100%)!important;
            // background: linear-gradient(to right,#a1c4fd 0%,#c2e9fb 100%)!important;
            // background: transparent;
            .item-node-container{
              // color: #008cd6;
              // font-weight: 700;
            }
          }
        }
      }
    }
  }
}
</style>
