<template>
  <div>
    <!-- <el-button type="primary" @click="saveFlow">测试</el-button> -->
    <div style="display: flex;margin-left: 1%;padding-top: 0.5%;position: absolute;z-index: 1000;justify-content: space-between;width: 98%;align-items: center;"> 
      <el-icon size="large" style="cursor: pointer" @click="back"><Back /></el-icon>
      <el-button @click="delWholeFlow" style="margin-left: auto;" type="danger" size="mini">删除</el-button>
      <el-button style="margin-left: 1%;" type="info" size="mini" plain @click="toImage">导出为图片</el-button>
      <el-button style="margin-left: 1%;" type="primary" size="mini" @click="saveFlow">保存</el-button>
      <el-button style="margin-left: 1%;" type="primary" size="mini" @click="showData">ceshi</el-button>
    </div>
    <div v-if="nodeDeSer" style="height: 85vh;width: 20vw;position: absolute;float: right;z-index: 1000;right: 1%;top: 1%;border: 0.1px solid #dedfe0;border-radius: 6px;background-color: white;">
      <div style="display: flex;margin-left: 3%;margin-top: 3%;align-items: center;justify-content: space-between;width: 95%;">
        <el-tag class="ml-2" style="" type="warning">服务</el-tag>
        <div style="margin-left: 4%;">
          {{servieName}}
        </div>
        <el-icon @click="nodeDeSer = false" style="margin-left: auto;cursor: pointer;"><Close /></el-icon>
      </div>
      <div>
      <div style="display: flex;width: 90%;margin-left: 5%;margin-top:10%;align-items: center;justify-content: space-between;">
        <el-input v-model="serviceUrl" style="width: 90%;" placeholder="Please input" disabled>
          <template #prepend>
            <div v-if="serviceRqtype==='GET'" style="color: #67C23A;background-color: transparent;">
              GET
            </div>
            <div v-if="serviceRqtype==='POST'" style="color: #409EFF;background-color: transparent;">
              POST
            </div>
          </template>
        </el-input>
        <svg-icon icon-class="startTest" style="margin-left: auto;width: 50px;height: 25px;cursor: pointer;"/>
      </div>
      <div style="display: flex;width: 90%;margin-left: 5%;margin-top:10%;align-items: center;justify-content: space-between;">
        <el-table :data="tableDataCan" border style="width: 100%">
          <el-table-column prop="paramCode" label="参数名" width="" />
          <el-table-column prop="paramValue" label="参数值" width="">
            <template #default="scope">
              <div style="width: 100%;">
                  <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramValue" size="mini" text style="margin-left: 0%;"></el-input>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex;width: 90%;margin-left: 5%;margin-top:10%;align-items: center;justify-content: space-between;">
        <el-form ref="deptRef" :model="form" label-width="80px" label-position="top">
          <el-form-item label="BODY">
            <el-radio-group v-model="form.bodyType">
              <el-radio value="none">none</el-radio>
              <el-radio value="form-data">form-data</el-radio>
              <el-radio value="x-www-form-urlencoded">x-www-form-urlencoded</el-radio>
              <el-radio value="JSON">JSON</el-radio>
              <el-radio value="raw">raw</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="失败处理">
            <el-select v-model="form.errorPolicy" style="width: 50%">
              <el-option label="报错" value="ABORT"></el-option>
              <el-option label="忽视" value="IGNORE"></el-option>
              <el-option label="重连" value="RETRY"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="失败重连次数">
            <el-input-number  v-model="form.retryCount" :min="1" style="width: 50%" :max="30"/>
          </el-form-item>
          <el-form-item  label="输出">
            <el-table :data="tableDataCanOut" border style="width: 100%">
              <el-table-column prop="paramCode" label="参数名" width="" />
              <el-table-column prop="paramValue" label="参数值" width="">
                <template #default="scope">
                  <div style="width: 100%;">
                      <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramValue" size="mini" text style="margin-left: 0%;"></el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      </div>
    </div>
    <div style="display: flex;height: 87vh;width: 100%;padding-top:2%;justify-items: center;">
      <div style="width: 20%;margin-left: 1%;overflow-y: auto;margin-top: 0.5%;">
        <el-input
          v-model="inputNode"
          style="width:90%;margin-left: 5%;background-color: #ebeef5;margin-top: 1%;"
          class="w-50 m-2"
          :prefix-icon="Search" 
        />
        <el-tree :expand-on-click-node="false" ref="treeRef" :filter-node-method="filterNode" :current-node-key="currentNodeKey" class="treeLeft" :data="dataTree" 
        @node-click="handleNodeClick" node-key="id" style="margin-left: 5%;margin-top: 3%;width: 90%;background-color: transparent;" default-expand-all :key="valueKet">
          <template #default="{ node, data }">
            <span  style="justify-content: space-between;display: flex;width: 100%;align-items: center;" :draggable="true" @dragstart="onDragStart($event,data)">
              <div class="custom-tree-node">
                  <!-- <el-tag v-if="data.nodeType=='MODEL'" class="ml-2" type="warning">模型</el-tag> -->
                   <svg-icon icon-class="model2" style="color: #eebe77;" v-if="data.nodeType=='MODEL'"/>
                  <!-- <el-tag  class="ml-2">
                    服务
                  </el-tag> -->
                  <svg-icon icon-class="model" dstyle="color: #13E03B;" v-if="data.nodeType=='SERVICE'"/>
                  <svg-icon svg-icon icon-class="cate" style="color: red;" v-if="data.nodeType=='TREE'"/>
                <span>{{ node.label }}</span>
              </div>
            </span>
          </template>
        </el-tree>
      </div>
      <div ref="flowContainer" style="width: 80%;">
        <VueFlow  ref="vueFlowRef" style="background-color: #EFEFF4;margin-top: 0.5%;" :nodes="nodes" :viewport="zoom" :edges="edges" @drop="onDrop" @dragover="onDragOver" @dragleave="onDragLeave"
          @node-click="onNodeClick"   @connect="onConnect" fit-view-on-init>
          <Controls :showInteractive="false" :showFitView="false"/>
          <template #node-special="specialNodeProps">
            <div v-if="specialNodeProps.data.label=='开始'" class="vue-flow__node-default" style="border: 0.2px solid #c8c9cc;border-radius: 6px;min-height: 6vh;min-width: 11vw">
                <div style='width:100%;font-size:10px;display:flex;align-items:flex-end;height: 10px;margin-top: 2%;'>
                  <img style="width: 15px;height:15px;border-radius: 12px;" src="@/assets/images/icon-Start-v2.jpg" alt="">
                  <div style="margin-left: 3%;font-weight: 500;">
                    开始
                  </div>
                  <el-tag class="ml-2" style="width: 30px;height: 15px;font-size: 7px;margin-left: 6%;" type="info">触发器</el-tag>
                </div>
                  <Handle type="source" :position="Position.Right"/>
              </div>
              <div v-if="specialNodeProps.data.label=='结束'" class="vue-flow__node-default" style="border: 0.2px solid #c8c9cc;border-radius: 6px;min-height: 6vh;min-width: 11vw">
                <div style='width:100%;font-size:10px;display:flex;align-items:flex-end;height: 10px;margin-top: 2%;'>
                  <img style="width: 15px;height:15px;border-radius: 12px;" src="@/assets/images/icon-Start-v2.jpg" alt="">
                  <div style="margin-left: 3%;font-weight: 500;">
                    结束
                  </div>
                  <div>

                  </div>
                </div>
                  <Handle type="target" :position="Position.Left"/>
              </div>
              <div v-if="specialNodeProps.data.label!=='结束'&&specialNodeProps.data.label!=='开始'" class="vue-flow__node-default" 
              style="border: 0.5px solid #c8c9cc;border-radius: 6px;border-radius: 6px;min-height: 8vh;min-width: 13vw">
                <div style='width:100%;font-size:10px;display:flex;align-items:flex-end;height: 10px;margin-top: 2%;justify-content: space-between;'>
                  <img style="width: 15px;height:15px;border-radius: 12px;" src="@/assets/images/icon-HTTP.png" alt="">
                  <div style="margin-left:3%;font-weight: 500;"> 
                    <el-input class="custom-no-border" placeholder="" type="primary" v-model="specialNodeProps.data.label" size="mini" text 
                    style="margin-left: 0%;font-size: 10px;height: 15px;width: 150%;" ></el-input>
                    <!-- {{ specialNodeProps.data.label}} -->
                  </div>
                  <el-icon style="cursor: pointer;margin-left: auto;"><CaretRight /></el-icon>
                  <el-icon @click.stop="delNode(specialNodeProps)" style="cursor: pointer;color: #F56C6C;margin-left: 2%;"><Delete /></el-icon>
                </div>
                <div style="display: flex;margin-top: 3%;">
                  <el-tag class="ml-2" style="width: 35px;height: 20px;font-size: 10px;" type="warning">服务</el-tag>
                </div>
                <div style="display: flex;margin-top: 3%;font-size: 9px;color: #b1b3b8;flex-wrap: wrap;align-items: flex-start;">
                  <div style="word-break: break-all;min-width: 0;width: 100%;text-align: left;">
                    {{ specialNodeProps.data.service.rqtype+ ':' }}{{ specialNodeProps.data.service.url }}
                  </div>
                </div>
                <div style="display: flex;margin-top: 3%;font-size: 9px;color: #b1b3b8;align-items: center;">
                  <div>
                    说明:
                  </div>
                  <div>
                    {{ specialNodeProps.data.service.intro }}
                  </div>
                </div>
                  <Handle type="source" :position="Position.Right"/>
                  <Handle type="target" :position="Position.Left"/>
              </div>
          </template>
          <template #edge-custom="specialEdgeProps">
            <div style="height: 1px;color: red;">

            </div>
          </template> 
        </VueFlow>
      </div>
      
    </div>

  </div>
