<template>
  <VueFlow ref="vueFlowRef" v-model:nodes="nodes" v-model:edges="edges"  :class="{ dark }"
    class="basic-flow" 
    style="background-image: url('src/assets/flowimg/surromdao.png'); background-position: center; background-repeat: no-repeat;"
    :default-viewport="{ zoom: 1.5 }" :min-zoom="0.2" :max-zoom="2.5" @drop="onDrop1"
    @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>
 
    <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="confirmDelete()">
        <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;">
        <div v-if="datacontent === '1'">
          <el-card :shadow="none" style="min-height: 240px; max-height: 480px;">
          <el-checkbox v-model="checkAll" 
          :indeterminate="isIndeterminate"
          @change="handlecheckAllchange">全选</el-checkbox>
          <div class="eldesign classtable">
            <el-table :data="youhuaFFDtable" border :show-header="false">
            <el-table-column
              type="index"
              label=""
            ></el-table-column>
            <el-table-column prop="steamflag" width="55">
              <template #default="{ row }">
                <el-checkbox
                :false-label="0"
                :true-label="1" 
                v-model="row.steamflag" 
                @change="handlecheckFlagchange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" ></el-table-column>
            </el-table>
          </div>
          </el-card>
        </div>
        <div v-if="datacontent === '2'">
          <el-card :shadow="none" style="min-height: 240px; max-height: 480px;">
          <el-checkbox v-model="checkAll" 
          :indeterminate="isIndeterminate"
          @change="handlecheckAllchange">全选</el-checkbox>
          <div class="eldesign classtable">
            <el-table :data="youhuaCSTtable" border :show-header="false">
            <el-table-column
              type="index"
              label=""
            ></el-table-column>
            <el-table-column prop="steamflag" width="55">
              <template #default="{ row }">
                <el-checkbox
                :false-label="0"
                :true-label="1" 
                v-model="row.steamflag" 
                @change="handlecheckFlagchange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" ></el-table-column>
            </el-table>
          </div>
          </el-card>
        </div>
        <div v-if="datacontent === '3'">
          <el-card :shadow="none" style="min-height: 240px; max-height: 480px;">
          <el-checkbox v-model="checkAll" 
          :indeterminate="isIndeterminate"
          @change="handlecheckAllchange">全选</el-checkbox>
          <div class="eldesign classtable">
            <el-table :data="ADflowyouhuatable" border :show-header="false">
            <el-table-column
              type="index"
              label=""
            ></el-table-column>
            <el-table-column prop="steamflag" width="55">
              <template #default="{ row }">
                <el-checkbox
                :false-label="0"
                :true-label="1" 
                v-model="row.steamflag" 
                @change="handlecheckFlagchange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" ></el-table-column>
            <el-table-column prop="steamtype">
              <template #default="{ row }">
                <el-select v-model="row.steamtype">
                  <el-option 
                  v-for="item in steamtypeoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            </el-table>
          </div>
          </el-card>
        </div>
        <div v-if="datacontent === '4'">
          <el-card :shadow="none" style="min-height: 240px; max-height: 480px;">
          <el-checkbox v-model="checkAll" 
          :indeterminate="isIndeterminate"
          @change="handlecheckAllchange">全选</el-checkbox>
          <div class="eldesign classtable">
            <el-table :data="Xfoilyouhuatable" border :show-header="false">
            <el-table-column
              type="index"
              label=""
            ></el-table-column>
            <el-table-column prop="steamflag" width="55">
              <template #default="{ row }">
                <el-checkbox
                :false-label="0"
                :true-label="1" 
                v-model="row.steamflag" 
                @change="handlecheckFlagchange"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" show-overflow-tooltip></el-table-column>
            <el-table-column prop="steamtype">
              <template #default="{ row }">
                <el-select v-model="row.steamtype">
                  <el-option 
                  v-for="item in steamtypeoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            </el-table>
          </div>
          </el-card>
        </div>
        
      </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, ElMessageBox} 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,addNodes,updateEdgeData } = 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;
})

