<template>
  <div class="settings-container">
    <el-row class="tip-row">

      <div class="model-row">
        <el-col :sm="24" :md="8">
          <el-card style="max-width: 480px" >
            <template #header>
              弹窗模式设置
            </template>
            <el-row>
              <el-col :sm="24" :md="24">
                <el-checkbox v-model="isInteractivePopupEnabled" @change="handleInteractiveChange">
                  开启交互式弹窗
                </el-checkbox>
              </el-col>
              <el-col :sm="24" :md="24">
                <el-checkbox v-model="isResponsivePopupEnabled" @change="handleResponsiveChange">
                  开启响应式弹窗
                </el-checkbox>
              </el-col>
            </el-row>
            <template #footer>(Tips: 不支持同时生效,关闭状态无声音)</template>
          </el-card>
        </el-col>
        <el-col :sm="24" :md="8">
          <el-card style="max-width: 480px" >
            <template #header>
              <span>弹窗队列设置</span>
            </template>
            <el-col :sm="24" :md="24" style="margin:1vh 0;">
              <el-button @click="loadNextNotification" size="small" type="primary">加载更多</el-button>
            </el-col>
            <el-col :sm="24" :md="24">
              <el-button @click="clearAllNotifications" size="small" type="danger">清空所有</el-button>
            </el-col>
            <template #footer>(Tips: 交互模式下加载/清空累积弹窗提示)</template>
          </el-card>
        </el-col>
        <el-col :sm="24" :md="8" class="audio-card">
          <el-card style="max-width: 480px" >
            <template #header>
              <span>弹窗声音设置</span>
            </template>
            <el-col :sm="24" :md="24">
              开启提示声音:&nbsp;&nbsp;&nbsp;
              <el-switch v-model="isSoundEnabled" @change="handleSoundSwitch">开启振荡器发声</el-switch>
            </el-col>
            <el-row :gutter="20">
              <el-col :sm="24" :md="5" >
                <span>音量设置: </span>
              </el-col>
              <el-col :sm="24" :md="16">
                <el-slider v-model="volume" :min="0" :max="1" :step="0.01" :disabled="isSoundEnabled"
                  @change="previewSound" size="small" />
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :sm="24" :md="5" >
                <span>音调设置: </span>
              </el-col>
              <el-col :sm="24" :md="16">
                <el-slider v-model="frequency" :min="300" :max="1200" :step="10" :disabled="isSoundEnabled"
                  @change="previewSound" size="small" />
              </el-col>
            </el-row>
            <template #footer>(Tips: 开启后锁定声音设置)</template>
          </el-card>
        </el-col>
      </div>
    </el-row>
    <el-row class="channel-row">
      <Channel />
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, inject, onMounted, onUnmounted, watch } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { GlobalWebSocket } from '@/utils/useGlobalWebSocket';
import Channel from '@/components/Channel.vue';


const isInteractivePopupEnabled = ref(false); // 交互式弹窗状态
const isResponsivePopupEnabled = ref(false); // 响应式弹窗状态

const globalWebSocket = inject<GlobalWebSocket>('globalWebSocket');
if (!globalWebSocket) throw new Error('globalWebSocket 注入失败');

const { notificationSoundParams, setNotificationSoundParams } = globalWebSocket;
const isSoundEnabled = ref(notificationSoundParams.isSoundEnabled);
const volume = ref(notificationSoundParams.volume);
const frequency = ref(notificationSoundParams.frequency);
let audioContext: AudioContext | null = null;
const loadNextNotification = () => {
  if (globalWebSocket) globalWebSocket.loadNextNotification();
};

const clearAllNotifications = () => {
  if (globalWebSocket) globalWebSocket.clearAllNotifications();
};



// 初始化时加载弹窗模式状态
onMounted(() => {
  isInteractivePopupEnabled.value = localStorage.getItem('isInteractivePopupEnabled') === 'true';
  isResponsivePopupEnabled.value = localStorage.getItem('isResponsivePopupEnabled') === 'true';
  isSoundEnabled.value = notificationSoundParams.isSoundEnabled;
  volume.value = notificationSoundParams.volume;
  frequency.value = notificationSoundParams.frequency;
  updateWebSocketConnection();
});

const handleSoundSwitch = () => {
  setNotificationSoundParams({
    isSoundEnabled: isSoundEnabled.value,
    volume: volume.value,
    frequency: frequency.value,
  });
  ElMessage.success(isSoundEnabled.value ? '提示音已开启，当前参数已锁定' : '提示音已关闭');
};



// 预览提示音
const previewSound = () => {
  if (audioContext) {
    audioContext.close();
  }
  audioContext = new (window.AudioContext || window.webkitAudioContext)();
  const oscillator = audioContext.createOscillator();
  const gainNode = audioContext.createGain();

  oscillator.type = 'triangle';
  oscillator.frequency.setValueAtTime(frequency.value, audioContext.currentTime);
  gainNode.gain.setValueAtTime(volume.value, audioContext.currentTime);

  oscillator.connect(gainNode);
  gainNode.connect(audioContext.destination);

  oscillator.start();
  setTimeout(() => {
    oscillator.stop();
    audioContext?.close();
    audioContext = null;
  }, 300); // 持续播放 300ms
};

