<template>
  <VueFlow ref="vueFlowRef" :nodes="nodes" :edges="edges"  :class="{ dark }"
    class="basic-flow" 
    :default-viewport="{ zoom: 1.5 }" :min-zoom="0.2" :max-zoom="2.5" @drop="onDrop1"
    @contextmenu.prevent="onContextMenu" @node-contextmenu="logEvent('contextmenu', $event)" 
    @dragover="onDragOver" @dragleave="onDragLeave" @edge-click="onEdgeClick" @node-double-click="onNodeDoubleClick"  @node-click="onNodeClick">

    <template  #node-default="props">
      <eltree :node="props" />
    </template>
 
    <Background pattern-color="#aaa" :gap="16" />

    <!-- <MiniMap /> @input="handleUpdate"-->
    <Panel :position="'right'" style="display: none;">
      <div class="field">
        <div>
        <label for="label">Label:</label>
        <input id="label"  v-model.lazy="labelname"  /></div>
        <button @click="handleUpdate"  class="lableaniu">确定</button>
      </div>
      <!-- <div> -->
        <!-- <button class="remove" @click="removeNode(event)">N</button>
        <button class="remove" @click="removeEdge(event)">E</button>
        <button class="remove" @click="removeall(event)">all</button>
     
      </div> -->
      <!-- <button @click="onSelection()"  class="lableaniu">获取</button> -->
    </Panel>
    <Controls position="top-left">
      <ControlButton title="Reset Transform" @click="resetTransform">
        <Icon name="reset" />
      </ControlButton>
      <ControlButton title="背景切换" @click="toggleDarkMode">
        <Icon v-if="dark" name="sun" />
        <Icon v-else name="moon" />
      </ControlButton>

      <ControlButton title="保存" @click="logToObject1">
        <!-- <Icon name="log" /> -->
        <el-icon :color="iconcolor"><UploadFilled /></el-icon>
      </ControlButton>
      <ControlButton title="删除节点" @click="removeNode()">
        <el-icon  :color="iconcolor"><DocumentDelete /></el-icon>
      </ControlButton>
      <ControlButton title="删除线" @click="removeEdge()">
        <el-icon  :color="iconcolor"><Crop /></el-icon>
      </ControlButton>
      <ControlButton title="清空全部" @click="removeall()">
        <el-icon :color="iconcolor"><DeleteFilled /></el-icon>
      </ControlButton>
      
    
    </Controls>

  </VueFlow>
  <div class="dnd-flow">

    <!-- <div id="contextMenu" @click="deleteItemConfirm">删除</div> -->


  </div>
</template>
<script setup>
import { ref, markRaw,inject } from 'vue'
import { VueFlow,Panel, useVueFlow, MarkerType} from '@vue-flow/core'
import { ElMessage, ElButton, ElDialog, ElSelect } from 'element-plus'
import {
  DocumentDelete,
  Delete,
  UploadFilled,
  Histogram,
  DeleteFilled,
  Crop,
} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router';
import { request, uploadFile } from "@/utils/request";
import { Background } from '@vue-flow/background'
import { ControlButton, Controls } from '@vue-flow/controls'
import { initialEdges, initialNodes } from './modeljs.js'
import { MiniMap } from '@vue-flow/minimap'
import "./main.css";//重置样式
import DropzoneBackground from './DropzoneBackground.vue'
import eltree from './eltree.vue'
import useDragAndDrop from './useDnD';
import f11 from '@/assets/img/f11.png'
import r2 from '@/assets/img/r2.png'
import html2canvas from 'html2canvas';
import Icon from './Icon.vue'
import { formatTime } from '@/js/lindex.js';
import emitter from "@/utils/emitter";
// import func from 'vue-temp/vue-editor-bridge.js';

