<template>
  <div class="dcs page">
    <HeaderComponent :title="'硫酸钠自动化工艺模块'" />

    <div class="flow_select" ref="flowRef">
      <div class="back_button" @click="$router.push('/index')">
        <img class="back_img" :src="backButton" alt="返回"/>
        <div class="back_text">返回</div>
      </div>
      <!-- 六边形模块 -->
      <div class="module frame module-reaction" data-key="reaction" :style="getModuleStyle('reaction')"
        @click="$router.push('/controlPage/flowSelect/reaction')">
        <img class="module-img" :src="imgReaction" alt="反应模块" />
        <div class="module-title">反应模块</div>
      </div>

      <div class="module frame module-24" data-key="m24" :style="getModuleStyle('m24')"
        @click="$router.push('/controlPage/flowSelect/flatBeltFiltration')">
        <img class="module-img" :src="img24" alt="24平过滤" />
        <div class="module-title">24平过滤</div>
      </div>

      <div class="module frame module-g1" data-key="g1" :style="getModuleStyle('g1')"
        @click="$router.push('/controlPage/flowSelect/G1Decomposition')">
        <img class="module-img" :src="imgG1" alt="G1分解" />
        <div class="module-title">G1分解</div>
      </div>

      <div class="module frame module-g3" data-key="g3" :style="getModuleStyle('g3')"
        @click="$router.push('/controlPage/flowSelect/G3Decomposition')">
        <img class="module-img" :src="imgG3" alt="G3分解" />
        <div class="module-title">G3分离</div>
      </div>

      <div class="module module-lhgb" data-key="lhgb" :style="getModuleStyle('lhgb')">
        <img class="module-img" :src="lhgb" alt="流化干包" />
        <div class="module-title">流化干包</div>
      </div>

      <div class="module module-s6" data-key="s6" :style="getModuleStyle('s6')">
        <img class="module-img" :src="s6" alt="S6罐" />
        <div class="module-title">S6罐</div>
      </div>

      <div class="module module-muye" data-key="muye" :style="getModuleStyle('muye')">
        <img class="module-img" :src="tank" alt="母液罐" />
        <div class="module-title">母液罐</div>
      </div>

      <div class="module module-guanqu" data-key="guanqu" :style="getModuleStyle('guanqu')">
        <img class="module-img" :src="tank" alt="罐区" />
        <div class="module-title">罐区</div>
      </div>

      <!-- 箭头连线：自动计算样式（left/top/width/rotate） -->
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('reaction', 'm24')" alt="arrow" />
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('m24', 'g1')" alt="arrow" />
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('g1', 'g3')" alt="arrow" />
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('s6', 'g1')" alt="arrow" />
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('g3', 'lhgb')" alt="arrow" />
      <img :src="arrowSvg" class="img-arrow" :style="getArrowStyle('g3', 'guanqu')" alt="arrow" />
      <img :src="G3To24" class="arrow" alt="arrow" style="top: 670px; left: 774px;" />
      <img :src="G3ToG1" class="arrow" alt="arrow" style="top: 816PX; left: 992PX;" />
      <img :src="PinArrow" class="arrow" alt="arrow" style="top: 558PX; left: 465PX;" />
      <img :src="PinToFanyin" class="arrow" alt="arrow" style="top: 426PX; left: 307PX;" />
      <img :src="PinTomuye" class="arrow" alt="arrow" style="top: 236PX; left: 699PX;" />
    </div>
  </div>
</template>

<script setup>
import HeaderComponent from '@/components/DCS/HeaderComponent.vue'
import img24 from '@/assets/dcs/controlRouter/24平过滤.png'
import imgG1 from '@/assets/dcs/controlRouter/G1分解.png'
import imgG3 from '@/assets/dcs/controlRouter/G3分解.png'
import imgReaction from '@/assets/dcs/controlRouter/反应模块.png'
import arrowSvg from '@/assets/dcs/controlRouter/arrow.svg'
import lhgb from '@/assets/dcs/controlRouter/流化干包.svg'
import s6 from '@/assets/dcs/controlRouter/S6罐.svg'
import tank from '@/assets/dcs/controlRouter/罐区.svg'
import G3To24 from '@/assets/dcs/controlRouter/G3至24平箭头.svg'
import G3ToG1 from '@/assets/dcs/controlRouter/G3ToG1.svg'
import PinArrow from '@/assets/dcs/controlRouter/24PinArrow.svg'
import PinTomuye from '@/assets/dcs/controlRouter/24PinTomuye.svg'
import PinToFanyin from '@/assets/dcs/controlRouter/24PinToFanyin.svg'
import backButton from '@/assets/dcs/controlRouter/返回.svg'
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
// import { useRouter } from 'vue-router'

// const router = useRouter()