</template>
<script setup>
import html2canvas from 'html2canvas';
import { Controls } from '@vue-flow/controls'
import '@vue-flow/controls/dist/style.css'
import '@vue-flow/core/dist/theme-default.css';
import { Plus,Search } from '@element-plus/icons-vue'
import DynamicMap from '@/components/DynamicMap/index.vue'
import {Promotion} from '@element-plus/icons-vue'
import { onMounted, ref,onBeforeUnmount } from 'vue'
import {useVueFlow, VueFlow ,MarkerType } from '@vue-flow/core'
import SpecialNode from './components/SpecialNode.vue'
import SpecialEdge from './components/SpecialEdge.vue'
import {getPtServiceList,getSerDe} from "@/api/service/info.js";
import {getModelList2} from "@/api/register/regCom.js";
import {copyObject} from "@/utils/index.js";
import {getModelingDe,addModelingFlow,editModelingFlow,delFlow} from "@/api/standardization/modeling.js";
import { useStore } from 'vuex';
import {Handle, Position} from '@vue-flow/core'
import { computed } from 'vue';
import { modelTreeSelect } from "@/api/service/info";
const {
  snapToGrid,
  addEdges,
  onEdgeClick,
  addNodes,
  removeNodes,
  screenToFlowCoordinate,
  onNodesInitialized,
  updateNode,
  onNodeClick,
  getNodes,
  zoomTo,
  toObject,
  getEdges,
} = useVueFlow()
snapToGrid.value = true
const vueFlowModel = ref();
const tableDataCanOut = ref([]);
const flowContainer = ref(null);
const status = ref('就绪');
const zoom = ref();
const inputNode = ref('');
const vueFlowRef = ref(null);
const treeRef = ref(null);
const servieName = ref()
const serviceRqtype = ref()
const serviceUrl = ref()
const parFlowId = ref()
const tableDataCan = ref()
const nodeDeSer = ref(false)
const isAdd = ref(false)
const {proxy} = getCurrentInstance();
const modelQueryParams = ref({
  name: undefined,
  isPublic: '0',
});
const toolQueryParams = ref({
  name: undefined,
});
const dataTree = ref([]);
const modelOptions = ref(undefined);
const modelId = ref(undefined);
const loading = ref(true);
const toolType = ref('0');
const serviceList = ref([]);
const defaultEdgeStyle = {
  style: { 
    stroke: '#79bbff', 
    strokeWidth: 2,
    type: 'bezier', 
    fill: 'none' // 避免截图时出现黑色背景 [4](@ref)
  },
  markerEnd: {
    type: MarkerType.Arrow,
    color: '#79bbff', // 箭头颜色
    width: 15,        // 箭头宽度
    height: 15        // 箭头高度
  }
};
const draggedData = ref(undefined);
const isDragging = ref(false);
const isDragOver = ref(false);
const nodes = ref([
  { id: '1', position: { x: -600, y: -300 }, data: { label: '开始' }, type: 'special' },
  { id: '2', position: { x: 150, y: 100 }, data: { label: '结束' }, type: 'special' },
]);
const edges =  ref([]);
const form = ref({
  bodyType: 'none',
  errorPolicy: 'ABORT',
  retryCount: 0,
});
const title = ref('')
const open = ref(false)
const store = useStore();

