<template>
  <div>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 400" width="600" height="400">
      <!-- 主干 -->
      <path
        ref="mainPipe"
        fill="none"
        stroke="#f1a400"
        stroke-width="10"
        :d="mainPipePath"
        :stroke-dasharray="mainPipeLength"
        :stroke-dashoffset="mainPipeLength - mainPipeProgress"
      />
      <!-- 分支1 -->
      <path
        ref="branch1"
        fill="none"
        stroke="#4db8ff"
        stroke-width="10"
        :d="branch1Path"
        :stroke-dasharray="branch1Length"
        :stroke-dashoffset="branch1Length - branch1Progress"
      />
      <!-- 分支2 -->
      <path
        ref="branch2"
        fill="none"
        stroke="#00ff00"
        stroke-width="10"
        :d="branch2Path"
        :stroke-dasharray="branch2Length"
        :stroke-dashoffset="branch2Length - branch2Progress"
      />
    </svg>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 主干和分支的路径数据
      mainPipePath: "M50,200 C150,200 250,200 350,200",
      branch1Path: "M350,200 C400,150 450,150 500,150",
      branch2Path: "M350,200 C400,250 450,250 500,250",

      // 每条路径的总长度
      mainPipeLength: 0,
      branch1Length: 0,
      branch2Length: 0,

      // 流水的进度
      mainPipeProgress: 0,
      branch1Progress: 0,
      branch2Progress: 0,

      // 添加流速控制
      mainPipeSpeed: 1,
      branch1Speed: 1,
      branch2Speed: 1,

      requestId: null, // 存储requestAnimationFrame返回的ID
    };
  },
  mounted() {
    this.initPipeLengths();
    this.animateFlow();
  },
  beforeDestroy() {
    cancelAnimationFrame(this.requestId); // 组件销毁前清除动画帧请求
  },
  methods: {
    initPipeLengths() {
      this.mainPipeLength = this.$refs.mainPipe.getTotalLength();
      this.branch1Length = this.$refs.branch1.getTotalLength();
      this.branch2Length = this.$refs.branch2.getTotalLength();
    },

    animateFlow() {
      this.updateFlowProgress();
      this.requestId = requestAnimationFrame(this.animateFlow);
    },

    updateFlowProgress() {
      // 更新主干的流水进度
      if (this.mainPipeProgress < this.mainPipeLength) {
        this.mainPipeProgress += this.mainPipeSpeed;
      } else {
        // 当主干的水流到达末端时，开始向分支流动
        if (this.branch1Progress < this.branch1Length) {
          this.branch1Progress += this.branch1Speed;
        }
        if (this.branch2Progress < this.branch2Length) {
          this.branch2Progress += this.branch2Speed;
        }

        // 如果两个分支都完成了水流，则重置所有进度
        if (this.branch1Progress >= this.branch1Length && this.branch2Progress >= this.branch2Length) {
          this.mainPipeProgress = 0;
          this.branch1Progress = 0;
          this.branch2Progress = 0;
        }
      }
    },
  },
};
</script>

<style scoped>
svg {
  display: block;
  margin: 0 auto;
}
</style>