<template>
  <div class="settings-container">
    <el-row class="popup-row">
      <el-checkbox v-model="isPopupEnabled" @change="handleCheckboxChange">
        开启弹窗
      </el-checkbox>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { GlobalWebSocket } from '../utils/useGlobalWebSocket'; // 引入类型

const isPopupEnabled = ref(false); // 控制弹窗状态
const globalWebSocket = inject<GlobalWebSocket>('globalWebSocket'); // 指定类型

// 确保 globalWebSocket 已经注入成功
if (!globalWebSocket) {
  throw new Error('globalWebSocket 注入失败');
}

// 从 localStorage 中读取勾选状态
onMounted(() => {
  const storedState = localStorage.getItem('isPopupEnabled');
  isPopupEnabled.value = storedState === 'true';
  
  // 如果已经勾选且 WebSocket 还未连接，则连接 WebSocket
  if (isPopupEnabled.value && !globalWebSocket.isWebSocketConnected.value) {
    globalWebSocket.connectWebSocket();
  }
});

// 当用户勾选或取消勾选时触发的函数
const handleCheckboxChange = () => {
  if (isPopupEnabled.value) {
    // 如果复选框被勾选，弹出确认对话框
    ElMessageBox.confirm('是否开启弹窗提示？', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        // 用户点击确认，开启 WebSocket 并保存状态
        localStorage.setItem('isPopupEnabled', 'true');
        globalWebSocket.connectWebSocket();
      })
      .catch(() => {
        // 用户取消勾选，重置状态
        isPopupEnabled.value = false;
        localStorage.setItem('isPopupEnabled', 'false');
      });
  } else {
    // 如果复选框未勾选，关闭 WebSocket
    globalWebSocket.closeWebSocket();
    localStorage.setItem('isPopupEnabled', 'false');
  }
};
</script>

<style scoped>
.settings-container {
  padding: 20px;
}
.popup-row {
  margin-bottom: 20px;
}
</style>