watch(inputNode, (val) => {
  treeRef.value?.filter(val); // 调用树的过滤方法
});
function showData(){
  console.log(nodes.value)
}
function delWholeFlow(){
  proxy.$confirm('是否删除该模型流程？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFlow(parFlowId.value).then(res => {
            if(res.code === 200){
                proxy.$message({
                    message: '删除成功',
                    type: 'success'
                });
                getList();
            } else {
                proxy.$message.error('删除失败');
            }
        })
      })
}
const toImage = async () => {
  console.log(flowContainer.value)
  await nextTick(); 
  status.value = '生成图片中...';
  try {
    const canvas = await html2canvas(flowContainer.value, {
      backgroundColor: '#fff', // 白底背景
      scale: 2, // 提高导出清晰度
      useCORS: true, // 支持跨域图片
    });
    
    // 生成下载链接
    const dataUrl = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = 'vueflow-diagram.png'; // 文件名
    link.click();
    
    status.value = '导出成功！';
    setTimeout(() => status.value = '就绪', 3000); // 重置状态
  } catch (error) {
    status.value = `导出失败: ${error.message}`;
    console.error('导出错误:', error);
  }
};
async function delNode(node){
  removeNodes([node])
  await nextTick()
  
}
onEdgeClick(({ edge }) => {
  console.log(edges.value,edge)
  edges.value = edges.value.filter(item => item.id !== edge.id)
});
async function getTreeLeft(){
  await modelTreeSelect().then(res=>{
    dataTree.value = res.data
  })
}
function saveFlow(){
  if(isAdd.value){
    const count = computed(() => store.getters.id)
    var par = {
      appId: count.value,
      flowName:'default',
      flowGraph: JSON.stringify(toRaw(toObject()))
    }
    console.log(par)
    addModelingFlow(par).then(res=>{
      if(res.code===200){
        proxy.$message({
          message: '保存成功',
          type: 'success'
        });
      }
      getList()
    })
  }
  else{
    const count = computed(() => store.getters.id)
    var par = {
      flowId: parFlowId.value,
      appId: count.value,
      flowName:'default',
      flowGraph: JSON.stringify(toRaw(toObject()))
    }
    console.log(par)
    editModelingFlow(par).then(res=>{
      if(res.code===200){
        proxy.$message({
          message: '保存成功',
          type: 'success'
        });
        getList()
      }
    })
  }
}
onNodeClick(({event, node}) => {
  console.log(node)
  if(node.data.nodeType==='SERVICE'){
    getSerDe(node.data.id).then(res=>{
      serviceRqtype.value = res.data.ptService.rqtype
      servieName.value = res.data.ptService.name
      tableDataCan.value = res.data.list
      tableDataCanOut.value = res.data.returnList
      serviceUrl.value = res.data.ptService.url
      nodeDeSer.value = true
    })
    
  }
  
});

