/**
 * Mock 设置模块
 * 仅在 localhost 环境下生效，用于测试验证功能
 */

import { state } from './state.js';
import { refreshData } from './api.js';

// Mock 设置状态
const mockState = {
  timeMode: 'real',      // workday-morning, workday-noon, workday-evening, workday-night, weekend, real
  statusMode: 'normal',  // normal, all-free, all-charging, all-occupied, mixed
  idleMinutes: 1,        // 空闲桩的空闲时长（分钟）
};

/**
 * 初始化 Mock 设置面板
 */
export function initMockSettings() {
  // 只在 localhost 环境下显示
  const isLocalhost = window.location.hostname === 'localhost' ||
                      window.location.hostname === '127.0.0.1' ||
                      window.location.protocol === 'file:';

  const panel = document.getElementById('mock-settings-panel');
  if (panel) {
    panel.classList.toggle('hidden', !isLocalhost);
  }

  if (isLocalhost) {
    // 恢复之前保存的设置
    loadMockSettings();
    // 初始化图标
    setTimeout(() => {
      if (window.lucide) {
        window.lucide.createIcons();
      }
    }, 100);
  }
}

/**
 * 切换 Mock 设置面板展开/折叠
 */
window.toggleMockSettings = function() {
  const content = document.getElementById('mock-settings-content');
  const chevron = document.getElementById('mock-settings-chevron');

  if (content && chevron) {
    const isHidden = content.classList.contains('hidden');
    content.classList.toggle('hidden', !isHidden);
    chevron.style.transform = isHidden ? 'rotate(180deg)' : '';
  }
};

/**
 * 应用 Mock 设置
 */
window.applyMockSettings = function() {
  const timeSelect = document.getElementById('mock-time-select');
  const statusSelect = document.getElementById('mock-status-select');
  const idleSelect = document.getElementById('mock-idle-select');

  if (timeSelect) mockState.timeMode = timeSelect.value;
  if (statusSelect) mockState.statusMode = statusSelect.value;
  if (idleSelect) mockState.idleMinutes = parseInt(idleSelect.value, 10) || 0;

  // 保存设置
  saveMockSettings();

  // 触发工作日状态更新（需要在 window 上调用）
  if (window.checkNotifyTime) {
    window.checkNotifyTime();
  }

  // 刷新数据以应用新设置
  refreshData();

  // 更新状态显示
  updateMockStatusDisplay();
};

/**
 * 清空订阅
 */
window.clearSubscriptions = async function() {
  if (!confirm('确定要清空所有订阅吗？')) return;

  try {
    // 调用后端 API 清空
    const res = await fetch('/api/subscriptions', {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ clear_all: true })
    });

    const result = await res.json();
    if (result.success) {
      alert('已清空所有订阅');
      updateMockStatusDisplay();
    } else {
      alert('清空失败: ' + result.message);
    }
  } catch (e) {
    console.error('清空订阅失败:', e);
    alert('清空订阅失败');
  }
};

/**
 * 获取当前 Mock 设置
 */
export function getMockSettings() {
  return { ...mockState };
}

/**
 * 模拟当前时间
 */
export function getMockTime() {
  const now = new Date();
  const mode = mockState.timeMode;

  switch (mode) {
    case 'workday-morning':
      // 周一 10:00
      return new Date(now.getFullYear(), now.getMonth(), now.getDate() + (1 - now.getDay() + 7) % 7, 10, 0, 0);
    case 'workday-noon':
      // 周三 12:00
      return new Date(now.getFullYear(), now.getMonth(), now.getDate() + (3 - now.getDay() + 7) % 7, 12, 0, 0);
    case 'workday-evening':
      // 周五 17:00
      return new Date(now.getFullYear(), now.getMonth(), now.getDate() + (5 - now.getDay() + 7) % 7, 17, 0, 0);
    case 'workday-night':
      // 周二 20:00
      return new Date(now.getFullYear(), now.getMonth(), now.getDate() + (2 - now.getDay() + 7) % 7, 20, 0, 0);
    case 'weekend':
      // 周六 14:00
      return new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - now.getDay() + 7) % 7, 14, 0, 0);
    default:
      return now;
  }
}

/**
 * 判断是否是工作日（根据 Mock 设置）
 */
export function isMockWorkday() {
  const mode = mockState.timeMode;
  if (mode === 'weekend') return false;
  if (mode.startsWith('workday')) return true;
  // 真实时间
  const day = new Date().getDay();
  return day >= 1 && day <= 5;
}

/**
 * 判断是否是工作时间（根据 Mock 设置）
 */
export function isMockWorkHours() {
  const mode = mockState.timeMode;
  if (mode === 'weekend') return false;

  const mockHour = getMockTime().getHours();
  return mockHour >= 10 && mockHour < 19;
}

/**
 * 保存 Mock 设置到 localStorage
 */
function saveMockSettings() {
  try {
    localStorage.setItem('mock_settings', JSON.stringify(mockState));
  } catch (e) {
    console.warn('保存 Mock 设置失败:', e);
  }
}

/**
 * 从 localStorage 加载 Mock 设置
 */
function loadMockSettings() {
  try {
    const saved = localStorage.getItem('mock_settings');
    if (saved) {
      const parsed = JSON.parse(saved);
      Object.assign(mockState, parsed);

      // 更新 UI
      const timeSelect = document.getElementById('mock-time-select');
      const statusSelect = document.getElementById('mock-status-select');
      const idleSelect = document.getElementById('mock-idle-select');

      if (timeSelect) timeSelect.value = mockState.timeMode;
      if (statusSelect) statusSelect.value = mockState.statusMode;
      if (idleSelect) idleSelect.value = String(mockState.idleMinutes * 60);
    }
  } catch (e) {
    console.warn('加载 Mock 设置失败:', e);
  }
}

/**
 * 更新 Mock 状态显示
 */
async function updateMockStatusDisplay() {
  const statusEl = document.getElementById('mock-current-status');
  const freeEl = document.getElementById('mock-free-count');
  const queueEl = document.getElementById('mock-queue-count');

  if (statusEl) {
    const statusTexts = {
      'normal': '正常',
      'all-free': '全空闲',
      'all-charging': '全充电',
      'all-occupied': '全占位',
      'mixed': '混合'
    };
    statusEl.textContent = statusTexts[mockState.statusMode] || '正常';
  }

  // 更新空闲桩数和队列人数
  if (state.station) {
    if (freeEl) {
      const freeCount = state.station.connectors.filter(c => c.state?.type === 'free').length;
      freeEl.textContent = String(freeCount);
    }
  }

  // 获取队列人数
  if (queueEl) {
    try {
      const res = await fetch('/api/queue/status');
      const result = await res.json();
      if (result.success) {
        queueEl.textContent = String(result.data?.queue_count || 0);
      }
    } catch (e) {
      queueEl.textContent = isMockMode() ? '0' : '-';
    }
  }
}
