<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" @edge-double-click="onEdgeDoubleClick">

    <template  #node-default="props">
      <eltree :node="props" />
    </template>

    <template #edge-default="props">
      <custom-edge :sourceX="props.sourceX" 
                  :sourceY="props.sourceY" 
                  :targetX="props.targetX" 
                  :targetY="props.targetY"
                  :label="props.data.label" />
    </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="重置" @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>

    <el-dialog v-model="changeNameshow" align-center :modal="false" :close-on-click-modal="false"
            :append-to-body="true" draggable :fullscreen="false" :modal-append-to-body="false" modal-class="summary-dlg"
             width="400" class="dialog_class bgcolor colortext tianjia sel">
      <template #header="{ titleId, titleClass }">
        <div class="my-header ">
          <h4 :id="titleId" :class="titleClass">修改名称</h4>
        </div>
      </template>
      <div style="margin-top: 20px;padding: 20px;">
        <el-form :model="changeName" label-width="100px" class="demo-ruleForm">
        <el-form-item label="新名称：" prop="name">
          <el-input v-model="changeName.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changeNameshow = false">取 消</el-button>
          <el-button type="primary" @click="handleUpdate">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 双击线段 -->
    <el-dialog v-model="dataflowshow" align-center :modal="false" :close-on-click-modal="false"
            :append-to-body="true" draggable :fullscreen="false" :modal-append-to-body="false" modal-class="summary-dlg"
             width="500" class="dialog_style bgcolor colortext tianjia sel">
      <template #header="{ titleId, titleClass }">
        <div class="my-header ">
          <h4 :id="titleId" :class="titleClass">数据流</h4>
        </div>
      </template>
      <div style="margin-top: 5px;padding: 10px 35px;">
        <el-card>
          <el-checkbox v-model="checkAll" 
          :indeterminate="isIndeterminate"
          @change="handlecheckAllchange">全选</el-checkbox>
          <div class="eldesign classtable">
            <el-table :data="shujuliutable" border>
            <el-table-column
              type="index"
              label=""
              :header-cell-style="{ display: 'none' }"
            ></el-table-column>
            <el-table-column prop="flag" width="55">
              <template #default="{ row }">
                <el-checkbox
                :false-label="0"
                :true-label="1" 
                v-model="row.flag" 
                @change="handlecheckFlagchange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="data" label="" ></el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dataflowshow = false">取 消</el-button>
          <el-button type="primary" @click="confirmselection();dataflowshow = false ">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </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 CustomEdge from './CustomEdge.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,
  },
  Xfoil: {
    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([]);

const changeNameshow = ref(false);
const changeName = ref({
  name: '',
  
})

onNodeContextMenu((e) => {
  noid.value = e.node;
  changeName.value.name = e.node.data.label;
  changeNameshow.value = true;
})

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;
})
//修改名称
const handleUpdate = () => {
  if (noid.value && noid.value.data) {
    noid.value.data.label = changeName.value.name; // 更新名称
    console.log(noid.value.data.label); // 打印更新后的值
  } else {
    console.error("noid.value 或 noid.value.data 未定义"); // 错误日志
  }
  changeNameshow.value = false; // 更新后关闭对话框
  // noid.value.data.label = labelname;
};
emitter.on('child2Data', data => {
  datatree.value = data;
  console.log(datatree.value);
})
onUnmounted(() => {
  emitter.off('child2Data');
});
function onNodeClick(e) {
  noid.value = e.node;
  changeName.value.name=e.node.data.label;
  console.log("shuju:",e.node.data);
  console.log("noid.value:",noid.value);
  console.log("changeName.value:",changeName.value.name);
  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( nodes.value); 
}


function onNodeDoubleClick(e) {
  noid.value = e.node;
  console.log( e.node.data.name);
  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=="Xfoil"){
    emit('optimizerfalse','Xfoil');
  }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(onPythonlist.value.some(item => e.node.data.name.includes(item))){
    emit('optimizerfalse','Python');
  }else if(e.node.data.name=="CATIA"){
    emit('optimizerfalse','CATIA');
  }else if(e.node.data.name=="FSI"){
    emit('optimizerfalse','FUM to FEM');
  }else if(e.node.data.name=="Flight"){
    emit('optimizerfalse','Flight');
  }

}

let onPythonlist=ref(['Python','Branin','Rosenbrock','Rastrigin','G9','Forrester']);


