<!--  -->
<template>
  <div style="height: 100%" class="flexStar">
    <div class="boxswai" style="width: 26%; padding-left: 0px">
      <div class="boxnei" style="display: flex; flex-direction: column">
        <div style="overflow: auto; flex: 1;height:500px">
          <el-tree 
          v-if="ishowTree"
          lazy :props="defaultProps" @node-click="getNodeDetail"  :load="loadNode" :expand-on-click-node="false"
                highlight-current
                node-key="id"
                ref="tree"
                :default-expanded-keys="defaultExpandedKeys"
                :data="treeData">
            <span
                  class="custom-tree-node"
                  :class="data.moreShow?'show':''"
                  slot-scope="{ node, data }"
                  @mouseleave="mouseout(data)"
                >
                  <div class="pd-r-20">
                    {{ node.label }}
                    <div class="normal-black">
                         <div >
                            <el-link :underline="false">
                              <i
                                class="el-icon-menu "
                                @click="showMenu($event,data, node)"
                              ></i>
                            </el-link>
                              <ul
                                v-show="menuvisible"
                                :style="{ left: menuleft + 'px', top: menutop + 'px' }"
                                class="contextmenu"
                              >
                                <li v-for="item in menusData" :key="item"  @click="menuClick($event,item,data,node)" > 
                                      <i :class="item.icon"></i>{{item.label}}
                                </li>
                               
                              </ul>
                        </div>
                    </div>
                  </div>
            </span>
          </el-tree>
        </div>
      </div>
    </div>
    <div
      class="boxswai"
      style="width: 74%; padding-left: 0px; padding-right: 0px"
    >
      <div class="boxnei">
        <h4 class="mg-b-10">节点信息</h4>
        <form class="form-horizontal">
            <table class="table-form" style="width: 100%;">
                <tbody>
                  <tr>
                    <td class="tit" width="10%">节点编码：</td>
                    <td id="code">{{ nodeDetail.nodeCode||'' }}</td>
                    <td class="tit" width="10%">节点名称：</td>
                    <td id="name">{{ nodeDetail.nodeName||'' }}</td>
                    <td class="tit" width="10%">节点类型：</td>
                    <td id="nodeType">{{nodeDetail.nodeTypeName||""}}</td>
                </tr>
                <tr>
                  <td class="tit" width="10%">工程类型：</td>
                  <td id="workType">{{ nodeDetail.engineeringTypeName||'' }}</td>
                  <td class="tit" width="10%" >备注</td>
                  <td id="nodeType" colspan="4">{{nodeDetail.remarks||""}}</td>
                </tr>
              </tbody>
          </table>
        </form>
        <h4 class="mg-b-10 mg-t-20">下级节点列表</h4>
        <div class="tableclass">
            <el-table
            :data="tableData"
            border
            height="650"
            style="width: 100%">
            <el-table-column
              prop="nodeCode"
              label="节点编号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="nodeName"
              label="节点名称"
           >
            </el-table-column>
            <el-table-column
            width="180"
              prop="nodeName"
              label="节点类型">
            </el-table-column>
            <el-table-column
            width="180"
              prop="engineeringTypeName"
              label="工程类型">
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 新增编辑节点 -->
    <el-dialog
      title="节点"
      :visible.sync="adddialogVisible"
      width="30%"
      append-to-body
      :before-close="handleAddClose">
      <el-form label-position="left" label-width="80px" :model="addForm" ref="ruleForm"  :rules="addFormrules">
          <el-form-item label="节点编码" prop="nodeCode">
            <el-input v-model="addForm.nodeCode"></el-input>
          </el-form-item>
          <el-form-item label="节点名称" prop="nodeName">
            <el-input v-model="addForm.nodeName"></el-input>
          </el-form-item>
          <el-form-item label="节点类型" prop="nodeType">
            <el-select v-model="addForm.nodeType" placeholder="请选择节点类型" style="width: 100%;">
              <el-option
                v-for="item in dataTypeList"
                :key="item.id"
                :label="item.dictValue"
                :value="item.dictKey"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工程类型"  prop="engineeringTypeName">
            <el-input v-model="addForm.engineeringTypeName" disabled></el-input>
          </el-form-item>
      
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="addForm.remarks"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddform" :loading="saveNodeLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 排序弹窗 -->
    <el-dialog
      title="节点排序"
      :visible.sync="sortTag"
      append-to-body
      width="30%"
      :before-close="handleSortClose">
      <ManualSorting
        v-if="sortTag2"
        @bianhua='bianhua()'
        :sort='sort'
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="sortTag = false,sortTag2=false">取 消</el-button>
        <el-button type="primary" @click="editSort()" >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script >
