<template>
  <el-dialog title="设备通道配对" v-model='dialogVisible' v-bind="dialogBig">
      <div  class="flow-container" style="overflow: hidden; position: relative;">
          <!-- <el-form  ref='dialogFormRef' :disabled="false" label-width="auto" class="form-two">
             <el-form-item label='被检设备'  prop='type'>
                  <el-select v-model="value"  clearable placeholder="被检设备" >
                    <el-option label="CN88888" :value="2"></el-option>
                    <el-option label="CN250985" :value="1"></el-option>     
                    <el-option label="PQS240224008" :value="0"></el-option>                              
                  </el-select>                           
              </el-form-item>  
              <el-form-item label='标准设备'  prop='type' >
                    <el-select v-model="value"  clearable placeholder="被检设备" >
                      <el-option label="CN88888" :value="2"></el-option>
                      <el-option label="CN250985" :value="1"></el-option>     
                      <el-option label="PQS240224008" :value="0"></el-option>                              
                    </el-select>                           
              </el-form-item>   
          </el-form> -->
            <!-- <el-button @click="logConnections">打印当前配对</el-button>  -->
            <VueFlow 
                :nodes="nodes" 
                :edges="edges"
                :connection-radius="30" 
                :nodes-draggable="false" 
                :dragging = "false"
                :zoom-on-scroll="false" 
                :pan-on-drag="false" 
                :disable-zoom-pan-on-connect="true"
                auto-connect 
                @connect="handleConnect"
                />          
        </div>
        

  </el-dialog>
 
</template>

<script lang="ts" setup>
import { h, ref} from 'vue'
import { VueFlow, useVueFlow} from '@vue-flow/core'
import {dialogBig} from "@/utils/elementBind";
import {Platform,Promotion,Flag} from '@element-plus/icons-vue'
import { c } from 'vite/dist/node/types.d-aGj9QkWt';
import { de, el } from 'element-plus/es/locale';
const dialogVisible = ref(false)
// 初始化 VueFlow
const { edges} = useVueFlow()


// 提取公共的label渲染函数
const createLabel = ( text: string,type :string) => {
  return h('div', {
    style: {
      display: 'flex',
      flexDirection: 'column', // 图标和文字上下排列
      alignItems: 'center',
      fontSize: '15px',
      textAlign: 'center',
      border: '1px solid #ccc',   // 添加边框
      borderRadius: '8px',        // 圆角
      padding: '8px',             // 内边距
      backgroundColor: '#f9f9f9'  // 可选：背景色
    }
  }, [
    h(Platform, {
      style: {
        width: '20px',
        marginBottom: '4px', // 图标与文字间距
        color: '#526ade'
      }
    }),
    h('div', null, '设备名称：'+ text),
    h('div', null, '设备类型：'+ type)
   ]) as any
}

const createLabel2 = (text: string) => {
  return h('div', {
    style: {
      display: 'flex',
      alignItems: 'center',
       fontSize: '15px',
      textAlign: 'center',
      border: '1px solid #ccc',   // 添加边框
      borderRadius: '8px',        // 圆角
      padding: '8px',             // 内边距
      backgroundColor: '#f9f9f9'  // 可选：背景色
    }
  }, [
    h(Promotion, {
      style: {
        width: '20px',
        marginRight: '4px',
        color: '#526ade'
      }
    }),
    text
  ]) as any
}

const createLabel3 = (text: string) => {
  return h('div', {
    style: {
      display: 'flex',
      alignItems: 'center',
      fontSize: '15px',
      textAlign: 'center',
      border: '1px solid #ccc',   // 添加边框
      borderRadius: '8px',        // 圆角
      padding: '8px',             // 内边距
      backgroundColor: '#f9f9f9'  // 可选：背景色
    }
  }, [
    h(Flag, {
      style: {
        width: '20px',
        marginRight: '4px',
        color: '#526ade'
      }
    }),
    text
  ]) as any
}