const dark = ref(false)
let datatree=ref();
const route = useRoute();
const { onInit, onNodeDragStop, onNodeContextMenu, onConnect, addEdges, setViewport, toObject,addNode } = useVueFlow()
let vueFlowRef = ref();
let emit = defineEmits(['optimizerfalse']);
let mergedObj=ref();
let labelname=ref();
let iconcolor=ref('#000')
const props = defineProps({

  optimizer: {
    type: Boolean,
  },
  jboptimizer: {
    type: Boolean,
  },
  Xfiol: {
    type: Boolean,
  },
  // color1: {
  //   type: String,
  // },
})
let newobj=ref({
  name:'',
  description:'',
})
let nodesitem=ref([]);
let linenum=ref(1);
let bgcolor=ref();
let linecolor=ref('#b1b1b7')
let pid=ref('');
let newroter=ref();
let vueflowimg=ref('');
const shopShow = ref(false);
let noid = ref([]);
let Edgeid = ref();
let seledge=ref(null);
let djshow=ref(false);
let node = ref();
let contextMenu = ref({
  position: { x: 0, y: 0 },
  target: 'kong',
})
let Nested=ref([]);
let Nested2=ref([]);
let nnum=ref(0);
const { onDragOver, onDrop, onDragLeave, isDragOver } = useDragAndDrop();
const edges = ref([]);
const nodes = ref([]);
onConnect((connection) => {
  console.log(connection);
  connection.type = 'smoothstep';//  smoothstep straight
  connection.markerEnd = MarkerType.ArrowClosed;
  connection.color=linecolor.value;
  // connection.label = '这是一条注释';
  connection.style = { strokeWidth:linenum.value ,stroke:linecolor.value};
  addEdges(connection)
  seledge.value=null;
})
//修改名称
function handleUpdate(){

  noid.value.data.label=labelname.value;
  console.log( noid.value.data.label);
}
emitter.on('child2Data', data => {
  datatree.value = data;
  console.log(datatree.value);
})
onUnmounted(() => {
  emitter.off('child2Data');
});
function onNodeClick(e) {
  noid.value = e.node;
  labelname.value=e.node.data.label;
  console.log(e.node);
  djshow.value = !djshow.value;
  // if(djshow.value){
  //   console.log('选中');

  // }else{
  //   console.log('取消选中');
  // }

}
//模块化
const  bgcolorfunc= (color)=>{

  bgcolor.value=color;
if(noid.value.style!=undefined){
  console.log(noid.value.style);
  noid.value.style.backgroundColor=color;
}

}

function onSelection(){
  let positionX=[];
  let positiony=[];
  for(let i=0;i<Nested.value.length;i++){
   // Nested2.value.push(Nested.value[i]);
   positionX.push(Nested.value[i].position.x)
   positiony.push(Nested.value[i].position.y)
  }
  let xmin=Math.min(...positionX);
  let ymax=Math.max(...positiony);
  console.log(positionX);
  // console.log( positionX)
  // console.log(44444)
  // console.log( positiony)
  nnum.value++;
//  let x=Math.floor(Math.random() * 91) + 10;
//  let y=Math.floor(Math.random() * 91) + 10;
  let name='模块'+nnum.value
   let item= {
    id:nnum.value.toString(),
    data: { label:name },
    position:  { x:xmin , y:ymax},
    style: { backgroundColor: bgcolor.value, width: '200px',height: '200px' },
    //children: [],
  }
    
 if(Nested.value.length!=0){
  Nested2.value=[];
  for(let i=0;i<Nested.value.length;i++){
    Nested2.value.push(Nested.value[i]);
  }
  console.log(Nested2.value);
  nodesitem.value= Nested2.value.map(node => {

    if(node.parentNode==undefined){
     
      node.isParent=false;
      node.parentNode=item.id;
      console.log(  node.parentNode)
      node.position.x= node.position.x /2;
      node.position.y= node.position.y/2;
      node.expandParent=true;
       //positionxy=node.position;
      // node.extent='parent';
      // return node;
    }
      return node;
      })
    
    }
    nodes.value.push(item)

    for(let i=0;i<nodesitem.value.length;i++){
      console.log(nodesitem.value[i]);
      nodes.value.push(nodesitem.value[i])
    }
console.log(1111)

   console.log( nodes.value);
//console.log(nodesitem.value);
     //nodes.value.push( nodes.value)
//  let item= {
//     id:nnum.value.toString(),
//     data: { label: '模块化' },
//     position: positionxy,
//     style: { backgroundColor: bgcolor.value, width: '200px',height: '200px' },
//   }
//  console.log(Nested2.value)
//     nodes.value = Nested2.value.map(node => {
//       positionxy=node.position;
//       if(node.parentNode==undefined){
//         node.parentNode=item.id;
//       // node.expandParent=true;
//       node.extent='parent';
     
//   }
//   return node;
//   });
//   Nested2.value.push(item)
//   nodes.value.push(item);
//  console.log( nodes.value);
 
// }else{
// console.log(222)
//  }
 
}
function onNodeDoubleClick(e) {
  noid.value = e.node;
  console.log( e.node.data.name);
  console.log(111111)
  if (e.node.data.name == '优化器') {
    emit('optimizerfalse','优化器');
  }else if(e.node.data.name=="进化优化器"){
    emit('optimizerfalse','进化优化器');

  }else if(e.node.data.name=="代理优化器"){
    emit('optimizerfalse','代理优化器');

  }else if(e.node.data.name=="Rosenbrock"||e.node.data.name=="Xfiol"){
    emit('optimizerfalse','Xfiol');
  }else if(e.node.data.name=="梯度优化器"){
    emit('optimizerfalse','梯度优化器');
  }else if(e.node.data.name=="CST"){
    emit('optimizerfalse','CST');
  }else if(e.node.data.name=="ADflow"){
    emit('optimizerfalse','ADflow');
  }else if(e.node.data.name=="CST"){
    emit('optimizerfalse','CST');
  }else if(e.node.data.name=="FFD"){
    emit('optimizerfalse','FFD');
  }else if(e.node.data.name=="TACS"){
    emit('optimizerfalse','TACS');
  }else if(e.node.data.name=="参数化"){
    emit('optimizerfalse','参数化');
  }else if(e.node.data.name=="气动分析"){
    emit('optimizerfalse','气动分析');
  }else if(e.node.data.name=="Python"){
    emit('optimizerfalse','Python');
  }

}
// 监听线
function onEdgeClick(e) {
  Edgeid.value = e.edge.id;
  seledge.value= e.edge;
   //seledge.value.style.stroke = 'red';
}
function logEvent(name, event) {
  console.log(2222)
}
function onContextMenu(event) {

}
onInit((vueFlowInstance) => {
  vueFlowInstance.fitView()
})