let previousEdge = null;  // 用于保存上一个选中的边缘
// 监听线
function onEdgeClick(e) {
  // 如果已经有选中的边缘
  if (seledge.value) {
    // 恢复上一个选中边缘的样式
    if (previousEdge) {
      previousEdge.style = {
        ...previousEdge.style,
        stroke: previousEdge.originalColor,  // 恢复原始颜色
        strokeWidth: 1,                      // 恢复原始宽度
      };
    }
  }

  // 保存当前点击的边缘为选中边缘
  Edgeid.value = e.edge.id;
  seledge.value = e.edge;

  // 暂时更改当前选中边缘的样式
  seledge.value.originalColor = seledge.value.style.stroke;  // 保存当前边缘的原始颜色
  seledge.value.style = {
    ...seledge.value.style,
    stroke: '#2267B1',       // 设置选中边缘的颜色
    strokeWidth: 2,          // 设置选中边缘的宽度
  };

  // 保存当前选中的边缘作为上一个选中边缘
  previousEdge = seledge.value;
}


let dataflowshow=ref(false);

let shujuliutable = ref([
  {data: '升力系数Cl',flag:1},
  {data: '阻力系数Cd',flag:1},
  {data: '压阻力系数Cdp',flag:1},
  {data: '上表面转换点位置xtr-upper',flag:1},
  {data: '下表面转换点位置xtr-lower',flag:1},
])


let checkAll = ref(false);
let isIndeterminate = ref(false);
const handlecheckAllchange = (val) => {
  shujuliutable.value.forEach((item) => {
    item.flag = val;
  });
  isIndeterminate.value = false;
};

const handlecheckFlagchange = () => {
  let checkedCount = shujuliutable.value.filter((item) => item.flag).length;
  checkAll.value = checkedCount === shujuliutable.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < shujuliutable.value.length;
};


const confirmselection=()=>{
  let checkedData = shujuliutable.value.filter((item) => item.flag).map((item) => item.data);
  console.log('xuanzhongshuju:',checkedData);
  console.log('seledge:',seledge.value);
  seledge.value.label=checkedData.join('\n');
  dataflowshow.value = false;
}


function onEdgeDoubleClick(e) {
  handlecheckFlagchange();
  console.log('Edge Double Click', e)
  seledge.value = e.edge;
  dataflowshow.value = true
}


function logEvent(name, event) {
  console.log(2222)
}

// 右键更改名字
// const onContextMenu = (e) => {
//       e.preventDefault();  // 阻止浏览器默认的右键菜单

//       const node = e.target.closest(".vue-flow__node");
//       console.log("nodes:",nodes);
//       console.log("node:",node);
//       if (node) {
//         // 获取当前右键点击的节点
//         const nodeId = node.getAttribute("data-id");
//         const clickedNode = nodes.value.find((n) => n.id === nodeId);
//         console.log("clickedNode:",clickedNode);
        
//         if (clickedNode) {
//           noid.value = clickedNode;
//           changeName.value.name = clickedNode.label;  // 将当前节点的label放入弹窗中
//           changeNameshow.value = true;  // 显示弹窗
//         }
//       }
// };
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, { scale: 3 });
        const img = canvas.toDataURL('image/jpeg', 1.0);
 
        // 创建一个图片元素并设置src属性为转换后的图片数据
       vueflowimg.value=img
       if(vueflowimg.value!=''){
        console.log("进入了")
        addflow();
       }
        // 添加到DOM中或者做其他操作
      } catch (error) {
        console.error('转换出错:', error);
      }
}
//添加接口
const addflow = () => {
    const savedObj = JSON.parse(sessionStorage.getItem("objlist"));
    const stypeValue = savedObj ? savedObj.stype : '';
    console.log(stypeValue);
    const params = {
        transCode: 'MDO0002',
        pid: pid.value,
        name: newobj.value.name,
        remark:newobj.value.description,
        image:vueflowimg.value,
        isshare:'1',
        flow:mergedObj.value ,
        stype:stypeValue,
    }
    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) => {
  console.log('yanse:', color1);
  linecolor.value = color1;

  // 找到当前选中的边缘
  if (seledge.value) {
    // 更新该边缘的颜色，不修改宽度
    const updatedEdge = { 
      ...seledge.value, 
      style: { 
        ...seledge.value.style, 
        stroke: linecolor.value, // 只修改颜色
        strokeWidth: 1, // 保持选中样式的宽度（如果想要恢复原始宽度，设置为 1）
      }
    };

    // 更新 edges 数组
    const updatedEdges = edges.value.map(edge => 
      edge.id === seledge.value.id ? updatedEdge : edge
    );

    edges.value = updatedEdges; // 持久化修改后的边缘
  }
};

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的左对齐 */
}

.edge-label {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px;
  border-radius: 4px;
  font-size: 14px;
  white-space: pre-line;  /* 保证文本支持换行 */
}

.edge-label-line {
  margin-bottom: 4px; /* 控制每行的间距 */
}

#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>