// 节点数据
const nodes2 = ref([
  {
    id: '1',
    data: { label: createLabel('被检设备1') },
    position: { x: 0, y: 50 },
    class: 'no-handle-node', // 👈 添加自定义 class
    style: { width: '200px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '2',
    data: { label: createLabel('标准设备1') },
    position: { x: 950, y: 0 },
    class: 'no-handle-node', // 👈 添加自定义 class
    style: { width: '200px', border: 'none', boxShadow: 'none'  }
  },

  {
    id: '3',
    data: { label: createLabel('被检设备2') },
    position: { x: 0, y: 250 },
    class: 'no-handle-node', // 👈 添加自定义 class
    style: { width: '200px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '4',
    data: { label: createLabel('标准设备2') },
    position: { x: 950, y: 200 },
    class: 'no-handle-node', // 👈 添加自定义 class
    style: { width: '200px', border: 'none', boxShadow: 'none'  }
  },


    {
    id: '5',
    data: { label: createLabel('被检设备3') },
    position: { x: 0, y: 425 },
    class: 'no-handle-node', // 👈 添加自定义 class
    style: { width: '200px', border: 'none', boxShadow: 'none' }
  },


  {
    id: '被检通道1',
    type: 'input',
    data: { label: createLabel3('被检通道1') },
    position: { x: 200, y: 0 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none'  }
  },
  {
    id: '被检通道2',
    type: 'input',
    data: { label: createLabel3('被检通道2') },
    position: { x: 200, y:50 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '被检通道3',
    type: 'input',
    data: { label: createLabel3('被检通道3') },
    position: { x: 200, y: 100 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '被检通道4',
    type: 'input',
    data: { label: createLabel3('被检通道4') },
    position: { x: 200, y: 150 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },

    {
    id: '被检通道5',
    type: 'input',
    data: { label: createLabel3('被检通道1') },
    position: { x: 200, y: 250 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none'  }
  },
  {
    id: '被检通道6',
    type: 'input',
    data: { label: createLabel3('被检通道2') },
    position: { x: 200, y:300 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },


  {
    id: '被检通道7',
    type: 'input',
    data: { label: createLabel3('被检通道1') },
    position: { x: 200, y:400 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '被检通道8',
    type: 'input',
    data: { label: createLabel3('被检通道2') },
    position: { x: 200, y:450 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
    {
    id: '被检通道9',
    type: 'input',
    data: { label: createLabel3('被检通道3') },
    position: { x: 200, y:500 },
    sourcePosition: 'right',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },


  {
    id: '标准通道1',
    type: 'output',
    data: { label: createLabel2('标准通道1') },
    position: { x: 800, y: 0 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '标准通道2',
    type: 'output',
    data: { label: createLabel2('标准通道2') },
    position: { x: 800, y: 50 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },

   {
    id: '标准通道3',
    type: 'output',
    data: { label: createLabel2('标准通道1') },
    position: { x: 800, y: 150 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '标准通道4',
    type: 'output',
    data: { label: createLabel2('标准通道2') },
    position: { x: 800, y: 200 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
   {
    id: '标准通道5',
    type: 'output',
    data: { label: createLabel2('标准通道3') },
    position: { x: 800, y: 250 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
  {
    id: '标准通道6',
    type: 'output',
    data: { label: createLabel2('标准通道4') },
    position: { x: 800, y: 300 },
    targetPosition: 'left',
    style: { width: '150px', border: 'none', boxShadow: 'none' }
  },
]);

const handleConnect = (params: any) => {
  const sourceNode = nodes.value.find(node => node.id === params.source)
  const targetNode = nodes.value.find(node => node.id === params.target)
  // 连接规则验证
  const isValidConnection = 
    sourceNode?.type === 'input' && 
    targetNode?.type === 'output'

  if (!isValidConnection) {
     // 删除当前连接
    removeEdge(params)
  } 
}
// 删除不合法连接的函数
const removeEdge = (params: any) => {
  const edgeIndex = edges.value.findIndex(edge => edge.source === params.source && edge.target === params.target)
  if (edgeIndex !== -1) {
    edges.value.splice(edgeIndex, 1) // 删除该连接
  }
}


// 打印当前节点和连线信息
function logConnections() {
  console.log('当前节点:', nodes.value);
  console.log('当前连线:', edges.value);

  const connections = edges.value.map(edge => ({
    source: edge.source,
    target: edge.target,
    label: `${edge.source} → ${edge.target}`
  }));

  console.table(connections);
}

const nodes = ref([])
const open = async () => {
  nodes.value = createNodes()
  dialogVisible.value = true
}

  // 每台设备的通道数量
  const channelCounts = {
    '1': 1, // 被检设备1 → 4个通道
    '3': 3, // 被检设备2 → 2个通道
    '5': 2, // 被检设备3 → 2个通道
    '7': 4  // 被检设备4 → 4个通道
  }

    // 每台设备的通道数量
  const channelCounts2 = {
    '2': 2, // 标准设备1 → 2个通道
    '4': 1, // 标准设备2 → 1个通道
  }

  const yPosition = ref(25)
  const yPosition2 = ref(25)
const createNodes = () => {
  const newNodes: any[] = []


  // 存储每组被检/标准通道的垂直范围
  const deviceChannelGroups: { deviceId: string; centerY: number; }[] = []
  const standardChannelGroups: any[] = []
 
  const deviceWidth = 0
  const inputChannelX = 200
  const outputChannelX = 800
  const standardWidth = 950

  // 添加被检通道
  Object.entries(channelCounts).forEach(([deviceId, count]) => {
    for (let i = 1; i <= count; i++) {
      const channelId = `被检通道-${deviceId}-${i}`
      newNodes.push({  
        id: channelId,
        type: 'input',
        data: { label: createLabel3(`被检通道${i}`) },
        position: { x: inputChannelX, y: yPosition.value },
        sourcePosition: 'right',
        style: { width: '150px', border: 'none', boxShadow: 'none' }
      })
      if(i == 1 && count == 1){
         deviceChannelGroups.push({
          deviceId,
          centerY: yPosition.value - 25
        })
      }else if(i == 2 && count == 2){
         deviceChannelGroups.push({
          deviceId,
          centerY: yPosition.value - 50
        })
      }else if(i == 3 && count == 3){
        deviceChannelGroups.push({
          deviceId,
          centerY: yPosition.value - 75
        })
      }else if(i == 4 && count == 4){
        deviceChannelGroups.push({
          deviceId,
          centerY: yPosition.value - 100
        })
      }
      yPosition.value += 50 
    }
    yPosition.value += 50
  })
  // 添加标准通道
  Object.entries(channelCounts2).forEach(([deviceId, count]) => {
    for (let i = 1; i <= count; i++) {
      const channelId = `标准通道-${deviceId}-${i}`
      newNodes.push({  
        id: channelId,
        type: 'output',
        data: { label: createLabel3(`标准通道${i}`) },
        position: { x: outputChannelX, y: yPosition2.value },
        targetPosition: 'left',
        style: { width: '150px', border: 'none', boxShadow: 'none' }
      })
     if(i == 1 && count == 1){
         standardChannelGroups.push({
          deviceId,
          centerY: yPosition2.value - 25
        })
      }else if(i == 2 && count == 2){
         standardChannelGroups.push({
          deviceId,
          centerY: yPosition2.value - 50
        })
      }else if(i == 3 && count == 3){
        standardChannelGroups.push({
          deviceId,
          centerY: yPosition2.value - 100
        })
      }else if(i == 4 && count == 4){
        standardChannelGroups.push({
          deviceId,
          centerY: yPosition2.value - 100
        })
      }
       yPosition2.value += 50
    }
     yPosition2.value += 50
  })


    // 添加被检设备
    deviceChannelGroups.forEach(({ deviceId, centerY }) => {
      const device = inspectionDevices.find(d => d.id === deviceId)
      if (!device) return
      newNodes.push({
        id: device.id,
        data: { label: createLabel(device.name,device.deviceType) },
        position: { x: deviceWidth, y: centerY },
        class: 'no-handle-node',
        style: { width: '200px', border: 'none', boxShadow: 'none' }
      })
    })

    // 添加标准设备
    standardChannelGroups.forEach(({ deviceId, centerY }) => {
      const device = standardDevices.find(d => d.id === deviceId)
      if (!device) return
      newNodes.push({
        id: device.id,
        data: { label: createLabel(device.name,device.deviceType) },
        position: { x: standardWidth, y: centerY },
        class: 'no-handle-node',
        style: { width: '200px', border: 'none', boxShadow: 'none' }
      })
    })

  return newNodes
}

const inspectionDevices = [
  { id: '1', name: '被检设备1', type: 'normal', deviceType: 'PQS-882B4' },
  { id: '3', name: '被检设备2', type: 'normal', deviceType: 'PQS-883A2' },
  { id: '5', name: '被检设备3', type: 'normal', deviceType: 'PQS-882B2' },
  { id: '7', name: '被检设备4', type: 'normal', deviceType: 'PQS_883B' }
]

const standardDevices = [
  { id: '2', name: '标准设备1', type: 'normal', deviceType: 'PQS-882A' },
  { id: '4', name: '标准设备2', type: 'normal', deviceType: 'PQS-882B2' },
]


defineExpose({open})
</script>

<style>
.flow-container {
  display: flex;
  flex-direction: column;
  height: 800px;
}

.vue-flow__node.no-handle-node .vue-flow__handle {
  display: none !important;
}
</style>