// 模块定位（像素，可根据实际截图继续微调）
const moduleSize = { width: 233, height: 249 }
const HEADER_HEIGHT = 81
const pos = reactive({
  reaction: { top: 227, left: 98 },
  m24: { top: 388, left: 407 },
  g1: { top: 572, left: 696 },
  g3: { top: 643, left: 1057 },
  lhgb: { top: 592, left: 1350 },
  s6: { top: 366, left: 798 },
  muye: { top: 123, left: 900 },
  guanqu: { top: 257, left: 1272 },
})

// 根据 pos 生成模块的定位样式，并扣除头部高度
function getModuleStyle(key) {
  const p = pos[key]
  if (!p) return {}
  return {
    left: `${p.left}px`,
    top: `${p.top - HEADER_HEIGHT}px`,
    width: `${moduleSize.width}px`,
    height: `${moduleSize.height}px`,
  }
}

// DOM 参考，使用实际渲染矩形计算边缘到边缘的箭头
const flowRef = ref(null)

function getElRect(key) {
  const root = flowRef.value
  if (!root) return null
  // 优先使用模块内的首个图片作为定位参考，避免是否带边框导致的偏差
  const img = root.querySelector(`.module[data-key="${key}"] .module-img`)
  const el = img || root.querySelector(`.module[data-key="${key}"]`)
  if (!el) return null
  const rootRect = root.getBoundingClientRect()
  const r = el.getBoundingClientRect()
  return {
    left: r.left - rootRect.left,
    top: r.top - rootRect.top,
    width: r.width,
    height: r.height,
  }
}

function edgeIntersection(fromRect, toRect) {
  const fromCenter = {
    x: fromRect.left + fromRect.width / 2,
    y: fromRect.top + fromRect.height / 2,
  }
  const toCenter = {
    x: toRect.left + toRect.width / 2,
    y: toRect.top + toRect.height / 2,
  }
  const dx = toCenter.x - fromCenter.x
  const dy = toCenter.y - fromCenter.y
  const len = Math.hypot(dx, dy)
  if (len === 0) return { start: fromCenter, end: toCenter, len, angle: 0, ux: 0, uy: 0 }
  const ux = dx / len
  const uy = dy / len

  // 椭圆近似模块外形，减少不同方向上的系统性偏差
  const margin = 12 // 略缩内切，避免压到边框描边
  const rxFrom = Math.max(0, fromRect.width / 2 - margin)
  const ryFrom = Math.max(0, fromRect.height / 2 - margin)
  const rxTo = Math.max(0, toRect.width / 2 - margin)
  const ryTo = Math.max(0, toRect.height / 2 - margin)

  // 椭圆交点缩放系数 s = 1 / sqrt((ux^2/rx^2) + (uy^2/ry^2))
  const sFrom = 1 / Math.sqrt((ux * ux) / ((rxFrom || 1e-6) * (rxFrom || 1e-6)) + (uy * uy) / ((ryFrom || 1e-6) * (ryFrom || 1e-6)))
  const sTo = 1 / Math.sqrt((ux * ux) / ((rxTo || 1e-6) * (rxTo || 1e-6)) + (uy * uy) / ((ryTo || 1e-6) * (ryTo || 1e-6)))

  const start = { x: fromCenter.x + ux * sFrom, y: fromCenter.y + uy * sFrom }
  const end = { x: toCenter.x - ux * sTo, y: toCenter.y - uy * sTo }
  const segLen = Math.hypot(end.x - start.x, end.y - start.y)
  const angleDeg = Math.atan2(dy, dx) * 180 / Math.PI
  return { start, end, len: segLen, angle: angleDeg, ux, uy }
}

// 箭头自动计算参数
const ARROW_BASE_ANGLE = -135.77 // 资源基准朝向校正
const LONG_WIDTH = 100
const MIN_WIDTH = 40
const LONG_THRESHOLD = 260 // 线段长度阈值（保留但不强制使用）

function computeShortWidth(fromKey, toKey) {
  const a = pos[fromKey]
  const b = pos[toKey]
  if (!a || !b) return 71
  const gapX = Math.max(0, Math.abs(b.left - a.left) - moduleSize.width)
  const gapY = Math.max(0, Math.abs(b.top - a.top) - moduleSize.height)
  const shortLen = Math.hypot(gapX, gapY)
  return Math.max(0, Math.min(shortLen, LONG_WIDTH))
}

// 针对个别连线的屏幕坐标微调（像素），默认不偏移
function getEdgeOffsetPx(fromKey, toKey) {
  const key = `${fromKey}>${toKey}`
  switch (key) {
    case 's6>g1':
      return { dx: 0, dy: -30 }
    default:
      return { dx: 0, dy: 0 }
  }
}