// 线的类型 process-逻辑线 data-数据线
let lineType = ref('process');
// 线序号
let linecount = ref(0);

onConnect((connection) => {
  console.log('线连接',connection);
  // 创建唯一的边ID（由源节点和目标节点组成）
  const edgeId = `${connection.source}-${connection.target}`;
  connection.id = edgeId;  // 自定义 ID
  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;
  
  linecount.value++;
  const newName = `Seg${linecount.value}`;

  const sourceNode = vueFlowRef.value.getNode(connection.source);
  const targetNode = vueFlowRef.value.getNode(connection.target);

  // 调用 saveflow 保存数据并获取 wid
  saveflow(pid.value, '', newName, lineType.value, sourceNode.data.uid, targetNode.data.uid)
    .then((wid) => {
      // 更新连接线的数据
      const updatedData = {
        wid: wid,
        uid: newName,
        type: lineType.value,
        fromuid: sourceNode.data.uid,
        touid: targetNode.data.uid,
      };
      updateEdgeData(connection.id, updatedData);

    })
    .catch((error) => {
      console.error('保存流程失败:', error);
    });
})
//修改名称
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的值：",datatree.value);
})

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;
  const nowid = e.node.data.wid;
  console.log( e.node.data.name);
  if (e.node.data.name == 'optimizer') {
    emit('optimizerfalse',{name:'优化器',wid:nowid});
  }else if(e.node.data.name=="optimizer1"){
    emit('optimizerfalse',{name:'进化优化器',wid:nowid});

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

  }else if(e.node.data.name=="Xfoil"){
    emit('optimizerfalse',{name:'Xfoil',wid:nowid});
  }else if(e.node.data.name=="optimizer2"){
    emit('optimizerfalse',{name:'梯度优化器',wid:nowid});
  }else if(e.node.data.name=="CST"){
    emit('optimizerfalse',{name:'CST',wid:nowid});
  }else if(e.node.data.name=="ADflow"|| e.node.data.name=="RAE2822"){
    emit('optimizerfalse',{name:'ADflow',wid:nowid});
  }else if(e.node.data.name=="FFD"){
    emit('optimizerfalse',{name:'FFD',wid:nowid});
  }else if(e.node.data.name=="TACS"){
    emit('optimizerfalse',{name:'TACS',wid:nowid});
  }else if(e.node.data.name=="参数化"){
    emit('optimizerfalse',{name:'参数化',wid:nowid});
  }else if(e.node.data.name=="气动分析"){
    emit('optimizerfalse',{name:'气动分析',wid:nowid});
  }else if(onPythonlist.value.some(item => e.node.data.name.includes(item))){
    emit('optimizerfalse',{name:e.node.data.name,wid:nowid});
  }else if(e.node.data.name=="CATIA"){
    emit('optimizerfalse',{name:'CATIA',wid:nowid});
  }else if(e.node.data.name=="FSI"){
    emit('optimizerfalse',{name:'FSI',wid:nowid});
  }else if(e.node.data.name=="Flight"){
    emit('optimizerfalse',{name:'Flight',wid:nowid});
  }

}

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


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

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

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

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

}


let dataflowshow=ref(false);

let youhuaFFDtable = ref([
  { name:'FFD参数(sample)', steamflag:1 }
])

let youhuaCSTtable = ref([
  { name:"上表面CST参数(upper)", steamflag:1 },
  { name:'下表面CST参数(lower)', steamflag:1 }
])

let steamtypeoptions = ref([
  { label:'约束条件', value:1 },
  { label:'优化目标', value:2 }
])

let ADflowyouhuatable = ref([
  { code: "cl", name:'升力系数Cl', comtype:2 , steamflag:1, steamtype:1 },
  { code: "cd", name:'阻力系数Cd', comtype:2 , steamflag:1, steamtype:1 },
  { code: "cm", name:'力矩系数Cm', comtype:2 , steamflag:1, steamtype:1 },
  
])