/**
 * 开始拖拽选项的事件
 * @param event
 * @param data
 */
function onDragStart(event, data) {
  if (event.dataTransfer) {
    event.dataTransfer.setData('application/vueflow', data)
    event.dataTransfer.effectAllowed = 'move'
  }

  draggedData.value = data
  isDragging.value = true
  
  document.addEventListener('drop', onDragEnd)
}
function back(){
  proxy.$router.push({ path: '/standardization/modelUsing' });
}
/**
 * 拖拽到画布vueflow的事件
 * @param event
 */
function onDragOver(event) {
  event.preventDefault()
  
  if (draggedData.value) {
    isDragOver.value = true

    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = 'move'
    }
  }
}

/**
 * 拖拽放下的事件
 * @param event
 */

function onDrop(event) {
  getSerDe(draggedData.value.id).then(res=>{
    draggedData.value = res.data.ptService
  })
  const position = screenToFlowCoordinate({
    x: event.clientX,
    y: event.clientY,
  })

  const nodeId = Math.random() + "id";
  const data = copyObject(draggedData.value)
  const newNode = {
    id: nodeId,
    type: 'special',
    position,
    data,
  }

  // 更新位置到鼠标中心
  const {off} = onNodesInitialized(() => {
    updateNode(nodeId, (node) => ({
      position: {x: node.position.x - node.dimensions.width / 2, y: node.position.y - node.dimensions.height / 2},
    }))

    off()
  })

  addNodes(newNode)
  // nodes.value.push(newNode)
}