function getArrowStyle(fromKey, toKey) {
  const fromRect = getElRect(fromKey)
  const toRect = getElRect(toKey)
  if (!fromRect || !toRect) return {}
  const { start, end, len, angle, ux, uy } = edgeIntersection(fromRect, toRect)
  // 宽度按两模块净间距计算，并夹在 [40, 100]
  const width = Math.max(MIN_WIDTH, Math.min(LONG_WIDTH, computeShortWidth(fromKey, toKey)))
  // 箭头放在连线中心，结合 CSS translate(-50%, -50%) 居中
  // 放在连线中心（去除方向性偏置）
  const cx = (start.x + end.x) / 2
  const cy = (start.y + end.y) / 2

  // 按连线法线方向做统一偏移，补偿箭头资源的视觉中心
  // 取法线方向为 (uy, -ux)，确保 S6->G1 等下行箭头向下偏移
  const nx = uy
  const ny = -ux
  const adjX = cx + nx
  const adjY = cy + ny

  const { dx, dy } = getEdgeOffsetPx(fromKey, toKey)
  return {
    left: `${adjX + dx}px`,
    top: `${adjY + dy}px`,
    width: `${width}px`,
    transform: `translate(-50%, -50%) rotate(${angle + ARROW_BASE_ANGLE}deg)`
  }
}

onMounted(() => { })
onBeforeUnmount(() => { })
</script>

<style lang="scss" scoped>
@import '@/assets/styles/dcs/hnyzConfiguratePage.scss';

.dcs {
  position: relative;
  width: 1920px;
  height: 1080px;
  overflow: hidden;

  // &::before {
  //     content: '';
  //     position: absolute;
  //     inset: 0;
  //     background-image: url('@/assets/dcs/flowBg.jpeg');
  //     background-size: cover;
  //     background-position: center;
  //     background-repeat: no-repeat;
  //     filter: blur(2px);
  //     z-index: 0;
  // }

  .flow_select {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 1;

    .back_button {
      position: relative;
      left: 64px;
      top: 114.5px - 81px;
      flex-shrink: 0;
      width: 124px;

      .back_text {
        position: absolute;
        top: 11px;
        color: #fff;
        left: 48px;
        user-select: none;
      }

      &:hover {
        transform: scale(1.04);
      }
      // .back_img {
      // width: 1920px;
      // }
    }

    // 六边形模块通用样式
    .module {
      position: absolute;
      width: v-bind('moduleSize.width + "px"');
      height: v-bind('moduleSize.height + "px"');

      // 默认无边框
      &::before {
        display: none;
      }

      &.frame::before {
        content: '';
        position: absolute;
        inset: 0;
        background: url('@/assets/dcs/controlRouter/模块框.svg') no-repeat center/contain;
        filter: drop-shadow(0 0 12px rgba(0, 173, 255, .35));
        pointer-events: none;
        display: block;
      }

      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: transform .25s ease;

      &:hover {
        transform: scale(1.04);
      }

      .module-img {
        // 1920*1080
        width: 192px;
        height: 100px;
        // margin-top: 26px; // 让图片位于标题下方
        filter: drop-shadow(0 0 8px rgba(0, 0, 0, .4));
      }

      .module-title {
        position: absolute;
        top: 40px; // 放在六边形内部，位于图片上方
        left: 50%;
        transform: translateX(-50%);
        color: #8ad0ff;
        font-size: 16px;
        line-height: 1;
        letter-spacing: 1px;
        text-shadow: 0 2px 6px rgba(0, 0, 0, .6);
        z-index: 1;
        pointer-events: none;
      }

      .sample {
        position: absolute;
        bottom: -18px;
        left: 50%;
        transform: translateX(-50%);
        color: #ff5ec7;
        font-size: 16px;
      }
    }

    // 定位由脚本中的 getModuleStyle(pos) 生成

    // 箭头
    .img-arrow {
      position: absolute;
      width: 220px;
      filter: drop-shadow(0 0 6px rgba(0, 255, 255, .35));
      z-index: 2; // 箭头在模块之上
      pointer-events: none;
      transform-origin: center center;
    }

    // 固定箭头样式（按需启用）
    // .img-arrow-reaction-m24 {
    //     left: 385px;
    //     top: 336px;
    //     width: 71px;
    //     transform: rotate(-110.5211deg);
    // }
    // .img-arrow-m24-g1 {
    //     left: 671.905px;
    //     top: 518.432px;
    //     width: 71px;
    //     transform: rotate(-100.516deg);
    // }
    // .img-arrow-g1-g3 {
    //     left: 1021.868px;
    //     top: 639.764px;
    //     width: 100px;
    //     transform: rotate(-126.873deg);
    // }
    .arrow {
      position: absolute;
      z-index: 2; // 箭头在模块之上
      pointer-events: none;
      transform-origin: center center;
    }

    .arrow_line {
      border: 2px greenyellow dashed;
    }
  }
}
</style>