let Xfoilyouhuatable = ref([
  // { code:'', name:'升力系数Cl', comtype:2 , steamflag:1, steamtype:1 },
  // { code:'', name:'阻力系数Cd', comtype:2 , steamflag:1, steamtype:1 },
  // { code:'', name:'压阻力系数Cdp', comtype:2 , steamflag:1, steamtype:1 },
  // { code:'', name:'力矩系数Cm', comtype:2 , steamflag:1, steamtype:1 },
  // { code:'', name:'上表面转换点位置xtr-upper', comtype:2 , steamflag:1, steamtype:1 },
  // { code:'', name:'下表面转换点位置xtr-lower', comtype:2 , steamflag:1, steamtype:1 },
])

let checkAll = ref(false);
let isIndeterminate = ref(false);
const dataTables = {
  '1': youhuaFFDtable,
  '2': youhuaCSTtable,
  '3': ADflowyouhuatable,
  '4': Xfoilyouhuatable
};

const handlecheckFlagchange = () => {
  const table = dataTables[datacontent.value];
  if (!table) return;

  let checkedCount = table.value.filter(item => Boolean(item.steamflag)).length;
  checkAll.value = checkedCount === table.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < table.value.length;
};

const handlecheckAllchange = (val) => {
  const table = dataTables[datacontent.value];
  if (!table) return;

  table.value.forEach(item => item.steamflag = val ? 1 : 0);
  isIndeterminate.value = false;
};


const confirmselection=()=>{
  const table = dataTables[datacontent.value];
  let checkedData = table.value.filter((item) => item.steamflag).map((item) => item.name);
  console.log('xuanzhongshuju:',checkedData);
  console.log('seledge:',seledge.value);
  seledge.value.label=checkedData.join('\n');
  if(datacontent.value === '4') {
    dataFlowsave();
  }else if(datacontent.value === '3') {
    dataFlowsave2();
  }
  
  dataflowshow.value = false;
}



const xfid = ref('')
const adid = ref('')
// 监听组件xfoil返回的xfid
const handleXfid = (xfidFromB) => {
  xfid.value = xfidFromB.value;
};

const handleAdid = (adidFromB) => {
  adid.value = adidFromB.value;
}


let datacontent = ref('')
function onEdgeDoubleClick(e) {
  
  console.log('Edge Double Click', e)
  seledge.value = e.edge;
  // dataflowshow.value = true
  console.log('qidian:',e.edge.sourceNode.data.name);
  console.log('zhongdian:',e.edge.targetNode.data.name);
  let qidian = e.edge.sourceNode.data.name;
  let zhongdian = e.edge.targetNode.data.name;
  let youhualist = ['optimizer','optimizer3','optimizer1','optimizer2'];
  if( youhualist.includes(qidian) && zhongdian ==='FFD' ){
    datacontent.value = '1';
    dataflowshow.value = true;
  }else if( youhualist.includes(qidian) && zhongdian ==='CST') {
    datacontent.value = '2';
    dataflowshow.value = true;
  }else if( qidian === 'ADflow' && youhualist.includes(zhongdian) ) {
    datacontent.value = '3';
    emitter.emit('requestGetadid',pid.value);
    console.log('adid:',adid.value)
    if(adid.value) {
      querydataFlow(adid);
      dataflowshow.value = true;
    }else{
      ElMessage.error('ADflow未初始化！')
    }
  }else if ( qidian === 'Xfoil' && youhualist.includes(zhongdian) ) {
    datacontent.value = '4';
    emitter.emit('requestGetxfid',pid.value);
    console.log('xfid:',xfid.value)
    if(xfid.value) {
      querydataFlow(xfid);
      dataflowshow.value = true;
    }else{
      ElMessage.error('Xfoil未初始化！')
    }
  }
  console.log('leixing:',datacontent.value);

  nextTick(() => {
    handlecheckFlagchange();
  });
}