import ManualSorting from '@/components/WbsTree/ManualSorting'
import { getLazyTree,add,getDetail,getChildList,updateNode,removeNode,getSameList,sortNode,getEngineeringTypeName } from "@/api/measure/template.js";
import { getDictionary } from "@/api/system/dict";
import {isObjectEmpty} from "@/util/util";

 export default {
  components:{
    ManualSorting
  },
    data() {
      return {
        ishowTree:true,
        treeData: [{
          label: '系统计量单元',
          children: [
            {
              label: '总则',
              children: [{
                label: '保险费'
              }]
            },
            {
              label: '路基工程',
              children: [{
                label: '清理与掘除'
              }]
            },
            {
              label: '路面工程',
              children: [{
                label: '底基层'
              }]
            },
        ]
        }],
        defaultExpandedKeys:[],
        defaultProps: {
          children: 'children',
          label: 'nodeName',
          isLeaf: 'notExsitChild'
        
        },
        
      menuvisible:false,//右键菜单
      menuleft:20,
      menutop:0,
      menusData:[
        {icon: 'el-icon-plus', label: '新增节点', key: "add"},
        {icon: 'el-icon-s-promotion', label: '编辑节点', key: "edit"},
        {icon: 'el-icon-sort', label: '排序节点', key: "sort"},
        {icon: 'el-icon-delete', label: '删除节点', key: "del"},
      
      ],//树组件操作菜单
      menuKey:'',
      adddialogVisible:false,//新增节点
      addForm:{},
      nodeDetail:{},
      addFormrules:{
        nodeName: [
            { required: true, message: '请输入节点名称', trigger: 'blur' },
          ],
          engineeringType: [
            { required: true, message: '请输入工程类型', trigger: 'blur' }
          ]
      },
      sortTag2: false,
      sortTag: false,
      sort: [],
      tableData:[],
      id:'',//模板ID
      dataTypeList:[],//节点类型
      saveNodeLoading:false
      };
    },
    created () {
      this.init();
   
  },
  methods: {
    init(){
      const {id} = this.$route.query;
      this.id = id
      this.getNodeTypelist()
    },
    //获取节点类型
    getNodeTypelist () {
      if (this.dataTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: 'meter_node_type'
      }).then((res) => {
        res.data.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.dataTypeList = res.data.data;
      })
    },
    //获取节点类型对应的名称
    getNodeTypeName(type){
      this.dataTypeList.forEach((ele)=>{
        if(ele.dictKey==type){
          this.nodeDetail.nodeTypeName=ele.dictValue
        }
      })
    },
    loadNode (node, resolve) {
      let pid = 0;
      if (node.level != 0) {
        pid = node.data.id
      }
      getLazyTree({
        templateId:this.id,
        id:pid
      }).then((res) => {
        let arr = [];
        if (Array.isArray(res.data.data)) {
          arr = res.data.data;
        }
        return resolve(arr);
      })
    },
    async getLazytree () {//冲洗获取wbs树
      const { data: res } = await getLazyTree({id:0,templateId:this.id})
      //console.log(res);
      if (res.code == 200) {
        this.treeData = res.data
      }
    },
    handleNodeClick(data) {
        console.log(data);
        this.curTreeData=data
    },
          //树形控件菜单相关方法
    mouseout(){
        this.menuvisible=false
    },
    //展示菜单
  showMenu(e,data,node){
    e.preventDefault();
    console.log(e,'e');
    var x = e.pageX; //这个应该是相对于整个浏览器页面的x坐标，左上角为坐标原点（0,0）
    var y = e.pageY; //这个应该是相对于整个浏览器页面的y坐标，左上角为坐标原点（0,0）
    this.menutop = y;
    this.menuleft = x;
    this.menuvisible=true

    },
    getEngineeringTypeNameById(id){
      getEngineeringTypeName({id}).then((res)=>{
        console.log(res.data.data,'data');
        if(!isObjectEmpty(res.data.data)){
          console.log(111111);
          this.addForm.engineeringTypeName=res.data.data||''
        }else{
          this.addForm.engineeringTypeName=''
        }
        
      })
    },
    menuClick(e,item,data,node){
       this.menuKey=''
        e.preventDefault();
        if(item.key==='add'){
          console.log('新增');
          this.menuKey='add'
          this.adddialogVisible=true
          this.getEngineeringTypeNameById(data.id)
          this.addForm.engineeringTypeName=node.parent.data.engineeringTypeName
          this.addNodeHandle()
        }
        
        else if(item.key==='edit'){
          console.log('编辑',data,node);
          this.menuKey='edit'
          this.adddialogVisible=true
          this.editNodeHandle()
          
        }
         else if(item.key==='del'){
            this.menuKey='del'
            console.log('删除');
            this.deleNode(data,node)
        }
        else if(item.key==='sort'){
            this.menuKey='sort'
            console.log('排序');
            this.paixuMD(data,node)
        }
    },
    editNodeHandle(){
      if(!this.curTreeData.id || !this.curTreeNode.id){
        this.$message({
          type: "warning",
          message: "请先选择节点"
        })
        return;
      }
      this.addForm=this.curTreeData
    },
    addNodeHandle(){
      if(!this.curTreeData.id ){
        this.$message({
          type: "warning",
          message: "请先选择节点"
        })
        return;
      }
     
   
    },
    
    handleAddClose(){
      this.adddialogVisible=false
    },
    saveAddform(){
      //新增节点确定
      this.adddialogVisible=false
      if( this.menuKey==='add'){
        this.$refs.ruleForm.validate(async (valid) => {
          if(valid){
            this.saveNodeLoading=true
              this.addForm.parentId=this.curTreeData.id
              this.addForm.ancestor=this.curTreeData.ancestor
              this.addForm.templateId=this.curTreeData.templateId
              let subobj=this.addForm
              add(subobj).then(() => {
                this.saveNodeLoading=false
              this.updateTreeNewNode();
              this.dialogVisible = false;
              this.addForm={}
              this.$message({
                type: "success",
                message: "新增成功!"
              });
            })
          }
        })
     
      }
      if(this.menuKey==='edit'){
        let subobj=this.addForm
        updateNode(subobj).then(() => {
        this.saveNodeLoading=false
        this.updateTreeNewNode();
        this.dialogVisible = false;
        this.addForm={}
        this.$message({
          type: "success",
          message: "修改成功!"
        });
        getDetail(subobj.id).then((res) => {
          this.nodeDetail = Object.assign({}, res.data.data);
          this.getNodeTypeName(this.nodeDetail.nodeType)
        
        })
      })
      }
    },
    getNodeDetail (data, node) {
      let parentName = '';
      if (node.parent.data) {
        parentName = node.parent.data.title;
      }
      this.curTreeData = data;
      this.curTreeNode = node;
      this.curTreeData.parentName = parentName;
      getDetail(data.id).then((res) => {
        res.data.data.parentName = parentName;
        this.tableData = [res.data.data];
        this.nodeDetail = Object.assign({}, res.data.data);
        this.getNodeTypeName(this.nodeDetail.nodeType)
       
      })
      getChildList({id: this.curTreeData.id}).then((res)=>{
        this.tableData=res.data.data
      })
      // this.updateNodeTable();

      //获取节点展开路径
      // this.getExpandedKeys(node);
    },
    updateTreeNewNode () {
      let detail = (this.nodeDetail.parentId ? this.nodeDetail : this.curTreeData);
      getLazyTree({id:detail.id,templateId:this.id}).then((res) => {
        let node = this.$refs.tree.getNode(detail.parentId);
        // node.isLeaf = false;
        // node.isLeafByUser = false;
        //console.log(node)
        this.$refs.tree.updateKeyChildren(detail.id, res.data.data)
      })
    },
    //排序
    handleSortClose(){
      this.sortdialogVisible=false
    },
    bianhua () {
      this.sortTag2 = false
      this.$nextTick(() => {
        this.sortTag2 = true
      })
    },
    editSort () {//修改排序
      let sortArr = this.sort, newArr = []
      for (let i = 0; i < sortArr.length; i++) {
        newArr.push({
          id: sortArr[i].id,
          nodeName: sortArr[i].nodeName
        })
      }
      this.wbsTreeSort(newArr)
    },
    ids() {
        let ids = [];
        this.sort.forEach(ele => {
          ids.push(ele.id);

        });
        return ids.join(",");
      },
    async wbsTreeSort () {//表单排序
      const { data: res } = await sortNode({ids:this.ids()})
      //console.log(res);
      if (res.code == 200) {
        this.sortTag = false
        this.sortTag2 = false
        this.ishowTree=false
        setTimeout(() => {
          this.ishowTree=true
        }, 100);
   
      }
    },
    paixuMD (data) {
      this.sortTag = true
      this.sortTag2 = true
      
          
      this.findWbsTreeSameLevel(data.parentId)
    },
    async findWbsTreeSameLevel (parentId) {//查询当前节点的同级节点
      const { data: res } = await getSameList({ parentId })
      //console.log(res);
      if (res.code === 200) {
        this.sort = res.data
      }
    },
    deleNode(data, node) {
      this.$confirm(
        "此操作将删除节点【" + data.nodeName + "】, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          removeNode(data.id).then(() => {
            this.$refs.tree.remove(node);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {});
    },
    },
  }
</script>
<style lang='scss' scoped>
.custom-tree-node {
  .normal-black {
    display: none;
  }
  &:hover {
    .normal-black {
      display: inline-block;
    }
  }
  &.show .normal-black {
    display: inline-block;
  }
}
// 树形控件菜单样式
.contextmenu {
margin: 0;
background: #fff;
z-index: 1000;
position: fixed; //关键样式设置固定定位
list-style-type: none;
padding: 5px 0;
border-radius: 4px;
font-size: 12px;
font-weight: 400;
color: #333;
box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}
.contextmenu li {
margin: 0;
padding: 7px 16px;
cursor: pointer;
}
.contextmenu li:hover {
background: #eee;
}
.form-horizontal .table-form, .form-horizontal .table-form td {
    border: 1px solid #ddd;
    background-color: #fdfdfd;
    font-size: 14px;
    padding: 10px;
    color: #606266
}

</style>