/**
 * 拖拽到画布外面的的事件
 */
function onDragLeave() {
  isDragOver.value = false
}

/**
 * 拖拽结束
 */
function onDragEnd() {
  isDragging.value = false
  isDragOver.value = false
  draggedData.value = null
  document.removeEventListener('drop', onDragEnd)
}

function onConnect(params) {
  addEdges({ ...params, ...defaultEdgeStyle })
}

/** 查询模型列表 */
function getModelList() {
  getModelList2(modelQueryParams.value).then(res => {
    loading.value = false;
    modelOptions.value = res.data;
  });
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 查询流程图 */
function getList() {
  const count = computed(() => store.getters.id)
  console.log(count.value);
  var par = {
    appId: count.value
  }
  getModelingDe(par).then(res => {
    if(res.data.length===0){
      isAdd.value = true
      nodes.value = [
        { id: '1', position: { x: -600, y: -300 }, data: { label: '开始' }, type: 'special' },
        { id: '2', position: { x: 150, y: 100 }, data: { label: '结束' }, type: 'special' },
      ]
    }
    else{
      isAdd.value = false
      var a = JSON.parse(JSON.parse(JSON.stringify(res.data[0].flowGraph)))
      console.log(a)
      nodes.value = a.nodes
      edges.value = a.edges
      zoom.value = a.zoom
      zoomTo(zoom.value) 
      parFlowId.value = res.data[0].flowId
    }
  });
}

onMounted(() => {
    getTreeLeft()
    getList();
})

watch(nodes, (newNodes) => {
  console.log('当前节点列表:', newNodes) // 实时输出最新数据
}, { deep: true })
</script>
<style>
@import '@vue-flow/core/dist/style.css';
@import '@vue-flow/core/dist/theme-default.css';
</style>
<style scoped>
.custom-no-border :deep(.el-input__wrapper) {
  box-shadow: none !important; /* 移除默认阴影（即边框） */
  border: none !important;     /* 双重保障 */
}
/* 处理悬停和聚焦状态 */
.custom-no-border :deep(.el-input__wrapper:hover),
.custom-no-border :deep(.el-input__wrapper:focus-within) {
  box-shadow: none !important;
  border: none !important;
}
:deep(.treeLeft) .el-tree-node__content {
  display: flex !important;
  height: 28px;                  /* 按设计稿调整高度 */
  align-items: center;
  padding-top: 0 !important;
}
:deep(.treeLeft) .el-tree-node__content:hover {
  background-color: #e9e9eb;
}
:deep(.treeLeft) .el-tree-node__content:active {
    background-color: rgka(69,157,255,0.1) !important;
  }

  /* 选中态（Active） */
:deep(.treeLeft) .el-tree-node.is-current > .el-tree-node__content {
    background-color: #c6e2ff !important;
  }
</style>