const querydataFlow = (comid) => {
  const params = {
    transCode: "MDO0052",
    pid: pid.value,
    comid: comid.value
  }
  request(params).then((res) => {
    if(datacontent.value === '3'){
      ADflowyouhuatable.value = res.params;
      handlecheckFlagchange();
    }
    if(datacontent.value === '4'){
      Xfoilyouhuatable.value = res.params;
      handlecheckFlagchange();
    }
    
  })
  .catch((err) => {
      ElMessage.error(err.returnMsg)
  })
}

const dataFlowsave = () => {
  const params = {
    transCode: "MDO0053",
    paramstr: convertToStringArray([],Xfoilyouhuatable.value),
  };
  request(params).then((res) => {
    ElMessage({
        message: res.returnMsg,
        type: 'success',
      })
  })
  .catch((err) => {
      ElMessage.error(err.returnMsg)
  })
}

const dataFlowsave2 = () => {
  console.log('ADflowyouhuatable:',ADflowyouhuatable.value);
  const params = {
    transCode: "MDO0053",
    paramstr: convertToStringArray([],ADflowyouhuatable.value),
  };
  request(params).then((res) => {
    ElMessage({
        message: res.returnMsg,
        type: 'success',
      })
  })
  .catch((err) => {
      ElMessage.error(err.returnMsg)
  })
}

const convertToStringArray = (result, Data) => {
  console.log('Data:', Data);

  // 安全检查 Data，确保它是一个数组
  if (!Array.isArray(Data)) {
    console.error('Data should be an array');
    return result; // 返回原 result 或者根据需要返回其他默认值
  }

  result = Data.map(row => {
    // 获取每一行的 `code`, `name`, `value` 和 `flag`
    const paramid = row.paramid ?? ' ';
    const steamflag = row.steamflag ?? '';
    const steamtype = row.steamtype ?? ' ';

    // 将字段连接为一个以逗号分隔的字符串
    return `${paramid},${steamflag},${steamtype}`;
  }).join(';');  // 每行之间用分号分隔

  return result;
}


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)
//   console.log('Connection', 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;
  const wid = seledge.value.data.wid;
  vueFlowRef.value.removeEdges(id);
  deleteflow(wid);
  seledge.value=null;
  console.log('msg:',datatree.value);
}


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

}


function removeNode(id) {
  id = noid.value.id;
  const wid = noid.value.data.wid;
  console.log('removeNodewid:',wid);
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)
          deleteflow(wid);
        }
}
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);
           deleteflow(wid);
           vueFlowRef.value.removeNodes(id);
           removeRelatedEdges(id);
        }
    
  }
    }

}
}
}

function removeRelatedEdges(nodeId) { 
  //过滤出与该节点相关的连线
  const relatedEdges = edges.value.filter(
    (edge) => edge.source === nodeId || edge.target === nodeId
  );
  
  // 遍历删除关联的连线
  relatedEdges.forEach((edge) => {
    if (edge.data && edge.data.wid) {
      deleteflow(edge.data.wid);
    }
  });
}

