<template>
  <div class="control-panel">
    <div class="status-bar">
      <div class="placeholder-div"></div>
      <div class="title-container">
        <div class="title-box">
          手柄控制界面
        </div>
      </div>
      <div class="top-right-icons">
        <img src="../assets/img/connect.png" alt="link" class="top-icon">
        <img src="../assets/img/bat_empty.png" alt="mp3" class="top-icon">
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧数据显示 -->
      <div class="left-panel">
        <div class="data-card">
          <div class="card-title">摇杆数据</div>
          <div class="data-row">
            <span>X轴:</span>
            <span class="value">{{ directionAxis0_1 }}</span>
          </div>
          <div class="data-row">
            <span>Y轴:</span>
            <span class="value">{{ directionAxis0_1 }}</span>
          </div>
        </div>
      </div>

      <!-- 中间按键状态 -->
      <div class="center-panel">
        <div class="data-card">
          <div class="card-title">按键状态</div>
          <div class="button-grid">
            <div v-for="(button, index) in buttons" 
                 :key="index" 
                 class="button-status"
                 :class="{ 'active': button.pressed }">
              {{ button.name }}
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧方向数据 -->
      <div class="right-panel">
        <div class="data-card">
          <div class="card-title">方向数据</div>
          <div class="data-row">
            <span>当前方向:</span>
            <span class="value">{{ directionAxis9 }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      interval: null,
      gamepad: null,
      gamepadIndex: null,
      buttons: [
        { name: "Left2", pressed: false },
        { name: "Back", pressed: false },
        { name: "Right Joystick Press", pressed: false }
      ],
      directionAxis0_1: "",
      directionAxis9: ""
    };
  },
  created() {
    window.addEventListener("gamepadconnected", this.onGamepadConnected);
    window.addEventListener("gamepaddisconnected", this.onGamepadDisconnected);
  },
  beforeDestroy() {
    window.removeEventListener("gamepadconnected", this.onGamepadConnected);
    window.removeEventListener("gamepaddisconnected", this.onGamepadDisconnected);
  },
  methods: {
    onGamepadConnected(e) {
      console.log("Gamepad connected:", e.gamepad);
      this.gamepadIndex = e.gamepad.index;
      this.gamepad = navigator.getGamepads()[this.gamepadIndex];
      this.startGamepad();
    },
    onGamepadDisconnected() {
      clearInterval(this.interval);
      this.gamepad = null;
    },
    startGamepad() {
      this.interval = setInterval(() => {
        const gamepads = navigator.getGamepads();
        const gamepad = gamepads[this.gamepadIndex];
        
        if (gamepad) {
          console.log('Axes data:', {
            axis0: gamepad.axes[0],
            axis1: gamepad.axes[1],
            gamepadIndex: this.gamepadIndex
          });
          
          this.updateDirection(gamepad.axes);
          this.updateDirectionAxis9(gamepad.axes);
          this.pressKey(gamepad.buttons);
        }
      }, 50);
    },
    updateDirection(axes) {
      const axis0 = axes[0];
      const axis1 = axes[1];

      // 计算方向角度（0-360度）
      if (Math.abs(axis0) < 0.1 && Math.abs(axis1) < 0.1) {
        this.directionAxis0_1 = "未定义";
        return;
      }

      // 使用反正切函数计算角度，并将结果转换为度数
      let angle = Math.atan2(axis1, axis0) * (180 / Math.PI);
      angle = (angle + 360) % 360; // 确保角度在 0-360 范围内
      angle = Math.round(angle);

      // 检查死区
      if (Math.abs(axis0) > 0.1 || Math.abs(axis1) > 0.1) {
        this.directionAxis0_1 = angle + "°";
        console.log(`摇杆方向: ${angle}°, X轴: ${axis0.toFixed(2)}, Y轴: ${axis1.toFixed(2)}`);
      }
    },
    updateDirectionAxis9(axes) {
      const axis9 = axes[9];
      const roundedAxis9 = Math.round(axis9 * 100) / 100;
      if (roundedAxis9 <= -0.9) {
        this.directionAxis9 = "上";
      } else if (roundedAxis9 >= 0.0 && roundedAxis9 <= 0.2) {
        this.directionAxis9 = "下";
      } else if (roundedAxis9 >= 0.6 && roundedAxis9 <= 0.8) {
        this.directionAxis9 = "左";
      } else if (roundedAxis9 >= -0.5 && roundedAxis9 <= -0.4) {
        this.directionAxis9 = "右";
      } else {
        this.directionAxis9 = "未定义";
      }
    },
    pressKey(buttons) {
      this.buttons = [
        { name: "Left2", pressed: buttons[6].value === 1 },
        { name: "Back", pressed: buttons[8].value === 1 },
        { name: "Right Joystick Press", pressed: buttons[11].value === 1 }
      ];
    }
  }
};
</script>

<style scoped>
.control-panel {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #000033;
  color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 60px;
  background-color: #000033;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  position: relative;
}

.title-container {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 24px;
}

.title-box {
  border: 2px solid #00ffff;
  padding: 5px 15px;
  border-radius: 8px;
}

.main-content {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
}

.data-card {
  border: 1px solid #00ffff;
  border-radius: 8px;
  padding: 15px;
  background-color: rgba(0, 255, 255, 0.05);
}

.card-title {
  color: #00ffff;
  font-size: 20px;
  margin-bottom: 15px;
  text-align: center;
}

.data-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  font-size: 18px;
}

.value {
  color: #00ffff;
  font-weight: bold;
}

.button-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.button-status {
  padding: 10px;
  border: 1px solid #00ffff;
  border-radius: 5px;
  text-align: center;
  transition: all 0.3s ease;
}

.button-status.active {
  background-color: #00ffff;
  color: #000033;
}

.left-panel, .right-panel {
  width: 200px;
}

.center-panel {
  flex: 1;
}

.placeholder-div {
  width: 63px;
}

.top-right-icons {
  display: flex;
  gap: 15px;
  align-items: center;
  width: 63px;
}

.top-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}
</style>