onNodeDragStop(({ event, nodes, node }) => {
  console.log(nodes)
  Nested.value=nodes;
  //console.log('Node Drag Stop', { event, nodes, node })
})

onConnect((connection) => {
  addEdges(connection)
})
function updatePos() {

  nodes.value = nodes.value.map((node) => {
    return {
      ...node,
      position: {
        x: Math.random() * 400,
        y: Math.random() * 400,
      },
    }
  })
}

function removeEdge(id) {
  id = Edgeid.value;
  vueFlowRef.value.removeEdges(id);
  console.log('msg:',datatree.value);
}


// 触摸
const onDrop1=(event)=>{
  onDrop(event);
emitter.emit('doSomethingEvent');

}
function removeNode(id) {
  id = noid.value.id;
if(datatree.value==undefined){
  if(nodes.value.length>0){
    for (let i = 0; i <nodes.value.length; i++) {
        if(id==nodes.value[i].id){
          console.log(44444)
          console.log( nodes.value[i]);
          nodes.value.splice(i, 1)
        }
}
console.log( nodes.value);
  }
}else{
  if(nodes.value.length>0){
    for (let i = 0; i <nodes.value.length; i++) {
        if(id==nodes.value[i].id){
          console.log( nodes.value[i]);
         nodes.value.splice(i, 1)
        }
}
  }
  for (let i = 0; i <datatree.value[0].children.length; i++) {
    if(id.includes(datatree.value[0].children[i].Text)){
      for (let j = 0; j <datatree.value[0].children[i].children.length; j++) {
        if(id==datatree.value[0].children[i].children[j].id){
         //datatree.value[0].children.splice(datatree.value[0].children[i].children[j], 1); 
           datatree.value[0].children[i].children.splice(j, 1)
           vueFlowRef.value.removeNodes(id);
        }
    
  }
    }

}
}
}
function removeall(){
  nodes.value=[];
  edges.value=[];
  Nested2.value=[];
  Nested.value=[];

  for (let i = 0; i <datatree.value[0].children.length; i++) {
      for (let j = 0; j <datatree.value[0].children[i].children.length; j++) {
        datatree.value[0].children[i].children=[];
    }

}

}
async  function logToObject1() {
  let obj = { nodes: toObject().nodes,edges:toObject().edges };
  mergedObj.value=JSON.stringify(obj);
  try {
        const container = vueFlowRef.value.$el;
        const canvas = await html2canvas(container);
        const img = canvas.toDataURL('image/png');
 
        // 创建一个图片元素并设置src属性为转换后的图片数据
       vueflowimg.value=img
       if(vueflowimg.value!=''){
        console.log("进入了")
        addflow();
       }
        // 添加到DOM中或者做其他操作
      } catch (error) {
        console.error('转换出错:', error);
      }
}
//添加接口
const addflow = () => {
    const params = {
        transCode: 'MDO0002',
        pid: pid.value,
        name: newobj.value.name,
        remark:newobj.value.description,
        image:vueflowimg.value,
        isshare:'1',
        flow:mergedObj.value 
    }
    console.log(params);
    request(params)
        .then((res) => {
            console.log(res);
            ElMessage({
                  message: res.returnMsg,
                  type: 'success',
              })
        })
        .catch((err) => {
            ElMessage.error(err.returnMsg)
        })
}
/**
 * Resets the current viewport transformation (zoom & pan)
 */
