<template>
  <div class="flow-chart">
    <div class="flow-title">{{ flowTitle }}</div>
    <div class="flow-body" ref="bodyRef">
      <div class="flow-nodes">
        <div
          v-for="(node, index) in activeNodes"
          :key="index"
          class="flow-node-wrap"
          :ref="(el) => (nodeEls[index] = el)"
        >
          <div
            class="flow-node"
            :class="[node.type || 'step', getNodeStatus(index)]"
          >
            <span class="node-label">{{ node.label }}</span>
          </div>
          <div v-if="node.annotation" class="flow-annotation">
            {{ node.annotation }}
          </div>
          <div v-if="index < activeNodes.length - 1" class="flow-arrow">
            <div class="arrow-line"></div>
            <div class="arrow-head"></div>
            <div v-if="hasBidirectional(index)" class="bi-arrow">
              <div class="arrow-head" style="transform: rotate(180deg)"></div>
              <div class="arrow-line"></div>
              <div class="arrow-head"></div>
              <span class="bi-text">提交/退回</span>
            </div>
          </div>
        </div>
      </div>
      <svg
        v-if="svgPaths.length"
        class="return-svg"
        :width="svgWidth"
        :height="svgHeight"
      >
        <defs>
          <marker
            id="arrowEnd"
            markerWidth="8"
            markerHeight="6"
            refX="8"
            refY="3"
            orient="auto"
          >
            <path d="M0,0 L8,3 L0,6 Z" fill="#909399" />
          </marker>
        </defs>
        <g v-for="(path, i) in svgPaths" :key="i">
          <polyline
            :points="path.points"
            fill="none"
            stroke="#909399"
            stroke-width="1.5"
            marker-end="url(#arrowEnd)"
          />
          <text
            :x="path.textX"
            :y="path.textY"
            font-size="11"
            fill="#909399"
            text-anchor="middle"
            dominant-baseline="middle"
            :transform="path.textRotate"
          >
            {{ path.label }}
          </text>
        </g>
      </svg>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from "vue";

const props = defineProps({
  flowType: {
    type: String,
    default: "complex",
  },
  currentState: {
    type: Number,
    default: 0,
  },
});

const complexNodes = [
  { label: "开始", type: "terminal" },
  { label: "所属单位员工发起" },
  { label: "所属单位部门长核准" },
  { label: "投管部经办人初审", returnTo: 1 },
  { label: "投管部正副职审核" },
  { label: "结束", type: "terminal" },
];

const complexBiIndices = new Set([1, 3]);

const simpleNodes = [
  { label: "开始", type: "terminal" },
  { label: "投管部员工发起" },
  { label: "投管部正副职审核" },
  { label: "结束", type: "terminal" },
];

const simpleBiIndices = new Set([1]);

const complexLevelMap = {
  1: 2,
  7: 2,
  2: 3,
  3: 4,
  4: 5,
  8: 5,
  5: 6,
  9: 6,
  13: 6,
  14: 6,
  15: 6,
};

const simpleLevelMap = {
  1: 2,
  2: 2,
  3: 3,
  4: 3,
  5: 4,
};

const activeNodes = computed(() => {
  const result = props.flowType === "simple" ? simpleNodes : complexNodes;
  console.log('[ProcessFlowChart] flowType:', props.flowType, '=> 使用' + (props.flowType === 'simple' ? '简单' : '复杂') + '流程, currentState:', props.currentState);
  console.log('[ProcessFlowChart] 节点列表:', result.map(n => n.label).join(' -> '));
  return result;
});

const hasBidirectional = (index) => {
  const biSet =
    props.flowType === "simple" ? simpleBiIndices : complexBiIndices;
  return biSet.has(index);
};

const highlightLevel = computed(() => {
  const map = props.flowType === "simple" ? simpleLevelMap : complexLevelMap;
  const level = map[props.currentState] || 0;
  console.log('[ProcessFlowChart] currentState:', props.currentState, '=> highlightLevel:', level, '(使用' + (props.flowType === 'simple' ? '简单' : '复杂') + 'LevelMap)');
  return level;
});

