<template>
  <div class="editor-container">
    <div class="left-editor">
      <!-- 左侧编辑区域内容 -->
      <canvas ref="canvas" width="600" height="165"></canvas>
    </div>
    <div class="right-editor">
      <!-- 右侧编辑区域内容 -->
      <el-form-item label="电压有效值(V)">
        <el-input v-model="input1" />
      </el-form-item>
      <el-form-item label="电流有效值(A)">
        <el-input v-model="input1" />
      </el-form-item>
      <el-form-item label="相角(°)">
        <el-input v-model="input2" />
      </el-form-item>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";

const canvas = ref<HTMLCanvasElement | null>(null);

onMounted(() => {
  if (canvas.value) {
    const ctx = canvas.value.getContext('2d');
    if (ctx) {
      drawSineWave(ctx);
    }
  }
});

function drawSineWave(ctx: CanvasRenderingContext2D) {
  const width = canvas.value!.width;
  const height = canvas.value!.height;
  const amplitude = 50; // 振幅
  const frequency = 0.02; // 频率
  const offset = height / 2; // 偏移量

  // 绘制横轴
  ctx.beginPath();
  ctx.moveTo(0, offset);
  ctx.lineTo(width, offset);
  ctx.strokeStyle = 'black';
  ctx.stroke();

  // 绘制纵轴
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(0, height);
  ctx.stroke();

  // 绘制横轴刻度
  const xStep = width / 10;
  for (let x = 0; x <= width; x += xStep) {
    ctx.beginPath();
    ctx.moveTo(x, offset - 5);
    ctx.lineTo(x, offset + 5);
    ctx.stroke();

    // 添加横轴刻度标签
    ctx.font = '12px Arial';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'center';
    ctx.fillText((x / xStep).toFixed(0), x, offset + 20);
  }

  // 绘制纵轴刻度
  const yStep = height / 10;
  for (let y = 0; y <= height; y += yStep) {
    ctx.beginPath();
    ctx.moveTo(-5, y);
    ctx.lineTo(5, y);
    ctx.stroke();

    // 添加纵轴刻度标签
    ctx.font = '12px Arial';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'right';
    ctx.fillText(((offset - y) / yStep - 5).toFixed(1), -10, y + 5);
  }

  // 绘制正弦波
  ctx.beginPath();
  ctx.moveTo(0, offset);

  for (let x = 0; x < width; x++) {
    const y = offset + amplitude * Math.sin(frequency * x);
    ctx.lineTo(x, y);
  }

  ctx.strokeStyle = 'red';
  ctx.lineWidth = 2;
  ctx.stroke();
}
</script>

<style scoped>
canvas {
  border: 1px solid #ccc;
}

.editor-container {
  display: flex;
  height: 100%;
}

.left-editor {
  flex: 3; /* 左侧区域占据 3/4 的宽度 */
  margin-left: 150px; /* 可选：添加间距 */
}

.right-editor {
  flex: 1; /* 右侧区域占据 1/4 的宽度 */
  margin-right: 250px; /* 向左侧移动一点 */
}
</style>