function resetTransform() {
  setViewport({ x: 0, y: 0, zoom: 1 })
}

function toggleDarkMode() {
  dark.value = !dark.value;
  if(dark.value){
    iconcolor.value='#fff'
  }else{
    iconcolor.value='#000'
  }


}
onMounted(() => {
  setTimeout(function() {
    getroter();
}, 1500);
  // childfun();

});
// 获取链接
const getroter=()=>{
  //datatree.value[0].children=[];
  let objlist=JSON.parse(sessionStorage.getItem("objlist"));
  if(objlist.flow!=''){
    let nodesflow=JSON.parse(objlist.flow)
    nodes.value=nodesflow.nodes;
    edges.value=nodesflow.edges;
  }
  newobj.value.name=objlist.name;
  newobj.value.description=objlist.remark;
  pid.value=objlist.pid;

  // let item={
  //   id:'1-0',
  //   label: objlist.name,
  //   img:r2,
  // }
  // console.log(  datatree.value[0].children);
  // datatree.value[0].children.push(item);

}
//改变线的粗
const linestrokeWidth=(num)=>{
  if(seledge.value){
    seledge.value.style.strokeWidth = num;
  }
  linenum.value=num;
// console.log(seledge.value);
//   let edgearr= toObject().edges;
//   for (let i = 0; i <= edgearr.length-1; i++) {
//     edgearr[i].style.strokeWidth = num;
// }
console.log(num)
//addEdges(edgearr);

}
//改变线的颜色
const changeAllEdgesColor=(color1)=>{
  linecolor.value= color1;
  if(  seledge.value){
    console.log(11111)
    seledge.value.style.stroke =  linecolor.value;
  }

 
}

watch(() => seledge.value, (newItems, oldItems) => {
  // if(seledge.value!=null){
  //   //seledge.value.style.stroke =  linecolor.value;
  // }
    });
defineExpose({changeAllEdgesColor,linestrokeWidth,getroter,onSelection,bgcolorfunc});
</script>

<style>
/* .vue-flow__edge.selected .vue-flow__edge-path, .vue-flow__edge:focus .vue-flow__edge-path, .vue-flow__edge:focus-visible .vue-flow__edge-path {
    stroke: #555 !important;
} */
.vue-flow__edge:focus .vue-flow__edge-path, .vue-flow__edge:focus-visible .vue-flow__edge-path {
    stroke: #555 !important;
} 
.vue-flow__edge {
  text-align: left;
  /* 设置edges的左对齐 */
}

#contextMenu {
  display: none;
  position: absolute;
  background-color: #fff;
  border-radius: 5px;
  padding: 10px;
  text-align: center;
  color: black;
  font-size: 14px;
  font-weight: 400;
  cursor: pointer;
  z-index: 99999;
}
.vue-flow__node-default.selectable:hover,
.vue-flow__node-input.selectable:hover,
.vue-flow__node-output.selectable:hover {
  box-shadow: none;
}

panel {
  cursor: pointer;
  position: absolute;
  z-index: 100000;
}

.remove {
  background: #fff;
  color: #666;
  margin: 0 10px;
  font-size: 12px;
}
.vue-flow__node-default, .vue-flow__node-input, .vue-flow__node-output{
  /* width: auto !important; */
  border: none;
  background-color: rgba(0,0,0,0);
}
.node-content {
  cursor: move;  /* 更改鼠标光标表示可拖动 */
}
.vue-flow__node {
  cursor: move;
}

/* 禁用文本选中效果 */
.left_main * {
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+/Edge */
  user-select: none; /* Standard syntax */
}
.lableaniu{

  font-size: 12px;
    background-color: #ddd;
    padding: 4px 16px;
    /* margin-top: -17px; */
    margin-left: 5px;
    margin-top: 0px;
    border-radius: 1px;
}
.vue-flow__controls-button svg{
  max-width: 16px;
  max-height: 16px;
}
.field{
  display: flex;
}
.node-label, .edge-label,.custom-node span {
    text-transform: none; /* 确保文本不转换为大写 */
    font-family: 'Inter-Regular';
}
</style>