const flowTitle = computed(() => {
  if (props.flowType === "simple") return "立项审批流程";
  return props.currentState >= 7 ? "决策审批流程" : "立项审批流程";
});

const getNodeStatus = (index) => {
  const level = highlightLevel.value;
  const total = activeNodes.value.length;
  if (level === 0 || index >= level) return "";
  if (level >= total) return "completed";
  if (index === level - 1) return "active";
  return "completed";
};

const bodyRef = ref(null);
const nodeEls = ref([]);
const svgWidth = ref(0);
const svgHeight = ref(0);
const svgPaths = ref([]);

const calcSvgPaths = () => {
  const body = bodyRef.value;
  if (!body) return;
  const bodyRect = body.getBoundingClientRect();
  svgWidth.value = bodyRect.width;
  svgHeight.value = bodyRect.height;

  const paths = [];
  const nodes = activeNodes.value;

  let leftOffset = 0;
  nodes.forEach((node, index) => {
    if (node.returnTo === undefined) return;
    const sourceEl = nodeEls.value[index];
    const targetEl = nodeEls.value[node.returnTo];
    if (!sourceEl || !targetEl) return;

    const sourceNode = sourceEl.querySelector(".flow-node");
    const targetNode = targetEl.querySelector(".flow-node");
    if (!sourceNode || !targetNode) return;

    const sourceRect = sourceNode.getBoundingClientRect();
    const targetRect = targetNode.getBoundingClientRect();

    const sourceY = sourceRect.top + sourceRect.height / 2 - bodyRect.top;
    const targetY = targetRect.top + targetRect.height / 2 - bodyRect.top;
    const nodeLeft = sourceRect.left - bodyRect.left;

    leftOffset += 20;
    const lineX = nodeLeft - leftOffset;

    paths.push({
      points: `${nodeLeft},${sourceY} ${lineX},${sourceY} ${lineX},${targetY} ${nodeLeft},${targetY}`,
      textX: lineX - 8,
      textY: (sourceY + targetY) / 2,
      textRotate: `rotate(-90, ${lineX - 8}, ${(sourceY + targetY) / 2})`,
      label: "返回修改",
    });
  });

  svgPaths.value = paths;
};

onMounted(() => {
  nextTick(calcSvgPaths);
});

watch(
  () => [props.flowType, props.currentState],
  () => {
    nextTick(() => nextTick(calcSvgPaths));
  },
);
</script>

<style scoped lang="scss">
.flow-chart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 12px;
  min-width: 200px;
}

.flow-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.flow-body {
  position: relative;
  width: 100%;
  padding-left: 90px;
}

.flow-nodes {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.return-svg {
  position: absolute;
  top: 0;
  left: -20px;
  pointer-events: none;
  overflow: visible;
}

.flow-node-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  width: 100%;
}

.flow-node {
  min-width: 200px;
  max-width: 280px;
  padding: 10px 24px;
  text-align: center;
  border: 2px solid #dcdfe6;
  background: #fff;
  font-size: 13px;
  color: #606266;
  transition: all 0.3s;

  &.terminal {
    border-radius: 20px;
    background: #f5f7fa;
    border-color: #c0c4cc;
    color: #909399;
  }

  &.step {
    border-radius: 4px;
  }

  &.active {
    border-color: #409eff;
    background: #409eff;
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
  }

  &.completed {
    border-color: #409eff;
    background: #ecf5ff;
    color: #409eff;
  }

  &.terminal.completed {
    background: #ecf5ff;
    border-color: #409eff;
    color: #409eff;
  }

  &.terminal.active {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
  }
}

.node-label {
  white-space: nowrap;
}

.flow-annotation {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

.flow-arrow {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 28px;
  position: relative;

  .arrow-line {
    width: 2px;
    flex: 1;
    background: #c0c4cc;
  }

  .arrow-head {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 6px solid #c0c4cc;
  }
}

.bi-arrow {
  position: absolute;
  left: calc(50% + -5px);
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  .bi-text {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 9px;
    color: #909399;
    white-space: nowrap;
  }
}
</style>