watch([isSoundEnabled, volume, frequency], () => {
  setNotificationSoundParams({
    isSoundEnabled: isSoundEnabled.value,
    volume: volume.value,
    frequency: frequency.value,
  });
});





// const handleInteractiveChange = () => {
//   if (isInteractivePopupEnabled.value) {
//     isResponsivePopupEnabled.value = false; 
//     localStorage.setItem('isResponsivePopupEnabled', 'false');
//   }
//   localStorage.setItem('isInteractivePopupEnabled', String(isInteractivePopupEnabled.value));
//   updateWebSocketConnection();
// };

// const handleResponsiveChange = () => {
//   if (isResponsivePopupEnabled.value) {
//     isInteractivePopupEnabled.value = false;
//     localStorage.setItem('isInteractivePopupEnabled', 'false');
//   }
//   localStorage.setItem('isResponsivePopupEnabled', String(isResponsivePopupEnabled.value));
//   updateWebSocketConnection();
// };

const handleInteractiveChange = () => {
  if (isInteractivePopupEnabled.value) {
    ElMessageBox.confirm('是否开启交互式弹窗提示？', '确认提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        isResponsivePopupEnabled.value = false;
        localStorage.setItem('isResponsivePopupEnabled', 'false');

        localStorage.setItem('isInteractivePopupEnabled', 'true');
        updateWebSocketConnection();
      })
      .catch(() => {
        isInteractivePopupEnabled.value = false;
      });
  } else {
    ElMessageBox.confirm('是否关闭交互式弹窗？', '确认提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        localStorage.setItem('isInteractivePopupEnabled', 'false');
        updateWebSocketConnection();
      })
      .catch(() => {
        isInteractivePopupEnabled.value = true;
      });
  }
};


const handleResponsiveChange = () => {
  if (isResponsivePopupEnabled.value) {
    ElMessageBox.confirm('是否开启响应式弹窗提示？', '确认提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        isInteractivePopupEnabled.value = false;
        localStorage.setItem('isInteractivePopupEnabled', 'false');
        localStorage.setItem('isResponsivePopupEnabled', 'true');
        updateWebSocketConnection();
      })
      .catch(() => {
        isResponsivePopupEnabled.value = false;
      });
  } else {
    ElMessageBox.confirm('是否关闭响应式弹窗？', '确认提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    })
      .then(() => {
        localStorage.setItem('isResponsivePopupEnabled', 'false');
        updateWebSocketConnection();
      })
      .catch(() => {
        isResponsivePopupEnabled.value = true;
      });
  }
};

// 根据开关状态更新 WebSocket 连接
const updateWebSocketConnection = () => {
  if (isInteractivePopupEnabled.value || isResponsivePopupEnabled.value) {
    globalWebSocket.connectWebSocket();
  } else {
    globalWebSocket.closeWebSocket();
  }
};

onUnmounted(() => {
  audioContext?.close();
});
</script>

<style scoped>
.settings-container {
  display: flex;
  flex-direction: column;
  background-color: #F1F1F1;
  width: 100%;
  height: 100%;
}

.tip-row {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  height: 20vh;
  width: 80vw;
  padding: 1vh 1vw;
  margin: 1vh 2vw;
  background-color: #001529;
  border-radius: 8px;
  color: white;
}

.tip-row .el-card{
  border: none !important;
  color: white;
}

.tip-row .el-card .el-checkbox{
  color: white;
}

::v-deep .tip-row .el-card__header {
  background-color: #001529;
  /* height: 3vh; */
  padding: 1vh 0 1vh 1vw;
  display: flex;
  font-size: 18px;
  font-weight: bold;
  border-bottom: none !important;
}

::v-deep .tip-row .el-card__body {
  background-color: #001529;
  height: 12vh;
  font-size: 16px;
  /* border: 0px ; */
}

::v-deep .tip-row .el-card .is-always-shadow{
  color: aqua;
  
}

::v-deep .tip-row .el-card__footer {
  background-color: #001529;

  /* height: 3vh; */
  padding: 0 1vw 0 0;
  display: flex;
  justify-content: end;
  font-size: 14px;
  font-weight: bold;
  border-top: none !important;
  color: #a8a3a3;
}


.model-row {
  display: flex;
  flex-direction: row;
}

::v-deep .audio-card .el-card__body {
  padding: 1vh 1vw;
  /* background-color: aqua; */
}


.channel-row {
  margin: 1vh 2vw;
  width: 80vw;
  height: 70vh;
  background-color: #001529;
  border-radius: 8px;
}
</style>