// 删除提示
const confirmDelete = () => {
  ElMessageBox.confirm(
    '确定要删除全部吗？删除后不可恢复！',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      removeall();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

function removeall() {
  try {
    const allnodes = nodes.value;
    const allEdges = edges.value;
    for (let i = 0; i < allnodes.length; i++) {
      if (allnodes[i].data.wid) {
        deleteflow(allnodes[i].data.wid);
      }
    }
    for (let i = 0; i < allEdges.length; i++) {
      if (allEdges[i].data.wid) {
        deleteflow(allEdges[i].data.wid);
      }
    }

    nodes.value = []
    edges.value = []
    Nested2.value = []
    Nested.value = []

    // 判断 datatree 是否为空或未定义
    if (!datatree.value || datatree.value.length === 0 || !datatree.value[0]?.children) {
      console.warn('datatree 数据为空或未定义')
      ElMessage({
        type: 'warning',
        message: '没有数据可以删除'
      })
      return
    }

    // 清空 datatree 的 children
    for (let i = 0; i < datatree.value[0].children.length; i++) {
      if (datatree.value[0]?.children[i]?.children) {
        datatree.value[0].children[i].children = []
      }
    }

    
  } catch (error) {
    console.error('删除失败：', error)
    ElMessage({
      type: 'error',
      message: '删除过程中出错'
    })
  }
}

// 流查询
const queryflow = () => {
  const params = {
    transCode: 'MDO0057',
    pid: pid.value,
  }
  request(params)
  .then((res) => {
    console.log(res);
    
  })
  .catch((err) => {
    ElMessage.error(err.returnMsg)
  })
}

// 保存流
const saveflow = async (pid,wid, uid, type, fromuid, touid) => {
  const params = {
    transCode: 'MDO0058',
    pid: pid || '',
    wid: wid || '', // 流ID
    uid: uid || '',
    type: type || '',
    fromuid: fromuid || '',
    touid: touid || '',
  };

  try {
    // 直接使用 await 等待 request 返回
    const res = await request(params);
    return res.wid; // 返回 wid
  } catch (err) {
    // 处理错误
    ElMessage.error(err.returnMsg || '保存流程失败');
  }
};

// async function saveFlowExample() {
//   try {
//     const wid = await saveflow('flow123', 'user001', 'process', 'fromA', 'toB');
//     console.log('返回的 wid:', wid);
//   } catch (err) {
//     console.error('保存流程失败:', err.message);
//   }
// }
// saveFlowExample();

// 删除流
const deleteflow = (nowid) => {
  const params = {
    transCode: 'MDO0059',
    wid: nowid,
  }
  request(params)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    ElMessage.error('删除流程失败')
  })
}


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 savedObj = JSON.parse(sessionStorage.getItem("objlist"));
    const stypeValue = savedObj ? savedObj.stype : '';

    // 用于首页主界面切换数据一致
    const updateobjlist = {
      pid: pid.value,
      name: newobj.value.name,
      remark: newobj.value.description,
      image: vueflowimg.value,
      isshare: '1',
      flow: mergedObj.value,
      stype: stypeValue,
    }
    sessionStorage.setItem("objlist",JSON.stringify(updateobjlist));
    
    console.log("打印stypeValue:",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: '工程保存成功',
                  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();

  if (vueFlowRef.value) {
    vueFlowRef.value.$el.addEventListener('click', (event) => {
      // 确保点击的不是边缘
      if (seledge.value && !event.target.closest('.vue-flow__edge')) {
        // 恢复选中边缘的原始样式
        seledge.value.style = {
          ...seledge.value.style,
          stroke: seledge.value.originalColor,
          strokeWidth: previousEdge?.originalWidth || 1, // 恢复原始宽度
        };

        // 清空选中的边缘
        seledge.value = null;
        Edgeid.value = null;
        previousEdge = null;
      }
    });
  }

  emitter.on("xfidFromxfoil", handleXfid);
  emitter.on("adidFromadflow", handleAdid);
});


onUnmounted(() => {
  emitter.off('child2Data');

  emitter.off("xfidFromxfoil", handleXfid);
  emitter.off("adidFromadflow", handleAdid);
});


// 获取链接
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,logToObject1});
</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的左对齐 */
}

.vue-flow__edge-text {
  transform:  translateY(-10px); /* 将 label 向上偏移 */
  background: transparent !important;
  font-size: 8px;
  font-family: 'Microsoft YaHei';
  color: #333333;
}

.vue-flow__edge-textbg {
  fill: transparent !important; /* 将背景设置为透明 */
}

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

</style>
